diff options
Diffstat (limited to 'openecomp-be/lib')
501 files changed, 19634 insertions, 6219 deletions
diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java index de33804dff..565e60e427 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/Messages.java @@ -39,6 +39,8 @@ public enum Messages { FAILED_TO_TRANSLATE_ZIP_FILE("Failed to translate zip file"), ZIP_NOT_EXIST("Zip file doesn't exist"), + PERMISSIONS_ERROR("Permissions Error. The user does not have permission to perform this action."), + ZIP_SHOULD_NOT_CONTAIN_FOLDERS("Zip file should not contain folders"), VES_ZIP_SHOULD_CONTAIN_YML_ONLY( "Wrong VES EVENT Artifact was uploaded - all files contained in Artifact must be YAML files" + @@ -148,7 +150,11 @@ public enum Messages { + "Contrail 2 resources can be found in %s. Contrail 3 resources can be found in %s"), CONTRAIL_VM_TYPE_NAME_NOT_ALIGNED_WITH_NAMING_CONVENSION( "Service Template naming convention in Image and Flavor " - + "properties is not consistent in Resource, Resource ID %s"); + + "properties is not consistent in Resource, Resource ID %s"), + + /* Notifications */ + FAILED_TO_MARK_NOTIFICATION_AS_READ("Failed to mark notifications as read"), + FAILED_TO_UPDATE_LAST_SEEN_NOTIFICATION("Failed to update last seen notification for user %s"); private String errorMessage; diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcRuntimeException.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcRuntimeException.java new file mode 100644 index 0000000000..6e41d5888d --- /dev/null +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/errors/SdcRuntimeException.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.common.errors; + +public class SdcRuntimeException extends RuntimeException { + public SdcRuntimeException() { + } + + public SdcRuntimeException(String message) { + super(message); + } + + public SdcRuntimeException(String message, Throwable cause) { + super(message, cause); + } + + public SdcRuntimeException(Throwable cause) { + super(cause); + } + + public SdcRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/SdcCommon.java b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/SdcCommon.java index 24da8363c1..9de0e7b0e1 100644 --- a/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/SdcCommon.java +++ b/openecomp-be/lib/openecomp-common-lib/src/main/java/org/openecomp/sdc/common/utils/SdcCommon.java @@ -33,6 +33,7 @@ public class SdcCommon { public static final String PARENT = "parent"; public static final String VSP_ID = "vspId"; + public static final String VLM_ID = "vlmId"; public static final String VERSION = "version"; public static final String USER = "user"; } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/pom.xml b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/pom.xml new file mode 100644 index 0000000000..413cae7933 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/pom.xml @@ -0,0 +1,38 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-conflict-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>..</relativePath> + </parent> + + <artifactId>openecomp-conflict-api</artifactId> + + + <dependencies> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-facade-core</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-facade-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-versioning-api</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> + + + +</project>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandler.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandler.java new file mode 100644 index 0000000000..189e4cedd9 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandler.java @@ -0,0 +1,27 @@ +package org.openecomp.conflicts; + +import org.openecomp.conflicts.types.Conflict; +import org.openecomp.conflicts.types.ConflictResolution; +import org.openecomp.conflicts.types.ItemVersionConflict; +import org.openecomp.sdc.versioning.dao.types.Version; + +import java.util.Optional; + +public interface ItemMergeHandler { + + boolean isConflicted(String itemId, Version version); + + void finalizeMerge(String itemId, Version version); + + void postListConflicts(String itemId, Version version, ItemVersionConflict conflicts); + + Optional<Conflict> getConflict(String itemId, Version version, String conflictId); + + void postGetConflict(String itemId, Version version, Conflict conflict); + + void preResolveConflict(String itemId, Version version, String conflictId, + ConflictResolution resolution); + + boolean resolveConflict(String itemId, Version version, String conflictId, + ConflictResolution resolution); +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactory.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactory.java new file mode 100644 index 0000000000..8fb0a48870 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.conflicts; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +import java.util.Optional; + +public abstract class ItemMergeHandlerFactory + extends AbstractComponentFactory<ItemMergeHandler> { + + public static ItemMergeHandlerFactory getInstance() { + return AbstractFactory.getInstance(ItemMergeHandlerFactory.class); + } + + public abstract Optional<ItemMergeHandler> createInterface(String itemId); +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDao.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDao.java new file mode 100644 index 0000000000..273233a12c --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDao.java @@ -0,0 +1,18 @@ +package org.openecomp.conflicts.dao; + +import org.openecomp.conflicts.types.Conflict; +import org.openecomp.conflicts.types.ConflictResolution; +import org.openecomp.conflicts.types.ItemVersionConflict; +import org.openecomp.sdc.versioning.dao.types.Version; + +public interface ConflictsDao { + + boolean isConflicted(String itemId, Version version); + + ItemVersionConflict getConflict(String itemId, Version version); + + Conflict getConflict(String itemId, Version version, String conflictId); + + void resolveConflict(String itemId, Version version, String conflictId, + ConflictResolution conflictResolution); +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/UploadDataDaoFactory.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDaoFactory.java index 9654551f8f..e4c88d6279 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/UploadDataDaoFactory.java +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/dao/ConflictsDaoFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,14 +18,15 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.sdc.vendorsoftwareproduct.dao; +package org.openecomp.conflicts.dao; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; -public abstract class UploadDataDaoFactory extends AbstractComponentFactory<UploadDataDao> { +public abstract class ConflictsDaoFactory + extends AbstractComponentFactory<ConflictsDao> { - public static UploadDataDaoFactory getInstance() { - return AbstractFactory.getInstance(UploadDataDaoFactory.class); + public static ConflictsDaoFactory getInstance() { + return AbstractFactory.getInstance(ConflictsDaoFactory.class); } } diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Conflict.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Conflict.java new file mode 100644 index 0000000000..bc324af1dd --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Conflict.java @@ -0,0 +1,30 @@ +package org.openecomp.conflicts.types; + +import org.openecomp.sdc.datatypes.model.ElementType; + +public class Conflict<T> extends ConflictInfo { + private T yours; + private T theirs; + + public Conflict(String id, ElementType type, String name) { + super(id, type, name); + } + + public T getYours() { + return yours; + } + + public void setYours(T yours) { + this.yours = yours; + } + + public T getTheirs() { + return theirs; + } + + public void setTheirs(T theirs) { + this.theirs = theirs; + } + + +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictInfo.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictInfo.java new file mode 100644 index 0000000000..ff58f00121 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictInfo.java @@ -0,0 +1,39 @@ +package org.openecomp.conflicts.types; + +import org.openecomp.sdc.datatypes.model.ElementType; + +public class ConflictInfo { + private String id; + private ElementType type; + private String name; + + public ConflictInfo(String id, ElementType type, String name) { + this.id = id; + this.type = type; + this.name = name; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public ElementType getType() { + return type; + } + + public void setType(ElementType type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictResolution.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictResolution.java new file mode 100644 index 0000000000..961f9080d9 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ConflictResolution.java @@ -0,0 +1,32 @@ +package org.openecomp.conflicts.types; + +import java.util.Map; + +public class ConflictResolution { + private Resolution resolution; + // sits in lower level... + private Map<String, Object> otherResolution; + + public ConflictResolution() { + } + + public ConflictResolution(Resolution resolution) { + this.resolution = resolution; + } + + public Resolution getResolution() { + return resolution; + } + + public void setResolution(Resolution resolution) { + this.resolution = resolution; + } + + public Map<String, Object> getOtherResolution() { + return otherResolution; + } + + public void setOtherResolution(Map<String, Object> otherResolution) { + this.otherResolution = otherResolution; + } +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ItemVersionConflict.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ItemVersionConflict.java new file mode 100644 index 0000000000..a4749f3990 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/ItemVersionConflict.java @@ -0,0 +1,31 @@ +package org.openecomp.conflicts.types; + +import org.openecomp.sdc.versioning.dao.types.Version; + +import java.util.ArrayList; +import java.util.Collection; + +public class ItemVersionConflict { + private Conflict<Version> versionConflict; + private Collection<ConflictInfo> elementConflicts = new ArrayList<>(); + + public Conflict<Version> getVersionConflict() { + return versionConflict; + } + + public void setVersionConflict(Conflict<Version> versionConflict) { + this.versionConflict = versionConflict; + } + + public Collection<ConflictInfo> getElementConflicts() { + return elementConflicts; + } + + public void setElementConflicts(Collection<ConflictInfo> elementConflicts) { + this.elementConflicts = elementConflicts; + } + + public void addElementConflictInfo(ConflictInfo conflictInfo) { + elementConflicts.add(conflictInfo); + } +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Resolution.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Resolution.java new file mode 100644 index 0000000000..2222f81c70 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-api/src/main/java/org/openecomp/conflicts/types/Resolution.java @@ -0,0 +1,5 @@ +package org.openecomp.conflicts.types; + +public enum Resolution { + THEIRS,YOURS,OTHER +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/pom.xml b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/pom.xml new file mode 100644 index 0000000000..ddeb03df53 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/pom.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-conflict-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>..</relativePath> + </parent> + + <artifactId>openecomp-conflict-core</artifactId> + <dependencies> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-conflict-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-zusammen-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-vendor-software-product-core</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-vendor-license-core</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> +</project>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactoryImpl.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactoryImpl.java new file mode 100644 index 0000000000..4c981acee4 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/ItemMergeHandlerFactoryImpl.java @@ -0,0 +1,40 @@ +package org.openecomp.conflicts; + +import org.openecomp.conflicts.dao.ConflictsDaoFactory; +import org.openecomp.conflicts.impl.VspMergeHandler; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.model.ItemType; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDaoFactory; +import org.openecomp.sdc.versioning.ItemManagerFactory; +import org.openecomp.sdc.versioning.errors.EntityNotExistErrorBuilder; +import org.openecomp.sdc.versioning.types.Item; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class ItemMergeHandlerFactoryImpl extends ItemMergeHandlerFactory { + // TODO: 11/1/2017 read this map from configuration, move Vsp merge handler to vsp lib, rearrange lib deps + private static final Map<ItemType, ItemMergeHandler> MERGE_HANDLER_BY_ITEM_TYPE = + new HashMap<>(); + + static { + MERGE_HANDLER_BY_ITEM_TYPE.put(ItemType.vsp, + new VspMergeHandler(ConflictsDaoFactory.getInstance().createInterface(), + VspMergeDaoFactory.getInstance().createInterface())); + } + + @Override + public Optional<ItemMergeHandler> createInterface(String itemId) { + Item item = ItemManagerFactory.getInstance().createInterface().get(itemId); + if (item == null) { + throw new CoreException(new EntityNotExistErrorBuilder("", itemId).build()); + } + return Optional.ofNullable(MERGE_HANDLER_BY_ITEM_TYPE.get(ItemType.valueOf(item.getType()))); + } + + @Override + public ItemMergeHandler createInterface() { + return null; // call the one with the item id arg + } +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoFactoryImpl.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoFactoryImpl.java new file mode 100644 index 0000000000..7cb3598b9d --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoFactoryImpl.java @@ -0,0 +1,17 @@ +package org.openecomp.conflicts.dao.impl.zusammen; + + +import org.openecomp.conflicts.dao.ConflictsDao; +import org.openecomp.conflicts.dao.ConflictsDaoFactory; +import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; + +public class ConflictsDaoFactoryImpl extends ConflictsDaoFactory { + + private static final ConflictsDao INSTANCE = new + ConflictsDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public ConflictsDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoImpl.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoImpl.java new file mode 100644 index 0000000000..eac1be3b8e --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ConflictsDaoImpl.java @@ -0,0 +1,175 @@ +package org.openecomp.conflicts.dao.impl.zusammen; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Item; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.Resolution; +import org.openecomp.conflicts.dao.ConflictsDao; +import org.openecomp.conflicts.types.Conflict; +import org.openecomp.conflicts.types.ConflictResolution; +import org.openecomp.conflicts.types.ItemVersionConflict; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.sdc.datatypes.model.ElementType; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToEntitlementPoolConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToFeatureGroupConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLicenseAgreementConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLicenseKeyGroupConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLimitConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToVLMGeneralConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentDependencyModelConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToCompositionEntityConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComputeConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToImageConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToMonitoringUploadMapConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNetworkConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNicConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToOrchestrationTemplateCandidateMapConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToServiceModelMapConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToVSPGeneralConvertor; +import org.openecomp.sdc.versioning.dao.types.Version; + +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + +public class ConflictsDaoImpl implements ConflictsDao { + private final ZusammenAdaptor zusammenAdaptor; + + public ConflictsDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } + + @Override + public boolean isConflicted(String itemId, Version version) { + com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict itemVersionConflict = + zusammenAdaptor + .getVersionConflict(createSessionContext(), new Id(itemId), new Id(version.getId())); + return !(itemVersionConflict == null + || (itemVersionConflict.getVersionDataConflict() == null + && itemVersionConflict.getElementConflictInfos().isEmpty())); + } + + @Override + public ItemVersionConflict getConflict(String itemId, Version version) { + return new ItemVersionConflictConvertorFromZusammen().convert(itemId, version, + zusammenAdaptor + .getVersionConflict(createSessionContext(), new Id(itemId), new Id(version.getId()))); + } + + @Override + public Conflict getConflict(String itemId, Version version, String conflictId) { + return zusammenAdaptor.getElementConflict(createSessionContext(), + new ElementContext(new Id(itemId), new Id(version.getId())), new Id(conflictId)) + .map(elementConflict -> convertElementConflict(conflictId, elementConflict)) + .orElse(null); + } + + @Override + public void resolveConflict(String itemId, Version version, String conflictId, + ConflictResolution conflictResolution) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(new Id(itemId), new Id(version.getId())); + + // TODO: 7/31/2017 when 'OTHER' resolution will be supported - populate zusammen element with it + zusammenAdaptor.resolveElementConflict(context, elementContext, + buildElement(new Id(conflictId), null), + Resolution.valueOf(conflictResolution.getResolution().name())); + } + + private Conflict convertElementConflict(String conflictId, ElementConflict elementConflict) { + Element element = elementConflict.getLocalElement() == null + ? elementConflict.getRemoteElement() + : elementConflict.getLocalElement(); + ElementType elementType = ElementConvertor.getElementType(element); + + Conflict conflict = + new Conflict(conflictId, elementType, ElementConvertor.getElementName(element)); + ElementConvertor convertor = getConvertor(elementType); + if (elementConflict.getLocalElement() != null) { + conflict.setYours(convertor.convert(elementConflict.getLocalElement())); + } + if (elementConflict.getRemoteElement() != null) { + conflict.setTheirs(convertor.convert(elementConflict.getRemoteElement())); + } + return conflict; + } + + private ElementConvertor getConvertor(ElementType type) { + switch (type) { + case VendorSoftwareProduct: + return new ElementToVSPGeneralConvertor(); + case Process: + return new ElementToProcessConvertor(); + case Nic: + return new ElementToNicConvertor(); + case Network: + return new ElementToNetworkConvertor(); + case SNMP_POLL: + case SNMP_TRAP: + case VES_EVENTS: + return new ElementToMonitoringUploadMapConvertor(); + case Image: + return new ElementToImageConvertor(); + case Compute: + return new ElementToComputeConvertor(); + case Component: + return new ElementToComponentConvertor(); + case ComponentDependencies: + return new ElementToComponentDependencyModelConvertor(); + case VendorLicenseModel: + return new ElementToVLMGeneralConvertor(); + case LicenseAgreement: + return new ElementToLicenseAgreementConvertor(); + case FeatureGroup: + return new ElementToFeatureGroupConvertor(); + case LicenseKeyGroup: + return new ElementToLicenseKeyGroupConvertor(); + case EntitlementPool: + return new ElementToEntitlementPoolConvertor(); + case Limit: + return new ElementToLimitConvertor(); + case OrchestrationTemplateCandidate: + return new ElementToOrchestrationTemplateCandidateMapConvertor(); + case ServiceModel: + return new ElementToServiceModelMapConvertor(); + case VSPQuestionnaire: + case ImageQuestionnaire: + case ComponentQuestionnaire: + case ComputeQuestionnaire: + case NicQuestionnaire: + return new ElementToCompositionEntityConvertor(); + default: + return new EchoConvertor(); + } + } + + public static class EchoConvertor extends ElementConvertor { + + @Override + public Object convert(Element element) { + return element; + } + + @Override + public Object convert(Item item) { + return item; + } + + @Override + public Object convert(ElementInfo elementInfo) { + return elementInfo; + } + + @Override + public Object convert(ItemVersion itemVersion) { + return null; + } + } +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ItemVersionConflictConvertorFromZusammen.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ItemVersionConflictConvertorFromZusammen.java new file mode 100644 index 0000000000..4dffaf8231 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/dao/impl/zusammen/ItemVersionConflictConvertorFromZusammen.java @@ -0,0 +1,73 @@ +package org.openecomp.conflicts.dao.impl.zusammen; + + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflictInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict; +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionDataConflict; +import org.openecomp.conflicts.types.Conflict; +import org.openecomp.conflicts.types.ConflictInfo; +import org.openecomp.sdc.datatypes.model.ElementType; +import org.openecomp.sdc.versioning.dao.impl.zusammen.convertor.ItemVersionToVersionConvertor; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; + +import java.util.stream.Collectors; + +public class ItemVersionConflictConvertorFromZusammen { + public org.openecomp.conflicts.types.ItemVersionConflict convert(String itemId, Version version, + ItemVersionConflict source) { + org.openecomp.conflicts.types.ItemVersionConflict target = + new org.openecomp.conflicts.types.ItemVersionConflict(); + + target.setVersionConflict( + convertVersionDataConflict(itemId, version, source.getVersionDataConflict())); + target.setElementConflicts(source.getElementConflictInfos().stream() + .map(this::convertElementConflictInfo) + .collect(Collectors.toList())); + + return target; + } + + + private Conflict<Version> convertVersionDataConflict(String itemId, Version version, + ItemVersionDataConflict versionDataConflict) { + if (versionDataConflict == null) { + return null; + } + + Conflict<Version> conflict = + new Conflict<>(version.getId(), ElementType.itemVersion, null); + + ItemVersionToVersionConvertor convertor = new ItemVersionToVersionConvertor(); + conflict.setYours(convertor.convert( + getItemVersion(version.getId(), versionDataConflict.getLocalData()))); + conflict.setTheirs(convertor.convert( + getItemVersion(version.getId(), versionDataConflict.getRemoteData()))); + return conflict; + } + + private ItemVersion getItemVersion(String versionId, ItemVersionData versionData) { + if (versionData == null) { + return null; + } + ItemVersion itemVersion = new ItemVersion(); + itemVersion.setId(new Id(versionId)); + itemVersion.setData(versionData); + return itemVersion; + } + + private ConflictInfo convertElementConflictInfo(ElementConflictInfo elementConflictInfo) { + ElementInfo elementInfo = elementConflictInfo.getLocalElementInfo() == null + ? elementConflictInfo.getRemoteElementInfo() + : elementConflictInfo.getLocalElementInfo(); + + return new ConflictInfo(elementInfo.getId().getValue(), + ElementType + .valueOf(elementInfo.getInfo().getProperty(ElementPropertyName.elementType.name())), + elementInfo.getInfo().getName()); + } +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/impl/VspMergeHandler.java b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/impl/VspMergeHandler.java new file mode 100644 index 0000000000..f7d0bca392 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/java/org/openecomp/conflicts/impl/VspMergeHandler.java @@ -0,0 +1,204 @@ +package org.openecomp.conflicts.impl; + +import org.openecomp.conflicts.ItemMergeHandler; +import org.openecomp.conflicts.dao.ConflictsDao; +import org.openecomp.conflicts.types.Conflict; +import org.openecomp.conflicts.types.ConflictInfo; +import org.openecomp.conflicts.types.ConflictResolution; +import org.openecomp.conflicts.types.ItemVersionConflict; +import org.openecomp.conflicts.types.Resolution; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.datatypes.model.ElementType; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDao; +import org.openecomp.sdc.versioning.dao.types.Version; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.openecomp.sdc.datatypes.model.ElementType.NetworkPackage; +import static org.openecomp.sdc.datatypes.model.ElementType.OrchestrationTemplate; +import static org.openecomp.sdc.datatypes.model.ElementType.OrchestrationTemplateCandidate; +import static org.openecomp.sdc.datatypes.model.ElementType.OrchestrationTemplateCandidateContent; +import static org.openecomp.sdc.datatypes.model.ElementType.OrchestrationTemplateValidationData; +import static org.openecomp.sdc.datatypes.model.ElementType.VspModel; + +public class VspMergeHandler implements ItemMergeHandler { + + private static final String VSP_MODEL_CONFLICT_ID = "vspModelConflictId"; + private static final String ELEMENT_CONFLICT_NOT_EXIST_ERR_ID = "ELEMENT_CONFLICT_NOT_EXIST"; + private static final String ELEMENT_CONFLICT_NOT_EXISTS_MSG = + "Item Id %s, version Id %s, element conflict with Id %s does not exists."; + private static final Set<ElementType> FILTERED_OUT_TYPES = Stream + .of(OrchestrationTemplateCandidateContent, OrchestrationTemplateValidationData) + .collect(Collectors.toSet()); + private static final Map<ElementType, Set<ElementType>> ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES = + new HashMap<>(); + + static { + ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES.put(OrchestrationTemplateCandidate, + Collections.singleton(OrchestrationTemplateCandidateContent)); + ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES.put(OrchestrationTemplate, + Collections.singleton(OrchestrationTemplateValidationData)); + } + + private ConflictsDao conflictsDao; + private VspMergeDao vspMergeDao; + + public VspMergeHandler(ConflictsDao conflictsDao, VspMergeDao vspMergeDao) { + this.conflictsDao = conflictsDao; + this.vspMergeDao = vspMergeDao; + } + + @Override + public boolean isConflicted(String itemId, Version version) { + return vspMergeDao.isVspModelConflicted(itemId, version); + } + + @Override + public void finalizeMerge(String itemId, Version version) { + if (!conflictsDao.isConflicted(itemId, version)) { + vspMergeDao.applyVspModelConflictResolution(itemId, version); + } + } + + @Override + public void postListConflicts(String itemId, Version version, ItemVersionConflict conflicts) { + List<ConflictInfo> elementConflicts = new ArrayList<>(); + + boolean vspModelConflicted = false; + for (ConflictInfo elementConflict : conflicts.getElementConflicts()) { + if (elementConflict.getType() == VspModel) { + elementConflicts.add( + new ConflictInfo(elementConflict.getId(), NetworkPackage, NetworkPackage.name())); + vspModelConflicted = true; + continue; + } + if (!FILTERED_OUT_TYPES.contains(elementConflict.getType())) { + elementConflicts.add(elementConflict); + } + } + + if (!vspModelConflicted && vspMergeDao.isVspModelConflicted(itemId, version)) { + elementConflicts + .add(new ConflictInfo(VSP_MODEL_CONFLICT_ID, NetworkPackage, NetworkPackage.name())); + } + + conflicts.setElementConflicts(elementConflicts); + } + + @Override + public Optional<Conflict> getConflict(String itemId, Version version, String conflictId) { + return VSP_MODEL_CONFLICT_ID.equals(conflictId) + ? Optional.of(buildVspModelConflict(conflictId)) + : Optional.empty(); + } + + @Override + public void postGetConflict(String itemId, Version version, Conflict conflict) { + if (conflict.getType() == VspModel) { + Conflict vspModelConflict = buildVspModelConflict(null); + conflict.setType(vspModelConflict.getType()); + conflict.setName(vspModelConflict.getName()); + conflict.setYours(vspModelConflict.getYours()); + conflict.setTheirs(vspModelConflict.getTheirs()); + } + } + + @Override + public void preResolveConflict(String itemId, Version version, String conflictId, + ConflictResolution resolution) { + if (VSP_MODEL_CONFLICT_ID.equals(conflictId)) { + return; + } + resolveDependantConflicts(itemId, version, conflictId, resolution); + } + + @Override + public boolean resolveConflict(String itemId, Version version, String conflictId, + ConflictResolution resolution) { + if (VSP_MODEL_CONFLICT_ID.equals(conflictId)) { + vspMergeDao.updateVspModelConflictResolution(itemId, version, + com.amdocs.zusammen.datatypes.item.Resolution.valueOf(resolution.getResolution().name())); + return true; + } + Conflict conflict = conflictsDao.getConflict(itemId, version, conflictId); + if (conflict == null) { + throw getConflictNotExistException(itemId, version, conflictId); + } + if (conflict.getType() == VspModel) { + vspMergeDao.updateVspModelConflictResolution(itemId, version, + com.amdocs.zusammen.datatypes.item.Resolution.valueOf(resolution.getResolution().name())); + + conflictsDao.resolveConflict(itemId, version, conflictId, new ConflictResolution( + conflict.getTheirs() == null ? Resolution.YOURS : Resolution.THEIRS)); + return true; + } + return false; + } + + private void resolveDependantConflicts(String itemId, Version version, String conflictId, + ConflictResolution resolution) { + ItemVersionConflict conflicts = conflictsDao.getConflict(itemId, version); + + Set<ElementType> conflictDependantTypes = + ELEMENT_TYPE_TO_CONFLICT_DEPENDANT_TYPES + .get(findConflictById(conflicts, conflictId).getType()); + + if (conflictDependantTypes == null) { + return; + } + + findConflictsByTypes(conflicts, conflictDependantTypes) + .forEach(dependantConflict -> + conflictsDao.resolveConflict(itemId, version, dependantConflict.getId(), resolution)); + } + + private ConflictInfo findConflictById(ItemVersionConflict versionConflicts, + String conflictId) { + return versionConflicts.getElementConflicts().stream() + .filter(elementConflict -> conflictId.equals(elementConflict.getId())) + .findFirst() + .orElseThrow(() -> new IllegalStateException( + String.format("Conflict Id %s does not exist on conflicts list", conflictId))); + } + + private Collection<ConflictInfo> findConflictsByTypes(ItemVersionConflict versionConflicts, + Set<ElementType> elementTypes) { + return versionConflicts.getElementConflicts().stream() + .filter(elementConflict -> elementTypes.contains(elementConflict.getType())) + .collect(Collectors.toList()); + } + + private Conflict buildVspModelConflict(String conflictId) { + Conflict conflict = new Conflict(conflictId, NetworkPackage, NetworkPackage.name()); + + Map<String, String> yours = new HashMap<>(); + yours.put("File", "Local (Me)"); + conflict.setYours(yours); + + Map<String, String> theirs = new HashMap<>(); + theirs.put("File", "Last Committed"); + conflict.setTheirs(theirs); + return conflict; + } + + private CoreException getConflictNotExistException(String itemId, Version version, + String conflictId) { + return new CoreException(new ErrorCode.ErrorCodeBuilder() + .withCategory(ErrorCategory.APPLICATION) + .withId(ELEMENT_CONFLICT_NOT_EXIST_ERR_ID) + .withMessage( + String.format(ELEMENT_CONFLICT_NOT_EXISTS_MSG, itemId, version.getId(), conflictId)) + .build()); + } +} diff --git a/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..ec9f3703d1 --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/openecomp-conflict-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,4 @@ +{ + "org.openecomp.conflicts.ItemMergeHandlerFactory": "org.openecomp.conflicts.ItemMergeHandlerFactoryImpl", + "org.openecomp.conflicts.dao.ConflictsDaoFactory": "org.openecomp.conflicts.dao.impl.zusammen.ConflictsDaoFactoryImpl" +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-conflict-lib/pom.xml b/openecomp-be/lib/openecomp-conflict-lib/pom.xml new file mode 100644 index 0000000000..de6bcd6fef --- /dev/null +++ b/openecomp-be/lib/openecomp-conflict-lib/pom.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>..</relativePath> + </parent> + + <artifactId>openecomp-conflict-lib</artifactId> + <packaging>pom</packaging> + <modules> + <module>openecomp-conflict-api</module> + <module>openecomp-conflict-core</module> + </modules> +</project>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java index 6b5c5f94c4..e3d87656ad 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-config-lib/src/test/java/org/openecomp/sdc/applicationconfig/dao/ApplicationConfigImplDaoTest.java @@ -20,23 +20,6 @@ package org.openecomp.sdc.applicationconfig.dao; -import org.openecomp.core.utilities.applicationconfig.ApplicationConfig; -import org.openecomp.core.utilities.applicationconfig.ApplicationConfigFactory; -import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDao; -import org.openecomp.core.utilities.applicationconfig.dao.ApplicationConfigDaoFactory; -import org.openecomp.core.utilities.applicationconfig.dao.type.ApplicationConfigEntity; -import org.openecomp.core.utilities.applicationconfig.type.ConfigurationData; -import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCategory; -import org.openecomp.sdc.common.errors.ErrorCode; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - - public class ApplicationConfigImplDaoTest { /* diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java index 9353de662b..7b53f3416a 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-facade-lib/openecomp-facade-api/src/main/java/org/openecomp/core/factory/impl/AbstractFactoryBase.java @@ -21,9 +21,6 @@ package org.openecomp.core.factory.impl; -import static org.openecomp.core.utilities.CommonMethods.isEmpty; -import static org.openecomp.core.utilities.CommonMethods.newInstance; - import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -32,6 +29,9 @@ import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import static org.openecomp.core.utilities.CommonMethods.isEmpty; +import static org.openecomp.core.utilities.CommonMethods.newInstance; + public abstract class AbstractFactoryBase { /** diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java index dce34a1c96..15e9ceeee7 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-api/src/main/java/org/openecomp/core/util/UniqueValueUtil.java @@ -32,7 +32,7 @@ import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import java.util.Optional; public class UniqueValueUtil { - public static final String UNIQUE_VALUE_VIOLATION = "UNIQUE_VALUE_VIOLATION"; + private static final String UNIQUE_VALUE_VIOLATION = "UNIQUE_VALUE_VIOLATION"; private static final String UNIQUE_VALUE_VIOLATION_MSG = "%s with the value '%s' already exists."; private static final UniqueValueDao uniqueValueDao = @@ -46,9 +46,7 @@ public class UniqueValueUtil { * @param uniqueCombination the unique combination */ public static void createUniqueValue(String type, String... uniqueCombination) { - - - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Optional<String> value = formatValue(uniqueCombination); if (!value.isPresent()) { @@ -57,7 +55,7 @@ public class UniqueValueUtil { validateUniqueValue(type, value.get(), uniqueCombination); uniqueValueDao.create(new UniqueValueEntity(type, value.get())); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } /** @@ -69,7 +67,7 @@ public class UniqueValueUtil { public static void deleteUniqueValue(String type, String... uniqueCombination) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Optional<String> value = formatValue(uniqueCombination); if (!value.isPresent()) { @@ -77,7 +75,7 @@ public class UniqueValueUtil { } uniqueValueDao.delete(new UniqueValueEntity(type, value.get())); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } /** @@ -92,17 +90,14 @@ public class UniqueValueUtil { String... uniqueContext) { - mdcDataDebugMessage.debugEntryMessage(null, null); - - boolean nonEqual = (newValue != null) && (oldValue != null) - && !newValue.toLowerCase().equals(oldValue.toLowerCase()); + mdcDataDebugMessage.debugEntryMessage(null); - if (nonEqual || newValue == null || oldValue == null) { + if (newValue == null || oldValue == null || !newValue.equalsIgnoreCase(oldValue)) { createUniqueValue(type, CommonMethods.concat(uniqueContext, new String[]{newValue})); deleteUniqueValue(type, CommonMethods.concat(uniqueContext, new String[]{oldValue})); } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } /** @@ -112,7 +107,7 @@ public class UniqueValueUtil { * @param uniqueCombination the unique combination */ public static void validateUniqueValue(String type, String... uniqueCombination) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Optional<String> value = formatValue(uniqueCombination); if (!value.isPresent()) { @@ -120,11 +115,11 @@ public class UniqueValueUtil { } validateUniqueValue(type, value.get(), uniqueCombination); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } private static void validateUniqueValue(String type, String value, String... uniqueCombination) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (uniqueValueDao.get(new UniqueValueEntity(type, value)) != null) { throw new CoreException(new ErrorCode.ErrorCodeBuilder() @@ -134,13 +129,13 @@ public class UniqueValueUtil { uniqueCombination[uniqueCombination.length - 1])).build()); } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } private static Optional<String> formatValue(String[] uniqueCombination) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (uniqueCombination == null || uniqueCombination.length == 0 || uniqueCombination[uniqueCombination.length - 1] == null) { @@ -150,7 +145,7 @@ public class UniqueValueUtil { uniqueCombination[uniqueCombination.length - 1] = uniqueCombination[uniqueCombination.length - 1].toLowerCase(); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return Optional.of(CommonMethods.arrayToSeparatedString(uniqueCombination, '_')); } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java index 93410bc581..2172e1bc2f 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/main/java/org/openecomp/core/nosqldb/impl/cassandra/CassandraNoSqlDbImpl.java @@ -20,7 +20,11 @@ package org.openecomp.core.nosqldb.impl.cassandra; -import com.datastax.driver.core.*; +import com.datastax.driver.core.BoundStatement; +import com.datastax.driver.core.Host; +import com.datastax.driver.core.PreparedStatement; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Session; import com.datastax.driver.mapping.MappingManager; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.util.CassandraUtils; diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java index 5c4f951a7b..2bab7e0d67 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/NoSqlDbTest.java @@ -20,14 +20,7 @@ package org.openecomp.core.nosqldb; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; import org.openecomp.core.nosqldb.api.NoSqlDb; -import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; -import org.testng.Assert; -import org.testng.annotations.Test; - -import java.util.List; public class NoSqlDbTest { diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java index f8d5d2dce7..7a6343d15c 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-nosqldb-lib/openecomp-nosqldb-core/src/test/java/org/openecomp/core/nosqldb/util/ConfigurationManagerTest.java @@ -7,7 +7,7 @@ import java.io.Closeable; import java.io.IOException; import java.lang.reflect.Field; -import static org.testng.Assert.*; +import static org.testng.Assert.assertNotNull; /** * @author EVITALIY diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/pom.xml new file mode 100644 index 0000000000..c0618ba503 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/pom.xml @@ -0,0 +1,30 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-core-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + </parent> + + <artifactId>openecomp-session-lib</artifactId> + + + <dependencies> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-facade-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-facade-core</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> + + +</project>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContext.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContext.java new file mode 100644 index 0000000000..a1b410c90c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContext.java @@ -0,0 +1,8 @@ +package org.openecomp.sdc.common.session; + +public interface SessionContext { + + User getUser(); + + String getTenant(); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProvider.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProvider.java new file mode 100644 index 0000000000..8efbbd10eb --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProvider.java @@ -0,0 +1,10 @@ +package org.openecomp.sdc.common.session; + +public interface SessionContextProvider { + + void create(String user); + + SessionContext get(); + + void close(); +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductDaoFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProviderFactory.java index 32070fe06a..cfa6a346c9 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductDaoFactory.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/SessionContextProviderFactory.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,18 +18,15 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.sdc.vendorsoftwareproduct.dao; +package org.openecomp.sdc.common.session; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; +public abstract class SessionContextProviderFactory + extends AbstractComponentFactory<SessionContextProvider> { -public abstract class VendorSoftwareProductDaoFactory extends - AbstractComponentFactory<VendorSoftwareProductDao> { - - - public static VendorSoftwareProductDaoFactory getInstance() { - return AbstractFactory.getInstance(VendorSoftwareProductDaoFactory.class); + public static SessionContextProviderFactory getInstance() { + return AbstractFactory.getInstance(SessionContextProviderFactory.class); } - } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/User.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/User.java new file mode 100644 index 0000000000..5319a0bf56 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/User.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.common.session; + +public class User { + private final String userId; + + public User(String userId) { + this.userId = userId; + } + + public String getUserId() { + return userId; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/AsdcSessionContextProvider.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/AsdcSessionContextProvider.java new file mode 100644 index 0000000000..53a40a163f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/AsdcSessionContextProvider.java @@ -0,0 +1,50 @@ +package org.openecomp.sdc.common.session.impl; + +import org.openecomp.sdc.common.session.SessionContext; +import org.openecomp.sdc.common.session.SessionContextProvider; +import org.openecomp.sdc.common.session.User; + +public class AsdcSessionContextProvider implements SessionContextProvider { + + private static final ThreadLocal<String> threadUserId = new ThreadLocal<>(); + + @Override + public void create(String userId) { + threadUserId.set(userId); + } + + @Override + public SessionContext get() { + if (threadUserId.get() == null) { + throw new RuntimeException("UserId was not set for this thread"); + } + + return new AsdcSessionContext(new User(threadUserId.get()), "dox"); + } + + @Override + public void close() { + threadUserId.remove(); + } + + private static class AsdcSessionContext implements SessionContext { + + private final User user; + private final String tenant; + + private AsdcSessionContext(User user, String tenant) { + this.user = user; + this.tenant = tenant; + } + + @Override + public User getUser() { + return user; + } + + @Override + public String getTenant() { + return tenant; + } + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductDaoFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/SessionContextProviderFactoryImpl.java index 0a80b2ae51..635aa5b6ed 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/java/org/openecomp/sdc/common/session/impl/SessionContextProviderFactoryImpl.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,17 +18,16 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; +package org.openecomp.sdc.common.session.impl; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; +import org.openecomp.sdc.common.session.SessionContextProvider; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; - -public class VendorSoftwareProductDaoFactoryImpl extends VendorSoftwareProductDaoFactory { - private static final VendorSoftwareProductDao INSTANCE = new VendorSoftwareProductDaoImpl(); +public class SessionContextProviderFactoryImpl extends SessionContextProviderFactory { + private static final SessionContextProvider INSTANCE = new AsdcSessionContextProvider(); @Override - public VendorSoftwareProductDao createInterface() { + public SessionContextProvider createInterface() { return INSTANCE; } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..cd1637a80e --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-session-lib/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.sdc.common.session.SessionContextProviderFactory": "org.openecomp.sdc.common.session.impl.SessionContextProviderFactoryImpl" +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java index 6ab3f8b049..5a8a2db2f2 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java @@ -23,12 +23,9 @@ package org.openecomp.core.utilities.file; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.services.YamlUtil; import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.URL; diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java index 527ba22c1d..be0686ef5a 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java @@ -6,7 +6,9 @@ import java.io.IOException; import java.util.Arrays; import java.util.Optional; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; /** * @author EVITALIY diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml index 538a7fb42a..ee59b5bf77 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/pom.xml @@ -20,6 +20,16 @@ </dependency> <dependency> <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-session-lib</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-versioning-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> <artifactId>openecomp-facade-api</artifactId> <version>${project.version}</version> </dependency> @@ -43,6 +53,11 @@ <artifactId>commons-lang3</artifactId> <version>3.4</version> </dependency> + <dependency> + <groupId>com.amdocs.zusammen</groupId> + <artifactId>zusammen-datatypes</artifactId> + <version>${zusammen.version}</version> + </dependency> </dependencies> diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/convertor/ElementConvertor.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/convertor/ElementConvertor.java new file mode 100644 index 0000000000..68c709826f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/convertor/ElementConvertor.java @@ -0,0 +1,37 @@ +package org.openecomp.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Item; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import org.openecomp.sdc.datatypes.model.ElementType; +import org.openecomp.types.ElementPropertyName; + +public abstract class ElementConvertor<T> { + + public static ElementType getElementType(Element element) { + return ElementType + .valueOf(element.getInfo().getProperty(ElementPropertyName.elementType.name())); + } + + public static String getElementName(Element element) { + return element.getInfo().getName(); + } + + + abstract public T convert(Element element); + + public T convert( ElementInfo elementInfo) { + throw new UnsupportedOperationException("convert elementInfo item is not supported "); + } + + + public T convert( Item item) { + throw new UnsupportedOperationException("convert from item is not supported "); + } + + + public T convert( ItemVersion itemVersion) { + throw new UnsupportedOperationException("convert from itemVersion is not supported "); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptor.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptor.java index 2ba447fd6a..35c07cbee0 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptor.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenAdaptor.java @@ -1,7 +1,9 @@ package org.openecomp.core.zusammen.api; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.commons.health.data.HealthInfo; import com.amdocs.zusammen.datatypes.Id; @@ -11,31 +13,53 @@ import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Item; import com.amdocs.zusammen.datatypes.item.ItemVersion; import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus; +import com.amdocs.zusammen.datatypes.item.Resolution; import com.amdocs.zusammen.datatypes.itemversion.Tag; +import org.openecomp.sdc.versioning.dao.types.Revision; import java.util.Collection; +import java.util.List; import java.util.Optional; public interface ZusammenAdaptor { Collection<Item> listItems(SessionContext context); + Item getItem(SessionContext context, Id itemId); + Id createItem(SessionContext context, Info info); void updateItem(SessionContext context, Id itemId, Info info); - // TODO: 4/4/2017 fix this workaround when versionId will be recieved from UI + // TODO: 4/4/2017 remove this workaround when versionId will be recieved from UI Optional<ItemVersion> getFirstVersion(SessionContext context, Id itemId); + Collection<ItemVersion> listPublicVersions(SessionContext context, Id itemId); + + ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId); + Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData); void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData); + ItemVersion getVersion(SessionContext context, Id itemId, Id versionId); + + ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId); + + ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId); + void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag); - void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef); + void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String version); + + void publishVersion(SessionContext context, Id itemId, Id versionId, String message); + + void syncVersion(SessionContext context, Id itemId, Id versionId); + + void forceSyncVersion(SessionContext context, Id itemId, Id versionId); Optional<ElementInfo> getElementInfo(SessionContext context, ElementContext elementContext, Id elementId); @@ -43,38 +67,39 @@ public interface ZusammenAdaptor { Optional<Element> getElement(SessionContext context, ElementContext elementContext, String elementId); // TODO: 4/3/2017 change to Id - Optional<Element> getElementByName( - SessionContext context, ElementContext elementContext, Id parentElementId, - String elementName); + Optional<Element> getElementByName(SessionContext context, ElementContext elementContext, + Id parentElementId, String elementName); - Collection<ElementInfo> listElements(SessionContext context, - ElementContext elementContext, + Collection<ElementInfo> listElements(SessionContext context, ElementContext elementContext, Id parentElementId); - Collection<Element> listElementData(SessionContext context, - ElementContext elementContext, + Collection<Element> listElementData(SessionContext context, ElementContext elementContext, Id parentElementId); /** - * Lists the sub elements of the element named <elementName> which is a sub element of <parentElementId> - * @param context - * @param elementContext - * @param parentElementId - * @param elementName - * @return + * Lists the sub elements of the element named elementName which is a sub element of + * parentElementId */ - Collection<ElementInfo> listElementsByName( - SessionContext context, ElementContext elementContext, Id parentElementId, - String elementName); + Collection<ElementInfo> listElementsByName(SessionContext context, ElementContext elementContext, + Id parentElementId, String elementName); + + Optional<ElementInfo> getElementInfoByName(SessionContext context, ElementContext elementContext, + Id parentElementId, String elementName); - Optional<ElementInfo> getElementInfoByName( - SessionContext context, ElementContext elementContext, Id parentElementId, - String elementName); + Optional<ElementConflict> getElementConflict(SessionContext context, + ElementContext elementContext, Id elementId); - Optional<Element> saveElement(SessionContext context, ElementContext elementContext, - ZusammenElement element, String message); + Element saveElement(SessionContext context, ElementContext elementContext, + ZusammenElement element, String message); + + void resolveElementConflict(SessionContext context, ElementContext elementContext, + ZusammenElement element, Resolution resolution); Collection<HealthInfo> checkHealth(SessionContext context); - String getVersion(SessionContext sessionContext); + String getVersion(SessionContext context); + + void revert(SessionContext sessionContext, String itemId, String versionId, String revisionId); + + List<Revision> listRevisions(SessionContext sessionContext, String itemId, String versionId); } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenUtil.java index 3df6151fae..623f958ceb 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenUtil.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/core/zusammen/api/ZusammenUtil.java @@ -1,40 +1,40 @@ package org.openecomp.core.zusammen.api; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; +import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.UserInfo; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.datatypes.model.ElementType; +import org.openecomp.types.ElementPropertyName; public class ZusammenUtil { - // TODO: 3/19/2017 add user and tenant args + public static SessionContext createSessionContext() { + org.openecomp.sdc.common.session.SessionContext asdcSessionContext = + SessionContextProviderFactory.getInstance().createInterface().get(); + SessionContext sessionContext = new SessionContext(); - sessionContext.setUser(new UserInfo("GLOBAL_USER")); - sessionContext.setTenant("dox"); + sessionContext.setUser(new UserInfo(asdcSessionContext.getUser().getUserId())); + sessionContext.setTenant(asdcSessionContext.getTenant()); return sessionContext; } - public static ZusammenElement buildStructuralElement(String structureElementName, - Action action) { - ZusammenElement element = new ZusammenElement(); + public static ZusammenElement buildStructuralElement(ElementType elementType, Action action) { + ZusammenElement element = buildElement(null, action); Info info = new Info(); - info.setName(structureElementName); + info.setName(elementType.name()); + info.addProperty(ElementPropertyName.elementType.name(), elementType.name()); element.setInfo(info); - if (action != null) { - element.setAction(action); - } return element; } - // TODO: 4/24/2017 remove upon working with more than one single version - public static ItemVersionData createFirstVersionData() { - Info info = new Info(); - info.setName("main version"); - ItemVersionData itemVersionData = new ItemVersionData(); - itemVersionData.setInfo(info); - return itemVersionData; + public static ZusammenElement buildElement(Id elementId, Action action) { + ZusammenElement element = new ZusammenElement(); + element.setElementId(elementId); + element.setAction(action); + return element; } - } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/AsdcElement.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/AsdcElement.java new file mode 100644 index 0000000000..ae9c1fcd44 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/AsdcElement.java @@ -0,0 +1,131 @@ +package org.openecomp.types; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Relation; +import com.amdocs.zusammen.utils.fileutils.FileUtils; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; + +public class AsdcElement implements Element { + + private String type; + private String name; + private String description; + + private Map<String, Object> properties; + private byte[] data; + private Collection<Relation> relations; + private Collection<Element> subElements = new ArrayList<>(); + private Action action; + private Id elementId; + + @Override + public Action getAction() { + return this.action; + } + + @Override + public Id getElementId() { + return this.elementId; + } + + @Override + public Info getInfo() { + Info info = new Info(); + info.setProperties(this.properties); + info.addProperty(ElementPropertyName.elementType.name(), this.type != null ? this.type : this.name); + info.setName(this.name); + info.setDescription(this.description); + + return info; + } + + @Override + public Collection<Relation> getRelations() { + return this.relations; + } + + @Override + public InputStream getData() { + return FileUtils.toInputStream(this.data); + } + + @Override + public InputStream getSearchableData() { + return null; + } + + @Override + public InputStream getVisualization() { + return null; + } + + + @Override + public Collection<Element> getSubElements() { + return this.subElements; + } + + public void setElementId(Id elementId) { + this.elementId = elementId; + } + + public void setData(InputStream data) { + this.data = FileUtils.toByteArray(data); + } + + public void setRelations(Collection<Relation> relations) { + this.relations = relations; + } + + public void setSubElements(Collection<Element> subElements) { + this.subElements = subElements; + } + + public void setAction(Action action) { + this.action = action; + } + + public AsdcElement addSubElement(Element element) { + this.subElements.add(element); + return this; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map<String, Object> getProperties() { + return properties; + } + + public void setProperties(Map<String, Object> properties) { + this.properties = properties; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/ElementPropertyName.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/ElementPropertyName.java new file mode 100644 index 0000000000..ddbef7d8a4 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-api/src/main/java/org/openecomp/types/ElementPropertyName.java @@ -0,0 +1,6 @@ +package org.openecomp.types; + +public enum ElementPropertyName { + elementType, + compositionData +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnector.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnector.java index 6381b2efd2..9005bb84c3 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnector.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/ZusammenConnector.java @@ -1,7 +1,9 @@ package org.openecomp.core.zusammen.db; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.commons.health.data.HealthInfo; import com.amdocs.zusammen.datatypes.Id; @@ -11,22 +13,31 @@ import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Item; import com.amdocs.zusammen.datatypes.item.ItemVersion; import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus; +import com.amdocs.zusammen.datatypes.item.Resolution; +import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; import com.amdocs.zusammen.datatypes.itemversion.Tag; -import com.amdocs.zusammen.datatypes.response.Response; import java.util.Collection; -import java.util.Optional; public interface ZusammenConnector { + Collection<HealthInfo> checkHealth(SessionContext sessionContext); + + String getVersion(SessionContext sessionContext); + Collection<Item> listItems(SessionContext context); + Item getItem(SessionContext context, Id itemId); + Id createItem(SessionContext context, Info info); void updateItem(SessionContext context, Id itemId, Info info); - Collection<ItemVersion> listVersions(SessionContext context, Id itemId); + Collection<ItemVersion> listPublicVersions(SessionContext context, Id itemId); + + ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId); Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData); @@ -34,23 +45,42 @@ public interface ZusammenConnector { void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData); + ItemVersion getVersion(SessionContext context, Id itemId, Id versionId); + + ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId); + void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag); - void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef); + void resetVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId); + + void revertVersionRevision(SessionContext context, Id itemId, Id versionId, Id revisionId); + + ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, Id versionId); + + void publishVersion(SessionContext context, Id itemId, Id versionId, String message); + + void syncVersion(SessionContext context, Id itemId, Id versionId); + + void forceSyncVersion(SessionContext context, Id itemId, Id versionId); + + ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId); Collection<ElementInfo> listElements(SessionContext context, ElementContext elementContext, Id parentElementId); - Response<ElementInfo> getElementInfo(SessionContext context, ElementContext elementContext, Id - elementId); + ElementInfo getElementInfo(SessionContext context, ElementContext elementContext, Id elementId); - Response<Element> getElement(SessionContext context, ElementContext elementContext, Id elementId); + Element getElement(SessionContext context, ElementContext elementContext, Id elementId); - Optional<Element> saveElement(SessionContext context, ElementContext elementContext, - ZusammenElement element, String message); + ElementConflict getElementConflict(SessionContext context, ElementContext elementContext, + Id elementId); - Collection<HealthInfo> checkHealth(SessionContext sessionContext); + Element saveElement(SessionContext context, ElementContext elementContext, + ZusammenElement element, String message); - String getVersion(SessionContext sessionContext); + void resolveElementConflict(SessionContext context, ElementContext elementContext, + ZusammenElement element, Resolution resolution); + + void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef); } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java index deb5ffde35..1d387b939f 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/db/impl/ZusammenConnectorImpl.java @@ -1,11 +1,14 @@ package org.openecomp.core.zusammen.db.impl; +import com.amdocs.zusammen.adaptor.inbound.api.health.HealthAdaptorFactory; import com.amdocs.zusammen.adaptor.inbound.api.item.ElementAdaptorFactory; import com.amdocs.zusammen.adaptor.inbound.api.item.ItemAdaptorFactory; import com.amdocs.zusammen.adaptor.inbound.api.item.ItemVersionAdaptorFactory; -import com.amdocs.zusammen.adaptor.inbound.api.health.HealthAdaptorFactory; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.MergeResult; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.commons.health.data.HealthInfo; import com.amdocs.zusammen.datatypes.Id; @@ -16,6 +19,9 @@ import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Item; import com.amdocs.zusammen.datatypes.item.ItemVersion; import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus; +import com.amdocs.zusammen.datatypes.item.Resolution; +import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; import com.amdocs.zusammen.datatypes.itemversion.Tag; import com.amdocs.zusammen.datatypes.response.Response; import com.amdocs.zusammen.datatypes.response.ReturnCode; @@ -28,14 +34,18 @@ import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import java.util.Collection; -import java.util.Optional; public class ZusammenConnectorImpl implements ZusammenConnector { + private static final String GET_ELEMENT_ERR_MSG = + "Failed to get element. Item Id: %s, version Id: %s, element Id: %s message: %s"; + private static final String GET_ELEMENT_IN_REV_ERR_MSG = + "Failed to get element. Item Id: %s, version Id: %s, revision Id: %s, element Id: %s message: %s"; private ItemAdaptorFactory itemAdaptorFactory; private ItemVersionAdaptorFactory versionAdaptorFactory; private ElementAdaptorFactory elementAdaptorFactory; private HealthAdaptorFactory healthAdaptorFactory; + public ZusammenConnectorImpl( ItemAdaptorFactory itemAdaptorFactory, ItemVersionAdaptorFactory versionAdaptorFactory, @@ -69,14 +79,23 @@ public class ZusammenConnectorImpl implements ZusammenConnector { } @Override + public Item getItem(SessionContext context, Id itemId) { + Response<Item> response = itemAdaptorFactory.createInterface(context).get(context, itemId); + if (!response.isSuccessful()) { + throw new RuntimeException( + "Failed to get Item. message:" + response.getReturnCode().toString()); + } + return response.getValue(); + } + + @Override public Id createItem(SessionContext context, Info info) { Response<Id> response = itemAdaptorFactory.createInterface(context).create(context, info); - if (response.isSuccessful()) { - return response.getValue(); - } else { + if (!response.isSuccessful()) { throw new RuntimeException( - "failed to create Item. message:" + response.getReturnCode().toString()); + "Failed to create Item. message:" + response.getReturnCode().toString()); } + return response.getValue(); } @Override @@ -91,18 +110,30 @@ public class ZusammenConnectorImpl implements ZusammenConnector { } @Override - public Collection<ItemVersion> listVersions(SessionContext context, Id itemId) { + public Collection<ItemVersion> listPublicVersions(SessionContext context, Id itemId) { Response<Collection<ItemVersion>> versions = - versionAdaptorFactory.createInterface(context).list(context, Space.PRIVATE, itemId); + versionAdaptorFactory.createInterface(context).list(context, Space.PUBLIC, itemId); if (!versions.isSuccessful()) { logErrorMessageToMdc(ItemElementLoggerTargetServiceName.ITEM_VERSION_RETRIEVAL, versions .getReturnCode()); - throw new RuntimeException(versions.getReturnCode().toString()); // TODO: 3/26/2017 + throw new RuntimeException(versions.getReturnCode().toString()); } return versions.getValue(); } @Override + public ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId) { + Response<ItemVersion> response = versionAdaptorFactory.createInterface(context) + .get(context, Space.PUBLIC, itemId, versionId); + if (!response.isSuccessful()) { + throw new RuntimeException( + String.format("failed to get public Item Version. ItemId: %s, versionId: %s, message: %s", + itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); + } + return response.getValue(); + } + + @Override public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData itemVersionData) { Response<Id> response = versionAdaptorFactory.createInterface(context).create(context, itemId, @@ -110,10 +141,9 @@ public class ZusammenConnectorImpl implements ZusammenConnector { if (response.isSuccessful()) { return response.getValue(); } else { - throw new RuntimeException("failed to create Item Version. ItemId:" + itemId + " based " + - "on:" + baseVersionId + - " message:" + response - .getReturnCode().toString()); + throw new RuntimeException(String.format( + "failed to create Item Version. ItemId: %s, base versionId: %s, message: %s", + itemId.getValue(), baseVersionId.getValue(), response.getReturnCode().toString())); } } @@ -124,9 +154,33 @@ public class ZusammenConnectorImpl implements ZusammenConnector { .update(context, itemId, versionId, itemVersionData); if (!response.isSuccessful()) { throw new RuntimeException( - String.format("failed to create Item Version. ItemId: %s, versionId: %s, message: %s", + String.format("failed to update Item Version. ItemId: %s, versionId: %s, message: %s", + itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); + } + } + + @Override + public ItemVersion getVersion(SessionContext context, Id itemId, Id versionId) { + Response<ItemVersion> response = versionAdaptorFactory.createInterface(context) + .get(context, Space.PRIVATE, itemId, versionId); + if (!response.isSuccessful()) { + throw new RuntimeException( + String.format("failed to get Item Version. ItemId: %s, versionId: %s, message: %s", itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } + return response.getValue(); + } + + @Override + public ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) { + Response<ItemVersionStatus> response = + versionAdaptorFactory.createInterface(context).getStatus(context, itemId, versionId); + if (!response.isSuccessful()) { + throw new RuntimeException( + String.format("failed to get Item Version status. ItemId: %s, versionId: %s, message: %s", + itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); + } + return response.getValue(); } @Override @@ -136,65 +190,197 @@ public class ZusammenConnectorImpl implements ZusammenConnector { if (!response.isSuccessful()) { throw new RuntimeException(String.format( "failed to tag Item Version with tag %s. ItemId: %s, versionId: %s, message: %s", - tag.getName(), itemId.getValue(), versionId.getValue(), response.getReturnCode() - .getMessage())); + tag.getName(), itemId.getValue(), versionId.getValue(), + response.getReturnCode().toString())); } } @Override - public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, - String changeRef) { + public void resetVersionRevision(SessionContext context, Id itemId, Id versionId, + Id revisionId) { Response<Void> response = versionAdaptorFactory.createInterface(context) - .resetHistory(context, itemId, versionId, changeRef); + .resetRevision(context, itemId, versionId, revisionId); if (!response.isSuccessful()) { throw new RuntimeException(String.format( - "failed to reset Item Version back to %s. ItemId: %s, versionId: %s, message: %s", - changeRef, itemId.getValue(), versionId.getValue(), + "failed to reset Item Version back to revision: %s. ItemId: %s, versionId: %s, message:" + + " %s", + revisionId.getValue(), itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); } } @Override + public void revertVersionRevision(SessionContext context, Id itemId, Id versionId, + Id revisionId) { + Response<Void> response = versionAdaptorFactory.createInterface(context) + .revertRevision(context, itemId, versionId, revisionId); + if (!response.isSuccessful()) { + throw new RuntimeException(String.format( + "failed to revert Item Version back to revision: %s. ItemId: %s, versionId: %s, " + + "message: %s", + revisionId.getValue(), itemId.getValue(), versionId.getValue(), + response.getReturnCode().toString())); + } + } + + @Override + public ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, + Id versionId) { + Response<ItemVersionRevisions> response = + versionAdaptorFactory.createInterface(context) + .listRevisions(context, itemId, versionId); + if (!response.isSuccessful()) { + throw new RuntimeException(String.format( + "failed to list revisions of Item Version. ItemId: %s, versionId: %s, message: %s", + itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); + } + return response.getValue(); + } + + + @Override + public void publishVersion(SessionContext context, Id itemId, Id versionId, String message) { + Response<Void> response = + versionAdaptorFactory.createInterface(context).publish(context, itemId, versionId, message); + if (!response.isSuccessful()) { + throw new RuntimeException(String.format( + "failed to publish item Version. ItemId: %s, versionId: %s, message: %s", + itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); + } + } + + @Override + public void syncVersion(SessionContext context, Id itemId, Id versionId) { + Response<MergeResult> response = + versionAdaptorFactory.createInterface(context).sync(context, itemId, versionId); + if (!response.isSuccessful()) { + throw new RuntimeException(String.format( + "failed to sync item Version. ItemId: %s, versionId: %s, message: %s", + itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); + } + } + + @Override + public void forceSyncVersion(SessionContext context, Id itemId, Id versionId) { + Response<MergeResult> response = + versionAdaptorFactory.createInterface(context).forceSync(context, itemId, versionId); + if (!response.isSuccessful()) { + throw new RuntimeException(String.format( + "failed to force sync item Version. ItemId: %s, versionId: %s, message: %s", + itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); + } + } + + @Override + public ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId) { + Response<ItemVersionConflict> response = + versionAdaptorFactory.createInterface(context).getConflict(context, itemId, versionId); + if (!response.isSuccessful()) { + throw new RuntimeException(String + .format("failed to get Item Version conflict. ItemId: %s, versionId: %s, message: %s", + itemId.getValue(), versionId.getValue(), response.getReturnCode().toString())); + } + return response.getValue(); + } + + @Override public Collection<ElementInfo> listElements(SessionContext context, ElementContext elementContext, Id parentElementId) { - Response<Collection<ElementInfo>> elementInfosResponse = elementAdaptorFactory + Response<Collection<ElementInfo>> response = elementAdaptorFactory .createInterface(context).list(context, elementContext, parentElementId); - if (elementInfosResponse.isSuccessful()) { - return elementInfosResponse.getValue(); + if (response.isSuccessful()) { + return response.getValue(); } else { logErrorMessageToMdc(ItemElementLoggerTargetServiceName.ELEMENT_GET_BY_PROPERTY, - elementInfosResponse.getReturnCode()); - throw new RuntimeException(elementInfosResponse.getReturnCode().toString()); + response.getReturnCode()); + throw new RuntimeException(response.getReturnCode().toString()); } } + @Override - public Response<ElementInfo> getElementInfo(SessionContext context, ElementContext elementContext, - Id elementId) { - return elementAdaptorFactory.createInterface(context) - .getInfo(context, elementContext, elementId); + public ElementInfo getElementInfo(SessionContext context, ElementContext elementContext, + Id elementId) { + Response<ElementInfo> response = + elementAdaptorFactory.createInterface(context).getInfo(context, elementContext, elementId); + if (!response.isSuccessful()) { + throw buildGetElementException(elementContext, elementId, + response.getReturnCode().toString()); + + } + return response.getValue(); } + @Override + public Element getElement(SessionContext context, ElementContext elementContext, + Id elementId) { + Response<Element> response = + elementAdaptorFactory.createInterface(context).get(context, elementContext, elementId); + if (!response.isSuccessful()) { + throw buildGetElementException(elementContext, elementId, + response.getReturnCode().toString()); + } + return response.getValue(); + } @Override - public Response<Element> getElement(SessionContext context, ElementContext elementContext, - Id elementId) { - return elementAdaptorFactory.createInterface(context).get(context, elementContext, elementId); + public ElementConflict getElementConflict(SessionContext context, ElementContext elementContext, + Id elementId) { + Response<ElementConflict> response = elementAdaptorFactory.createInterface(context) + .getConflict(context, elementContext, elementId); + if (!response.isSuccessful()) { + throw new RuntimeException(String.format( + "Failed to get element conflict. Item Id: %s, version Id: %s, element Id: %s message: %s", + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementId.getValue(), response.getReturnCode().toString())); + } + return response.getValue(); } @Override - public Optional<Element> saveElement(SessionContext context, ElementContext elementContext, - ZusammenElement element, String message) { + public Element saveElement(SessionContext context, ElementContext elementContext, + ZusammenElement element, String message) { Response<Element> response = elementAdaptorFactory.createInterface(context) .save(context, elementContext, element, message); if (!response.isSuccessful()) { throw new RuntimeException(String - .format("Failed to save element %s. ItemId: %s, versionId: %s, message: %s", + .format("Failed to create element %s. ItemId: %s, versionId: %s, message: %s", element.getElementId().getValue(), elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), response.getReturnCode().toString())); } - return Optional.of(response.getValue()); + return response.getValue(); + } + + @Override + public void resolveElementConflict(SessionContext context, ElementContext elementContext, + ZusammenElement element, + Resolution resolution) { + Response<Void> response = elementAdaptorFactory.createInterface(context) + .resolveConflict(context, elementContext, element, resolution); + if (!response.isSuccessful()) { + throw new RuntimeException( + "Failed to resolve conflict. message:" + response.getReturnCode().toString()); + } + } + + @Override + public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, + String revision_id) { + + } + + private RuntimeException buildGetElementException(ElementContext elementContext, Id elementId, + String zusammenErrorMessage) { + if (elementContext.getRevisionId() == null) { + return new RuntimeException(String.format(GET_ELEMENT_ERR_MSG, + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementId.getValue(), zusammenErrorMessage)); + } + return new RuntimeException(String.format(GET_ELEMENT_IN_REV_ERR_MSG, + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue(), + elementId.getValue(), zusammenErrorMessage)); } private void logErrorMessageToMdc(ItemElementLoggerTargetServiceName diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorImpl.java index 41ce0283a1..9bdbfd681c 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-core/src/main/java/org/openecomp/core/zusammen/impl/ZusammenAdaptorImpl.java @@ -1,24 +1,30 @@ package org.openecomp.core.zusammen.impl; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.commons.health.data.HealthInfo; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.*; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Item; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus; +import com.amdocs.zusammen.datatypes.item.Resolution; +import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; import com.amdocs.zusammen.datatypes.itemversion.Tag; -import com.amdocs.zusammen.datatypes.response.Response; -import com.amdocs.zusammen.datatypes.response.ReturnCode; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.db.ZusammenConnector; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; -import org.openecomp.sdc.logging.types.LoggerConstants; -import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.versioning.dao.types.Revision; import java.util.ArrayList; import java.util.Collection; +import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.function.Predicate; @@ -33,30 +39,15 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { } @Override - public Optional<ItemVersion> getFirstVersion(SessionContext context, Id itemId) { - Collection<ItemVersion> versions = connector.listVersions(context, itemId); - if(versions == null || versions.size()==0) { - return Optional.empty(); - } - List<ItemVersion> itemVersions = new ArrayList<>(versions); - sortItemVersionListByModificationTimeDescOrder(itemVersions); - ItemVersion itemVersion = itemVersions.iterator().next(); - - return Optional.ofNullable(itemVersion); - } - - @Override public Optional<ElementInfo> getElementInfo(SessionContext context, ElementContext elementContext, Id elementId) { - Response<ElementInfo> response = connector.getElementInfo(context, elementContext, elementId); - return response.isSuccessful() ? Optional.ofNullable(response.getValue()) : Optional.empty(); + return Optional.ofNullable(connector.getElementInfo(context, elementContext, elementId)); } @Override public Optional<Element> getElement(SessionContext context, ElementContext elementContext, String elementId) { - Response<Element> response = connector.getElement(context, elementContext, new Id(elementId)); - return response.isSuccessful() ? Optional.ofNullable(response.getValue()) : Optional.empty(); + return Optional.ofNullable(connector.getElement(context, elementContext, new Id(elementId))); } @Override @@ -82,16 +73,14 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { public Collection<Element> listElementData(SessionContext context, ElementContext elementContext, Id parentElementId) { - Collection<ElementInfo> elementInfoList = connector.listElements(context, elementContext, parentElementId); - if (elementInfoList != null) { - return elementInfoList.stream().map(elementInfo -> connector.getElement(context, - elementContext, elementInfo.getId()).getValue()).collect(Collectors.toList()); - } - - return new ArrayList<>(); + return elementInfoList == null + ? new ArrayList<>() + : elementInfoList.stream() + .map(elementInfo -> connector.getElement(context, elementContext, elementInfo.getId())) + .collect(Collectors.toList()); } @@ -119,12 +108,24 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { } @Override - public Optional<Element> saveElement(SessionContext context, ElementContext elementContext, - ZusammenElement element, String message) { + public Optional<ElementConflict> getElementConflict(SessionContext context, ElementContext elementContext, + Id elementId) { + return Optional.ofNullable(connector.getElementConflict(context, elementContext, elementId)); + } + + @Override + public Element saveElement(SessionContext context, ElementContext elementContext, + ZusammenElement element, String message) { enrichElementHierarchyRec(context, elementContext, null, element); return connector.saveElement(context, elementContext, element, message); } + @Override + public void resolveElementConflict(SessionContext context, ElementContext elementContext, + ZusammenElement element, Resolution resolution) { + connector.resolveElementConflict(context, elementContext, element, resolution); + } + private void enrichElementHierarchyRec(SessionContext context, ElementContext elementContext, Id parentElementId, ZusammenElement element) { if (element.getAction() == Action.CREATE) { @@ -160,20 +161,14 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { .findFirst(); } - private void logErrorMessageToMdc(ItemElementLoggerTargetServiceName - itemElementLoggerTargetServiceName, - ReturnCode returnCode) { - logErrorMessageToMdc(itemElementLoggerTargetServiceName, returnCode.toString()); + @Override + public Collection<Item> listItems(SessionContext context) { + return connector.listItems(context); } - private void logErrorMessageToMdc(ItemElementLoggerTargetServiceName - itemElementLoggerTargetServiceName, - String message) { - MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - itemElementLoggerTargetServiceName.getDescription(), - ErrorLevel.ERROR.name(), - LoggerErrorCode.BUSINESS_PROCESS_ERROR.getErrorCode(), - message); + @Override + public Item getItem(SessionContext context, Id itemId) { + return connector.getItem(context, itemId); } @Override @@ -182,15 +177,52 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { } @Override - public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData - itemVersionData) { - return connector.createVersion(context, itemId, baseVersionId, itemVersionData); + public void updateItem(SessionContext context, Id itemId, Info info) { + connector.updateItem(context, itemId, info); + } + @Override + public Optional<ItemVersion> getFirstVersion(SessionContext context, Id itemId) { + Collection<ItemVersion> versions = connector.listPublicVersions(context, itemId); + if (versions == null || versions.size() == 0) { + return Optional.empty(); + } + List<ItemVersion> itemVersions = new ArrayList<>(versions); + sortItemVersionListByModificationTimeDescOrder(itemVersions); + ItemVersion itemVersion = itemVersions.iterator().next(); + + return Optional.ofNullable(itemVersion); } @Override - public Collection<Item> listItems(SessionContext context) { - return connector.listItems(context); + public Collection<ItemVersion> listPublicVersions(SessionContext context, Id itemId) { + return connector.listPublicVersions(context, itemId); + } + + @Override + public ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId) { + return connector.getPublicVersion(context, itemId, versionId); + } + + @Override + public ItemVersion getVersion(SessionContext context, Id itemId, Id versionId) { + return connector.getVersion(context, itemId, versionId); + } + + @Override + public ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) { + return connector.getVersionStatus(context, itemId, versionId); + } + + @Override + public ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId) { + return connector.getVersionConflict(context, itemId, versionId); + } + + @Override + public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, ItemVersionData + itemVersionData) { + return connector.createVersion(context, itemId, baseVersionId, itemVersionData); } @Override @@ -210,25 +242,96 @@ public class ZusammenAdaptorImpl implements ZusammenAdaptor { connector.resetVersionHistory(context, itemId, versionId, changeRef); } + /*@Override + public void revertVersionToRevision(SessionContext context, Id itemId, Id versionId, + Id revisionId) { + connector.resetVersionRevision(context, itemId, versionId, revisionId); + }*/ + + /*@Override + public ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, Id + versionId) { + return connector.listVersionRevisions(context, itemId, versionId); + }*/ + @Override - public void updateItem(SessionContext context, Id itemId, Info info) { - connector.updateItem(context, itemId, info); + public void publishVersion(SessionContext context, Id itemId, Id versionId, String message) { + connector.publishVersion(context, itemId, versionId, message); + } + + @Override + public void syncVersion(SessionContext context, Id itemId, Id versionId) { + connector.syncVersion(context, itemId, versionId); } + @Override + public void forceSyncVersion(SessionContext context, Id itemId, Id versionId) { + connector.forceSyncVersion(context, itemId, versionId); + } @Override public Collection<HealthInfo> checkHealth(SessionContext context) { return connector.checkHealth(context); } - private static void sortItemVersionListByModificationTimeDescOrder( - List<ItemVersion> itemVersions) { - itemVersions.sort((o1, o2) -> ((Integer)o2.getId().getValue().length()) - .compareTo( (o1.getId().getValue().length()))); - } - @Override public String getVersion(SessionContext sessionContext) { return connector.getVersion(sessionContext); } + + @Override + public void revert(SessionContext sessionContext, String itemId, String versionId, + String revisionId) { + connector.revertVersionRevision(sessionContext, new Id(itemId), new Id(versionId), + new Id(revisionId)); + } + + @Override + public List<Revision> listRevisions(SessionContext sessionContext, String itemId, + String versionId) { + List<Revision> revisions = new ArrayList<>(); + ItemVersionRevisions itemVersionRevisions = + connector.listVersionRevisions(sessionContext, new Id(itemId), new Id + (versionId)); + if(itemVersionRevisions == null || itemVersionRevisions.getItemVersionRevisions()==null || + itemVersionRevisions.getItemVersionRevisions().size()==0) { + return revisions; + } + else{ + revisions = itemVersionRevisions.getItemVersionRevisions().stream().map + (revision -> { + Revision rev = new Revision(); + rev.setId(revision.getRevisionId().getValue()); + rev.setTime(revision.getTime()); + rev.setUser(revision.getUser()); + rev.setMessage(revision.getMessage()); + return rev; + }).collect(Collectors.toList()); + revisions.sort(new Comparator<Revision>() { + @Override + public int compare(Revision o1, Revision o2) { + if(o1.getTime().before(o2.getTime())) return 1; + else return -1; + } + }); + // when creating a new item an initial version is created with + // invalid data. this revision is not an applicable revision. + //the logic of identifying this revision is: + //1- only the first version of item has this issue + //2- only in the first item version there are 2 revisions created + //3- the second revision is in format "Initial {vlm/vsp}: {name of the vlm/vsp} + //4- only if a revision in this format exists we remove the first revision. + if(revisions.size()>1 && revisions.get(revisions.size()-2).getMessage().matches("Initial " + + ".*:.*")){ + revisions.remove(revisions.size()-1); + } + return revisions; + } + } + + private static void sortItemVersionListByModificationTimeDescOrder( + List<ItemVersion> itemVersions) { + itemVersions.sort((o1, o2) -> ((Integer) o2.getId().getValue().length()) + .compareTo((o1.getId().getValue().length()))); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml index fba7d568e3..f8cfcfdc9b 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/pom.xml @@ -33,5 +33,32 @@ <artifactId>zusammen-state-store-cassandra-plugin</artifactId> <version>${zusammen-state-store.version}</version> </dependency> + <dependency> + <groupId>org.testng</groupId> + <artifactId>testng</artifactId> + <version>${testng.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <version>${mockito.all.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>com.amdocs.zusammen</groupId> + <artifactId>zusammen-commons-utils</artifactId> + <version>${zusammen.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-facade-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-session-lib</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> </project> diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java index 59afa70e9a..a973590eb5 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/ZusammenPluginUtil.java @@ -19,13 +19,30 @@ package org.openecomp.core.zusammen.plugin; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.Space; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionChange; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionDataConflict; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementChange; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementConflict; +import com.amdocs.zusammen.sdk.state.types.StateElement; +import com.amdocs.zusammen.sdk.types.ElementDescriptor; import com.amdocs.zusammen.utils.fileutils.FileUtils; +import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.Date; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; public class ZusammenPluginUtil { @@ -34,7 +51,7 @@ public class ZusammenPluginUtil { case PUBLIC: return ZusammenPluginConstants.PUBLIC_SPACE; case PRIVATE: - return ZusammenPluginUtil.getPrivateSpaceName(context); + return getPrivateSpaceName(context); default: throw new IllegalArgumentException(String.format("Space %s is not supported.", space)); } @@ -44,14 +61,54 @@ public class ZusammenPluginUtil { return context.getUser().getUserName(); } - public static ElementEntity getElementEntity(CollaborationElement element) { + public static ElementContext getPrivateElementContext(ElementContext elementContext) { + return new ElementContext(elementContext.getItemId(),elementContext.getVersionId(),Id.ZERO); + } + + + public static VersionEntity convertToVersionEntity(Id versionId, Id baseVersionId, + Date creationTime, + Date modificationTime) { + + return convertToVersionEntity(versionId, null, baseVersionId, + creationTime, modificationTime); + } + + public static VersionEntity convertToVersionEntity(Id versionId, Id revisionId, Id baseVersionId, + Date creationTime, + Date modificationTime) { + VersionEntity version = new VersionEntity(versionId); + version.setBaseId(baseVersionId); + version.setCreationTime(creationTime); + version.setModificationTime(modificationTime); + return version; + } + + public static ItemVersion convertToItemVersion(VersionEntity versionEntity, + ItemVersionData itemVersionData) { + ItemVersion itemVersion = new ItemVersion(); + itemVersion.setId(versionEntity.getId()); + + itemVersion.setBaseId(versionEntity.getBaseId()); + itemVersion.setCreationTime(versionEntity.getCreationTime()); + itemVersion.setModificationTime(versionEntity.getModificationTime()); + itemVersion.setData(itemVersionData); + return itemVersion; + } + + public static ElementEntity convertToElementEntity(CollaborationElement element) { + ElementEntity elementEntity = new ElementEntity(element.getId()); elementEntity.setNamespace(element.getNamespace()); elementEntity.setParentId(element.getParentId() == null - ? ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID + ? ROOT_ELEMENTS_PARENT_ID : element.getParentId()); + + elementEntity.setInfo(element.getInfo()); + elementEntity.setRelations(element.getRelations()); + if (element.getData() != null) { elementEntity.setData(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); } @@ -63,21 +120,29 @@ public class ZusammenPluginUtil { elementEntity.setVisualization( ByteBuffer.wrap(FileUtils.toByteArray(element.getVisualization()))); } + elementEntity.setElementHash(new Id(calculateElementHash(elementEntity))); + return elementEntity; } - public static CollaborationElement getCollaborationElement( - ElementEntityContext elementEntityContext, ElementEntity elementEntity) { - Id parentId = - ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID.equals(elementEntity.getParentId()) - ? null - : elementEntity.getParentId(); - CollaborationElement element = new CollaborationElement(elementEntityContext.getItemId(), - elementEntityContext.getVersionId(), elementEntity.getNamespace(), elementEntity.getId()); + public static ElementDescriptor convertToElementDescriptor( + ElementContext elementContext, ElementEntity elementEntity) { + if (elementEntity == null) { + return null; + } + ElementDescriptor element = new ElementDescriptor(elementContext.getItemId(), + elementContext.getVersionId(), elementEntity.getNamespace(), elementEntity.getId()); - element.setParentId(parentId); - element.setInfo(elementEntity.getInfo()); - element.setRelations(elementEntity.getRelations()); + mapElementEntityToDescriptor(elementEntity, element); + return element; + } + + public static CollaborationElement convertToCollaborationElement( + ElementContext elementContext, ElementEntity elementEntity) { + CollaborationElement element = new CollaborationElement(elementContext.getItemId(), + elementContext.getVersionId(), elementEntity.getNamespace(), elementEntity.getId()); + + mapElementEntityToDescriptor(elementEntity, element); if (elementEntity.getData() != null) { element.setData(new ByteArrayInputStream(elementEntity.getData().array())); @@ -89,7 +154,134 @@ public class ZusammenPluginUtil { if (elementEntity.getVisualization() != null) { element.setVisualization(new ByteArrayInputStream(elementEntity.getVisualization().array())); } + return element; + } + + public static CollaborationElementChange convertToElementChange( + ElementContext changedElementContext, ElementEntity changedElement, Action action) { + CollaborationElementChange elementChange = new CollaborationElementChange(); + elementChange.setElement(convertToCollaborationElement(changedElementContext, changedElement)); + elementChange.setAction(action); + return elementChange; + } + + public static ItemVersionChange convertToVersionChange(ElementContext elementContext, + ElementEntity versionDataElement, + Action action) { + ItemVersionChange versionChange = new ItemVersionChange(); + + ItemVersion itemVersion = new ItemVersion(); + itemVersion.setId(elementContext.getVersionId()); + + itemVersion.setData(convertToVersionData(versionDataElement)); + + versionChange.setItemVersion(itemVersion); + versionChange.setAction(action); + return versionChange; + } + + public static ItemVersionDataConflict getVersionConflict(ElementEntity localVesionData, + ElementEntity remoteVersionData) { + ItemVersionDataConflict versionConflict = new ItemVersionDataConflict(); + versionConflict.setLocalData(convertToVersionData(localVesionData)); + versionConflict.setRemoteData(convertToVersionData(remoteVersionData)); + return versionConflict; + } + + public static CollaborationElementConflict getElementConflict(ElementContext elementContext, + ElementEntity localElement, + ElementEntity remoteElement) { + CollaborationElementConflict elementConflict = new CollaborationElementConflict(); + elementConflict + .setLocalElement(convertToCollaborationElement(elementContext, localElement)); + elementConflict.setRemoteElement( + convertToCollaborationElement(elementContext, remoteElement)); + return elementConflict; + } + + public static ItemVersionData convertToVersionData(ElementEntity versionDataElement) { + ItemVersionData versionData = new ItemVersionData(); + versionData.setInfo(versionDataElement.getInfo()); + versionData.setRelations(versionDataElement.getRelations()); + return versionData; + } + + private static void mapElementEntityToDescriptor(ElementEntity elementEntity, + ElementDescriptor elementDescriptor) { + Id parentId = ROOT_ELEMENTS_PARENT_ID.equals(elementEntity.getParentId()) + ? null + : elementEntity.getParentId(); + + elementDescriptor.setParentId(parentId); + elementDescriptor.setInfo(elementEntity.getInfo()); + elementDescriptor.setRelations(elementEntity.getRelations()); + elementDescriptor.setSubElements(elementEntity.getSubElementIds()); + } + + public static String calculateElementHash(ElementEntity elementEntity) { + StringBuffer elementHash = new StringBuffer(); + if (elementEntity.getData() != null) { + elementHash.append(calculateSHA1(elementEntity.getData().array())); + } else { + elementHash.append("0"); + } + elementHash.append("_"); + if (elementEntity.getVisualization() != null) { + elementHash.append(calculateSHA1(elementEntity.getVisualization().array())); + } else { + elementHash.append("0"); + } + elementHash.append("_"); + + if (elementEntity.getSearchableData() != null) { + elementHash.append(calculateSHA1(elementEntity.getSearchableData().array())); + } else { + elementHash.append("0"); + } + elementHash.append("_"); + + if (elementEntity.getInfo() != null) { + elementHash.append(calculateSHA1(JsonUtil.object2Json(elementEntity.getInfo()).getBytes())); + } else { + elementHash.append("0"); + } + elementHash.append("_"); + + if (elementEntity.getRelations() != null) { + elementHash + .append(calculateSHA1(JsonUtil.object2Json(elementEntity.getRelations()).getBytes())); + } else { + elementHash.append("0"); + } + + return elementHash.toString(); + } + + private static String calculateSHA1(byte[] content2Convert) { + MessageDigest md = null; + try { + md = MessageDigest.getInstance("SHA-1"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return Base64.getEncoder().encodeToString(md.digest(content2Convert)); + } + + + public static StateElement getStateElement(ElementContext elementContext, ElementEntity + elementEntity) { + Id parentId = ROOT_ELEMENTS_PARENT_ID.equals(elementEntity.getParentId()) + ? null + : elementEntity.getParentId(); + StateElement element = new StateElement(elementContext.getItemId(), + elementContext.getVersionId(), elementEntity.getNamespace(), elementEntity.getId()); + + element.setParentId(parentId); + element.setInfo(elementEntity.getInfo()); + element.setRelations(elementEntity.getRelations()); element.setSubElements(elementEntity.getSubElementIds()); return element; } + + } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/CommitStagingService.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/CommitStagingService.java new file mode 100644 index 0000000000..45d5769e9c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/CommitStagingService.java @@ -0,0 +1,100 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Collection; +import java.util.Optional; + +public class CommitStagingService { + + private VersionPrivateStore versionPrivateStore; + private VersionStageStore versionStageStore; + private ElementPrivateStore elementPrivateStore; + private ElementStageStore elementStageStore; + + public CommitStagingService(VersionPrivateStore versionPrivateStore, + VersionStageStore versionStageStore, + ElementPrivateStore elementPrivateStore, + ElementStageStore elementStageStore) { + this.versionPrivateStore = versionPrivateStore; + this.versionStageStore = versionStageStore; + this.elementPrivateStore = elementPrivateStore; + this.elementStageStore = elementStageStore; + } + + public void commitStaging(SessionContext context, Id itemId, Id versionId) { + Optional<StageEntity<VersionEntity>> versionStage = + versionStageStore.get(context, itemId, new VersionEntity(versionId)); + + final ElementContext elementContext = new ElementContext(itemId, versionId, Id.ZERO); + Collection<ElementEntity> stagedElementIds = elementStageStore.listIds(context, elementContext); + + if ((!versionStage.isPresent() && stagedElementIds.isEmpty()) || + elementStageStore.hasConflicts(context, elementContext)) { + return; + } + + versionStage.ifPresent(verStage -> commitVersionStage(context, itemId, verStage)); + commitElementsStage(context, elementContext, stagedElementIds); + } + + private void commitVersionStage(SessionContext context, Id itemId, + StageEntity<VersionEntity> versionStage) { + switch (versionStage.getAction()) { + case CREATE: + versionPrivateStore.commitStagedCreate(context, itemId, versionStage.getEntity(), + versionStage.getPublishTime()); + break; + case UPDATE: + versionPrivateStore.commitStagedUpdate(context, itemId, versionStage.getEntity(), + versionStage.getPublishTime()); + break; + case IGNORE: + versionPrivateStore.commitStagedIgnore(context, itemId, versionStage.getEntity(), + versionStage.getPublishTime()); + break; + default: + throw new UnsupportedOperationException( + "Version change other then Create/Update/Ignore is not supported"); + } + + versionStageStore.delete(context, itemId, versionStage.getEntity()); + } + + private void commitElementsStage(SessionContext context, ElementContext elementContext, + Collection<ElementEntity> stagedElementIds) { + for (ElementEntity stagedElementId : stagedElementIds) { + StageEntity<ElementEntity> stagedElement = + elementStageStore.get(context, elementContext, stagedElementId) + .orElseThrow( + () -> new IllegalStateException("Element id returned by list must exist")); + switch (stagedElement.getAction()) { + case CREATE: + elementPrivateStore.commitStagedCreate(context, elementContext, stagedElement.getEntity(), + stagedElement.getPublishTime()); + break; + case UPDATE: + elementPrivateStore.commitStagedUpdate(context, elementContext, stagedElement.getEntity(), + stagedElement.getPublishTime()); + break; + case DELETE: + elementPrivateStore + .commitStagedDelete(context, elementContext, stagedElement.getEntity()); + break; + case IGNORE: + elementPrivateStore.commitStagedIgnore(context, elementContext, stagedElement.getEntity(), + stagedElement.getPublishTime()); + break; + default: + throw new UnsupportedOperationException( + "Element change other then Create/Update/Delete/Ignore is not supported"); + } + elementStageStore.delete(context, elementContext, stagedElement.getEntity()); + } + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java deleted file mode 100644 index ac103c0fbf..0000000000 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementCollaborationStore.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.openecomp.core.zusammen.plugin.collaboration; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.ElementContext; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; -import org.openecomp.core.zusammen.plugin.ZusammenPluginConstants; -import org.openecomp.core.zusammen.plugin.ZusammenPluginUtil; -import org.openecomp.core.zusammen.plugin.dao.ElementRepository; -import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; -import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Optional; - -import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getCollaborationElement; -import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; - - -public class ElementCollaborationStore { - - private static final String SUB_ELEMENT_NOT_EXIST_ERROR_MSG = - "List sub elements error: item %s, version %s - " + - "element %s, which appears as sub element of element %s, does not exist"; - - public Collection<CollaborationElement> listElements(SessionContext context, - ElementContext elementContext, - Id elementId) { - ElementEntityContext elementEntityContext = - new ElementEntityContext(ZusammenPluginUtil.getPrivateSpaceName(context), elementContext); - - if (elementId == null) { - elementId = ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; - } - - ElementRepository elementRepository = getElementRepository(context); - String elementIdValue = elementId.getValue(); - String versionIdValue = elementContext.getChangeRef() == null - ? elementContext.getVersionId().getValue() - : elementContext.getChangeRef(); - Collection<CollaborationElement> subElements = new ArrayList<>(); - - Optional<ElementEntity> element = - elementRepository.get(context, elementEntityContext, new ElementEntity(elementId)); - if (element.isPresent() && element.get().getSubElementIds() != null) { - for (Id subElementId : element.get().getSubElementIds()) { - ElementEntity subElement = - elementRepository.get(context, elementEntityContext, new ElementEntity(subElementId)) - .orElseThrow( - () -> new IllegalStateException(String.format(SUB_ELEMENT_NOT_EXIST_ERROR_MSG, - elementContext.getItemId().getValue(), versionIdValue, - subElementId.getValue(), elementIdValue))); - subElements.add(getCollaborationElement(elementEntityContext, subElement)); - } - } - return subElements; - } - - public CollaborationElement getElement(SessionContext context, ElementContext elementContext, - Id elementId) { - ElementEntityContext elementEntityContext = - new ElementEntityContext(ZusammenPluginUtil.getPrivateSpaceName(context), elementContext); - return getElementRepository(context) - .get(context, elementEntityContext, new ElementEntity(elementId)) - .map(elementEntity -> getCollaborationElement(elementEntityContext, elementEntity)) - .orElse(null); - } - - public void createElement(SessionContext context, CollaborationElement element) { - getElementRepository(context) - .create(context, - new ElementEntityContext(getSpaceName(context, element.getSpace()), - element.getItemId(), element.getVersionId()), - ZusammenPluginUtil.getElementEntity(element)); - } - - public void updateElement(SessionContext context, CollaborationElement element) { - getElementRepository(context) - .update(context, - new ElementEntityContext(getSpaceName(context, element.getSpace()), - element.getItemId(), element.getVersionId()), - ZusammenPluginUtil.getElementEntity(element)); - } - - public void deleteElement(SessionContext context, CollaborationElement element) { - deleteElementHierarchy(getElementRepository(context), - context, - new ElementEntityContext(getSpaceName(context, element.getSpace()), - element.getItemId(), element.getVersionId()), - ZusammenPluginUtil.getElementEntity(element)); - } - - public boolean checkHealth(SessionContext sessionContext) { - return getElementRepository(sessionContext).checkHealth(sessionContext); - } - - private void deleteElementHierarchy(ElementRepository elementRepository, SessionContext context, - ElementEntityContext elementEntityContext, - ElementEntity elementEntity) { - Optional<ElementEntity> retrieved = - elementRepository.get(context, elementEntityContext, elementEntity); - if (!retrieved.isPresent()) { - return; - } - retrieved.get().getSubElementIds().stream() - .map(ElementEntity::new) - .forEach(subElementEntity -> deleteElementHierarchy( - elementRepository, context, elementEntityContext, subElementEntity)); - - // only for the first one the parentId will populated (so it'll be removed from its parent) - elementRepository.delete(context, elementEntityContext, elementEntity); - } - - protected ElementRepository getElementRepository(SessionContext context) { - return ElementRepositoryFactory.getInstance().createInterface(context); - } -} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPrivateStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPrivateStore.java new file mode 100644 index 0000000000..045def2561 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPrivateStore.java @@ -0,0 +1,48 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import java.util.Optional; + +public interface ElementPrivateStore extends ElementStore { + + Map<Id, Id> listIds(SessionContext context, ElementContext elementContext); + + Collection<ElementEntity> listSubs(SessionContext context, ElementContext elementContext, + Id elementId); + + Optional<SynchronizationStateEntity> getSynchronizationState(SessionContext context, + ElementContext elementContext, + Id elementId); + + void create(SessionContext context, ElementContext elementContext, ElementEntity element); + + boolean update(SessionContext context, ElementContext elementContext, ElementEntity element); + + void delete(SessionContext context, ElementContext elementContext, ElementEntity element); + + void markAsPublished(SessionContext context, ElementContext elementContext, Id elementId, + Date publishTime); + + void markDeletionAsPublished(SessionContext context, ElementContext elementContext, Id elementId, + Date publishTime); + + void commitStagedCreate(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime); + + void commitStagedUpdate(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime); + + void commitStagedDelete(SessionContext context, ElementContext elementContext, + ElementEntity element); + + void commitStagedIgnore(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPublicStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPublicStore.java new file mode 100644 index 0000000000..0f1790a1bf --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementPublicStore.java @@ -0,0 +1,23 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; + +import java.util.Date; +import java.util.Map; + +public interface ElementPublicStore extends ElementStore { + + void create(SessionContext context, ElementContext elementContext, ElementEntity element, + Date publishTime); + + void update(SessionContext context, ElementContext elementContext, ElementEntity element, + Date publishTime); + + void delete(SessionContext context, ElementContext elementContext, ElementEntity element, + Date publishTime); + + Map<Id,Id> listIds(SessionContext context, ElementContext elementContext); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStageStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStageStore.java new file mode 100644 index 0000000000..a9236247f9 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStageStore.java @@ -0,0 +1,35 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Resolution; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.util.Collection; +import java.util.Optional; + +public interface ElementStageStore { + + Collection<ElementEntity> listIds(SessionContext context, ElementContext elementContext); + + boolean hasConflicts(SessionContext context, ElementContext elementContext); + + Collection<StageEntity<ElementEntity>> listConflictedDescriptors(SessionContext context, + ElementContext elementContext); + + Optional<StageEntity<ElementEntity>> get(SessionContext context, ElementContext elementContext, + ElementEntity element); + + Optional<StageEntity<ElementEntity>> getConflicted(SessionContext context, + ElementContext elementContext, + ElementEntity element); + + void create(SessionContext context, ElementContext elementContext, + StageEntity<ElementEntity> elementStage); + + void delete(SessionContext context, ElementContext elementContext, ElementEntity element); + + void resolveConflict(SessionContext context, ElementContext elementContext, ElementEntity element, + Resolution resolution); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStore.java new file mode 100644 index 0000000000..1c26a817ae --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ElementStore.java @@ -0,0 +1,20 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Optional; + +public interface ElementStore { + Optional<ElementEntity> get(SessionContext context, ElementContext elementContext, Id elementId); + + Optional<ElementEntity> getDescriptor(SessionContext context, ElementContext elementContext, + Id elementId); + + Collection<SynchronizationStateEntity> listSynchronizationStates(SessionContext context, + ElementContext elementContext); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ErrorCode.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ErrorCode.java new file mode 100644 index 0000000000..3d0910072c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/ErrorCode.java @@ -0,0 +1,5 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +public class ErrorCode { + public static final int NO_CHANGES_TO_PUBLISH = 60000; +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/Message.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/Message.java new file mode 100644 index 0000000000..2816974307 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/Message.java @@ -0,0 +1,6 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +public class Message { + public static final String NO_CHANGES_TO_PUBLISH = + "Item Id %s, version Id %s: There are no changes to publish."; +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/PublishService.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/PublishService.java new file mode 100644 index 0000000000..7b043c830f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/PublishService.java @@ -0,0 +1,201 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.response.ReturnCode; +import com.amdocs.zusammen.datatypes.response.ZusammenException; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeChange; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationPublishResult; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; + +import static com.amdocs.zusammen.datatypes.response.Module.ZCSP; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToElementChange; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToVersionChange; +import static org.openecomp.core.zusammen.plugin.collaboration.ErrorCode.NO_CHANGES_TO_PUBLISH; + +public class PublishService { + // TODO: 6/29/2017 throw ZusammenException with ReturnCode when needed. + private static final String PUSH_NON_EXISTING_VERSION = + "Item Id %s, version Id %s: Non existing version cannot be pushed."; + + private VersionPublicStore versionPublicStore; + private VersionPrivateStore versionPrivateStore; + private ElementPublicStore elementPublicStore; + private ElementPrivateStore elementPrivateStore; + + public PublishService(VersionPublicStore versionPublicStore, + VersionPrivateStore versionPrivateStore, + ElementPublicStore elementPublicStore, + ElementPrivateStore elementPrivateStore) { + this.versionPublicStore = versionPublicStore; + this.versionPrivateStore = versionPrivateStore; + this.elementPublicStore = elementPublicStore; + this.elementPrivateStore = elementPrivateStore; + } + + public CollaborationPublishResult publish(SessionContext context, Id itemId, Id versionId, + String message) { + CollaborationPublishResult result = new CollaborationPublishResult(); + result.setChange(new CollaborationMergeChange()); + + Date publishTime = new Date(); + Id revisionId = new Id(UUID.randomUUID().toString()); + boolean versionFirstPublication = publishVersion(context, itemId, versionId, revisionId, + publishTime,message); + if (versionFirstPublication) { + publishAllElements(context, new ElementContext(itemId, versionId, revisionId), publishTime, + result); + } else { + publishDirtyElements(context, new ElementContext(itemId, versionId, revisionId), publishTime, + result); + } + return result; + } + + private boolean publishVersion(SessionContext context, Id itemId, Id versionId, Id revisionId, + Date publishTime, String message) { + SynchronizationStateEntity privateVersionSyncState = + versionPrivateStore.getSynchronizationState(context, itemId, versionId) + .orElseThrow(() -> new IllegalArgumentException( + String.format(PUSH_NON_EXISTING_VERSION, itemId.toString(), versionId.toString()))); + + if (!privateVersionSyncState.isDirty()) { + throw new ZusammenException(new ReturnCode(NO_CHANGES_TO_PUBLISH, ZCSP, + String.format(Message.NO_CHANGES_TO_PUBLISH, itemId, versionId), null)); + } + + Optional<SynchronizationStateEntity> publicVersionSyncState = + versionPublicStore.getSynchronizationState(context, itemId, versionId); + + // private must be synced with public (if public exists) + if (publicVersionSyncState.isPresent() && + !privateVersionSyncState.getPublishTime() + .equals(publicVersionSyncState.get().getPublishTime())) { + // should not happen as it is validated in zusammen-core + throw new UnsupportedOperationException("Out of sync item version can not be publish"); + } + + boolean versionFirstPublication; + Map<Id, Id> versionElementIds = + elementPublicStore.listIds(context, new ElementContext(itemId, + versionId)); + if (publicVersionSyncState.isPresent()) { + versionPublicStore.update(context, itemId, new VersionEntity(versionId), revisionId, + versionElementIds,publishTime,message); + versionFirstPublication = false; + } else { + VersionEntity privateVersion = versionPrivateStore.get(context, itemId, versionId) + .orElseThrow(() -> new IllegalArgumentException( + String.format(PUSH_NON_EXISTING_VERSION, itemId.toString(), versionId.toString()))); + versionPublicStore.create(context, itemId, privateVersion, revisionId,versionElementIds, + publishTime,message); + versionFirstPublication = true; + } + versionPrivateStore.markAsPublished(context, itemId, versionId, publishTime); + return versionFirstPublication; + } + + private void publishAllElements(SessionContext context, ElementContext elementContext, + Date publishTime, CollaborationPublishResult result) { + Collection<SynchronizationStateEntity> privateElementSyncStates = + elementPrivateStore.listSynchronizationStates(context, elementContext); + + for (SynchronizationStateEntity privateElementSyncState : privateElementSyncStates) { + Optional<ElementEntity> privateElement = + elementPrivateStore.get(context, elementContext, privateElementSyncState.getId()); + + if (!privateElement.isPresent()) { + continue; + } + ElementEntity elementToPublish = privateElement.get(); + + elementPublicStore.create(context, elementContext, elementToPublish, + privateElementSyncState.isDirty() ? publishTime + : privateElementSyncState.getPublishTime()); + + if (privateElementSyncState.isDirty()) { + elementPrivateStore + .markAsPublished(context, elementContext, privateElementSyncState.getId(), publishTime); + } + updateResult(elementContext, elementToPublish, Action.CREATE, + ROOT_ELEMENTS_PARENT_ID.equals(privateElementSyncState.getId()), result); + } + } + + private void publishDirtyElements(SessionContext context, ElementContext elementContext, + Date publishTime, CollaborationPublishResult result) { + + Id revisionId = elementContext.getRevisionId(); + elementContext.setRevisionId(revisionId); + ElementContext privateElementContext = new ElementContext(elementContext.getItemId(), + elementContext.getVersionId(),Id.ZERO); + Collection<SynchronizationStateEntity> privateElementSyncStates = + elementPrivateStore.listSynchronizationStates(context, elementContext); + + Collection<SynchronizationStateEntity> publicElementSyncStates = + elementPublicStore.listSynchronizationStates(context, elementContext); + + for (SynchronizationStateEntity privateElementSyncState : privateElementSyncStates) { + if (!privateElementSyncState.isDirty()) { + continue; + } + + Optional<ElementEntity> privateElement = + elementPrivateStore.get(context, privateElementContext, privateElementSyncState.getId()); + + ElementEntity elementToPublish; + Action actionOnPublic; + if (privateElement.isPresent()) { + elementToPublish = privateElement.get(); + + if (publicElementSyncStates.contains(privateElementSyncState)) { + + elementPublicStore.update(context, elementContext, elementToPublish, publishTime); + actionOnPublic = Action.UPDATE; + } else { + elementPublicStore.create(context, elementContext, elementToPublish, publishTime); + actionOnPublic = Action.CREATE; + } + + elementPrivateStore + .markAsPublished(context, privateElementContext, privateElementSyncState.getId(), publishTime); + } else { + elementToPublish = + elementPublicStore.get(context, elementContext, privateElementSyncState.getId()) + .orElseThrow(() -> new IllegalStateException( + "Element that should be deleted from public must exist there")); + elementPublicStore.delete(context, elementContext, elementToPublish, publishTime); + actionOnPublic = Action.DELETE; + + elementPrivateStore + .markDeletionAsPublished(context, privateElementContext, privateElementSyncState.getId(), + publishTime); + } + + updateResult(elementContext, elementToPublish, actionOnPublic, + ROOT_ELEMENTS_PARENT_ID.equals(privateElementSyncState.getId()), result); + } + } + + private void updateResult(ElementContext elementContext, ElementEntity element, + Action action, boolean versionDataElement, + CollaborationPublishResult result) { + if (versionDataElement) { + result.getChange().setChangedVersion(convertToVersionChange(elementContext, element, action)); + } else { + result.getChange().getChangedElements() + .add(convertToElementChange(elementContext, element, action)); + } + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/RevertService.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/RevertService.java new file mode 100644 index 0000000000..0d2ea2c0d8 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/RevertService.java @@ -0,0 +1,161 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class RevertService { + + private ElementPublicStore elementPublicStore; + private ElementPrivateStore elementPrivateStore; + + public RevertService(ElementPublicStore elementPublicStore, + ElementPrivateStore elementPrivateStore) { + this.elementPublicStore = elementPublicStore; + this.elementPrivateStore = elementPrivateStore; + } + + public void revert(SessionContext context, Id itemId, Id versionId, Id revisionId) { + ElementContext targetContext = new ElementContext(itemId, versionId); + ElementContext sourceContext = new ElementContext(itemId, versionId, revisionId); + copyElementsFromPublic(context, sourceContext, targetContext); + } + + private void copyElementsFromPublic(SessionContext context, ElementContext sourceContext, + ElementContext targetContext) { + Collection<RevertElementAction> revertElementActions = + evaluateRevertElementActions(context, sourceContext, targetContext); + + revertElementActions.forEach(revertElementAction -> revertElementAction.run(context)); + } + + private Collection<RevertElementAction> evaluateRevertElementActions(SessionContext context, + ElementContext sourceContext, + ElementContext targetContext) { + + Map<Id, Id> sourceElements = elementPublicStore.listIds(context, sourceContext); + Map<Id, Id> targetPublicElements = elementPublicStore.listIds(context, targetContext); + Collection<SynchronizationStateEntity> synchronizationStateEntities = + elementPrivateStore.listSynchronizationStates(context, targetContext); + + Map<Id, Id> targetElements = + evaluateTargetElements(targetPublicElements, synchronizationStateEntities); + + + Collection<RevertElementAction> revertElementActions = new ArrayList<>(); + + sourceElements.entrySet().forEach(entry -> { + Id sourceElementId = entry.getKey(); + Id sourceElementRevisionId = entry.getValue(); + + if (!targetElements.containsKey(sourceElementId)) { + revertElementActions + .add(new RevertElementAction(sourceContext, sourceElementId, commands[CREATE])); + } else if (!targetElements.get(sourceElementId).equals(sourceElementRevisionId)) { + revertElementActions + .add(new RevertElementAction(sourceContext, sourceElementId, commands[UPDATE])); + } + }); + + targetElements.entrySet().forEach(entry -> { + Id targetElementId = entry.getKey(); + if (!sourceElements.containsKey(targetElementId)) { + revertElementActions + .add(new RevertElementAction(targetContext, targetElementId, commands[DELETE])); + } + }); + + return revertElementActions; + } + + private Map<Id, Id> evaluateTargetElements(Map<Id, Id> targetPublicElements, + Collection<SynchronizationStateEntity> syncStates) { + Map<Id, Id> targetElements = new HashMap<>(targetPublicElements); + syncStates.stream() + .filter(SynchronizationStateEntity::isDirty) + .forEach(syncState -> targetElements.put(syncState.getId(), Id.ZERO)); + return targetElements; + } + + private static class RevertElementAction { + private ElementContext elementContext; + private Id elementId; + private ActionCommand command; + + private RevertElementAction(ElementContext elementContext, Id elementId, + ActionCommand command) { + this.elementContext = elementContext; + this.elementId = elementId; + this.command = command; + } + + public ElementContext getElementContext() { + return elementContext; + } + + public Id getElementId() { + return elementId; + } + + public void run(SessionContext context) { + command.run(context, elementContext, elementId); + } + } + + private interface ActionCommand { + void run(SessionContext context, ElementContext elementContext, Id elementId); + } + + private static int CREATE = 0; + private static int UPDATE = 1; + private static int DELETE = 2; + + private ActionCommand[] commands = {new ActionCommand() { + @Override + public void run(SessionContext context, ElementContext elementContext, Id elementId) { + //create + Optional<ElementEntity> element = elementPublicStore.get(context, elementContext, elementId); + if (!element.isPresent()) { + throw getMissingElementException(elementContext, elementId); + } + elementPrivateStore.create(context, elementContext, element.get()); + } + }, new ActionCommand() { + @Override + public void run(SessionContext context, ElementContext elementContext, Id elementId) { + //update + Optional<ElementEntity> element = elementPublicStore.get(context, elementContext, elementId); + if (!element.isPresent()) { + throw getMissingElementException(elementContext, elementId); + } + elementPrivateStore.update(context, elementContext, element.get()); + } + }, new ActionCommand() { + @Override + public void run(SessionContext context, ElementContext elementContext, Id elementId) { + //delete + Optional<ElementEntity> element = elementPrivateStore.get(context, elementContext, elementId); + if (!element.isPresent()) { + return; // deleted by parent when hierarchy was deleted + } + elementPrivateStore.delete(context, elementContext, element.get()); + } + }}; + + private RuntimeException getMissingElementException(ElementContext elementContext, + Id elementId) { + return new IllegalStateException( + String.format("Item Id %s, version Id %s, revision Id %s: Missing element with Id %s", + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue(), elementId.getValue()) + ); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/SyncService.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/SyncService.java new file mode 100644 index 0000000000..04a7e9ffb1 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/SyncService.java @@ -0,0 +1,384 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeChange; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeConflict; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeResult; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; + +public class SyncService { + private static final String PULL_NON_EXISTING_VERSION = + "Item Id %s, version Id %s: Non existing version cannot be synced."; + private static final String PUBLIC_SYNC_STATE_EXISTS_WITHOUT_ELEMENT = + "Item Id %s, version Id %s: Sync state of element with Id %s " + + "exists in public space while the element does not"; + private static final String PRIVATE_UNPUBLISHED_SYNC_STATE_EXISTS_WITHOUT_ELEMENT = + "Item Id %s, version Id %s: Sync state of unpublished element with Id %s " + + "exists in private space while the element does not"; + + private VersionPublicStore versionPublicStore; + private VersionPrivateStore versionPrivateStore; + private VersionStageStore versionStageStore; + private ElementPublicStore elementPublicStore; + private ElementPrivateStore elementPrivateStore; + private ElementStageStore elementStageStore; + + public SyncService(VersionPublicStore versionPublicStore, + VersionPrivateStore versionPrivateStore, + VersionStageStore versionStageStore, + ElementPublicStore elementPublicStore, + ElementPrivateStore elementPrivateStore, + ElementStageStore elementStageStore) { + this.versionPublicStore = versionPublicStore; + this.versionPrivateStore = versionPrivateStore; + this.versionStageStore = versionStageStore; + this.elementPublicStore = elementPublicStore; + this.elementPrivateStore = elementPrivateStore; + this.elementStageStore = elementStageStore; + } + + public CollaborationMergeResult sync(SessionContext context, Id itemId, Id versionId, + boolean force) { + SynchronizationStateEntity publicVersionSyncState = + versionPublicStore.getSynchronizationState(context, itemId, versionId) + .orElseThrow(() -> new IllegalStateException( + String.format(PULL_NON_EXISTING_VERSION, itemId.toString(), versionId.toString()))); + + Date publishTime = publicVersionSyncState.getPublishTime(); + + Optional<SynchronizationStateEntity> privateVersionSyncState = + versionPrivateStore.getSynchronizationState(context, itemId, versionId); + + if (force || !privateVersionSyncState.isPresent() || + !publishTime.equals(privateVersionSyncState.get().getPublishTime())) { + ElementContext elementContext = + new ElementContext(itemId, versionId, publicVersionSyncState.getRevisionId()); + + Collection<SynchronizationStateEntity> publicSyncStates = + elementPublicStore.listSynchronizationStates(context, elementContext); + Collection<SynchronizationStateEntity> privateSyncStates = + elementPrivateStore.listSynchronizationStates(context, elementContext); + Map<Id, SynchronizationStateEntity> publicSyncStateById = toMapById(publicSyncStates); + + Set<Id> syncedElements = new HashSet<>(); + if (force) { + List<SynchronizationStateEntity> dirtyPrivateSyncStates = privateSyncStates.stream() + .filter(SynchronizationStateEntity::isDirty) + .collect(Collectors.toList()); + + forceSyncDirtyElements(context, elementContext, dirtyPrivateSyncStates, publicSyncStateById, + syncedElements); + } + + if (!privateVersionSyncState.isPresent() || + !publishTime.equals(privateVersionSyncState.get().getPublishTime())) { + syncVersion(context, itemId, versionId, publishTime, privateVersionSyncState.isPresent()); + syncElements(context, elementContext, + privateVersionSyncState.map(SynchronizationStateEntity::getPublishTime).orElse(null), + publicSyncStates, privateSyncStates, publicSyncStateById, syncedElements); + } + } + + return createResult(); + } + + private CollaborationMergeResult createResult() { + CollaborationMergeResult result = new CollaborationMergeResult(); + result.setChange(new CollaborationMergeChange()); + result.setConflict(new CollaborationMergeConflict()); + return result; + } + + private void syncVersion(SessionContext context, Id itemId, Id versionId, Date publishTime, + boolean versionExistOnPrivate) { + if (versionExistOnPrivate) { + stageVersion(context, itemId, new VersionEntity(versionId), Action.UPDATE, publishTime); + } else { + stageVersion(context, itemId, versionPublicStore.get(context, itemId, versionId) + .orElseThrow(() -> new IllegalArgumentException(String + .format(PULL_NON_EXISTING_VERSION, itemId.toString(), versionId.toString()))), + Action.CREATE, publishTime); + } + } + + private void syncElements(SessionContext context, ElementContext elementContext, + Date previousSyncedPublishTime, + Collection<SynchronizationStateEntity> publicSyncStates, + Collection<SynchronizationStateEntity> privateSyncStates, + Map<Id, SynchronizationStateEntity> publicSyncStateById, + Set<Id> syncedElements) { + Map<Id, SynchronizationStateEntity> privateSyncStateById = toMapById(privateSyncStates); + + Collection<SynchronizationStateEntity> updatedPublicSyncStates = + previousSyncedPublishTime == null + ? publicSyncStates + : publicSyncStates.stream() + .filter(syncState -> syncState.getPublishTime().after(previousSyncedPublishTime)) + .collect(Collectors.toList()); + + syncPublicUpdatedElements(context, elementContext, updatedPublicSyncStates, + publicSyncStateById, privateSyncStateById, syncedElements); + + List<SynchronizationStateEntity> onlyOnPrivatePublishedSyncStates = + privateSyncStates.stream() + .filter(syncState -> !publicSyncStateById.containsKey(syncState.getId()) && + syncState.getPublishTime() != null) + .collect(Collectors.toList()); + + syncPublicDeletedElements(context, elementContext, onlyOnPrivatePublishedSyncStates, + publicSyncStateById, privateSyncStateById, syncedElements); + } + + private void syncPublicUpdatedElements(SessionContext context, ElementContext elementContext, + Collection<SynchronizationStateEntity> updatedPublicSyncStates, + Map<Id, SynchronizationStateEntity> publicSyncStateById, + Map<Id, SynchronizationStateEntity> privateSyncStateById, + Set<Id> syncedElements) { + for (SynchronizationStateEntity publicSyncState : updatedPublicSyncStates) { + if (syncedElements.contains(publicSyncState.getId())) { + continue; + } + + ElementEntity publicElement = + elementPublicStore.get(context, elementContext, publicSyncState.getId()).orElseThrow( + () -> new IllegalStateException(String + .format(PUBLIC_SYNC_STATE_EXISTS_WITHOUT_ELEMENT, + elementContext.getItemId().getValue(), + elementContext.getVersionId().getValue(), + publicSyncState.getId().getValue()))); + + SynchronizationStateEntity privateSyncState = + privateSyncStateById.get(publicSyncState.getId()); + + if (privateSyncState != null) { + if (!privateSyncState.isDirty()) { + // not changed on private + stageElement(context, elementContext, publicElement, + publicSyncState.getPublishTime(), + Action.UPDATE, false, null); + syncedElements.add(publicSyncState.getId()); + } else { + Optional<ElementEntity> privateElement = + elementPrivateStore.get(context, elementContext, publicSyncState.getId()); + + if (privateElement.isPresent()) { + // updated on private - conflict if it has different hash + stageElement(context, elementContext, publicElement, + publicSyncState.getPublishTime(), Action.UPDATE, + !publicElement.getElementHash().equals(privateElement.get().getElementHash()), + null); + + syncedElements.add(publicSyncState.getId()); + } else { + // deleted on private - conflict tree + Set<Id> changeTreeElementIds = + stagePublicElementTree(context, elementContext, publicElement, publicSyncStateById, + (treeElementIds) -> true); + syncedElements.addAll(changeTreeElementIds); + } + } + } else { + // not existing on private - new creation on public + Set<Id> changeTreeElementIds = + stagePublicElementTree(context, elementContext, publicElement, publicSyncStateById, + (treeElementIds) -> containsDirty(treeElementIds, privateSyncStateById)); + syncedElements.addAll(changeTreeElementIds); + } + } + } + + private void syncPublicDeletedElements( + SessionContext context, ElementContext elementContext, + Collection<SynchronizationStateEntity> onlyOnPrivatePublishedSyncStates, + Map<Id, SynchronizationStateEntity> publicSyncStateById, + Map<Id, SynchronizationStateEntity> privateSyncStateById, + Set<Id> syncedElements) { + for (SynchronizationStateEntity privateSyncState : onlyOnPrivatePublishedSyncStates) { + if (syncedElements.contains(privateSyncState.getId())) { + continue; + } + + Optional<ElementEntity> privateElement = + elementPrivateStore.get(context, elementContext, privateSyncState.getId()); + + if (!privateElement.isPresent()) { + // deleted on private as well + stageElement(context, elementContext, new ElementEntity(privateSyncState.getId()), + null, Action.DELETE, false, null); + syncedElements.add(privateSyncState.getId()); + } else { + Set<Id> changeTreeElementIds = + stageElementTree(context, elementContext, privateElement.get(), + elementPrivateStore, publicSyncStateById::containsKey, + (treeElementIds) -> containsDirty(treeElementIds, privateSyncStateById), + (elementId) -> null, Action.DELETE); + syncedElements.addAll(changeTreeElementIds); + } + } + } + + private void forceSyncDirtyElements(SessionContext context, ElementContext elementContext, + List<SynchronizationStateEntity> dirtyPrivateSyncStates, + Map<Id, SynchronizationStateEntity> publicSyncStateById, + Set<Id> syncedElements) { + for (SynchronizationStateEntity privateSyncState : dirtyPrivateSyncStates) { + Optional<ElementEntity> privateElement = + elementPrivateStore.get(context, elementContext, privateSyncState.getId()); + if (privateSyncState.getPublishTime() == null) { + stageElement(context, elementContext, + privateElement.orElseThrow(() -> new IllegalStateException( + String.format(PRIVATE_UNPUBLISHED_SYNC_STATE_EXISTS_WITHOUT_ELEMENT, + elementContext.getItemId().getValue(), + elementContext.getVersionId().getValue(), + privateSyncState.getId().getValue()))), + null, Action.DELETE, false, null); + } else { + SynchronizationStateEntity publicSyncState = + publicSyncStateById.get(privateSyncState.getId()); + if (publicSyncState != null) { + ElementEntity publicElement = + elementPublicStore.get(context, elementContext, privateSyncState.getId()).orElseThrow( + () -> new IllegalStateException(String + .format(PUBLIC_SYNC_STATE_EXISTS_WITHOUT_ELEMENT, + elementContext.getItemId().getValue(), + elementContext.getVersionId().getValue(), + privateSyncState.getId().getValue()))); + + stageElement(context, elementContext, publicElement, publicSyncState.getPublishTime(), + privateElement.isPresent() ? Action.UPDATE : Action.CREATE, false, null); + } else { + stageElement(context, elementContext, privateElement.isPresent() + ? privateElement.get() + : new ElementEntity(privateSyncState.getId()), + null, Action.DELETE, false, null); + } + } + syncedElements.add(privateSyncState.getId()); + } + } + + private Set<Id> stagePublicElementTree(SessionContext context, + ElementContext elementContext, + ElementEntity publicElement, + Map<Id, SynchronizationStateEntity> publicSyncStateById, + Predicate<Set<Id>> isElementTreeConflicted) { + + + return stageElementTree(context, elementContext, publicElement, + elementPublicStore, + (elementId) -> elementPrivateStore.getDescriptor(context, elementContext, elementId) + .isPresent(), + isElementTreeConflicted, + (elementId) -> publicSyncStateById.get(elementId).getPublishTime(), + Action.CREATE); + } + + private Set<Id> stageElementTree(SessionContext context, ElementContext elementContext, + ElementEntity element, + ElementStore elementStore, + Predicate<Id> isElementExist, + Predicate<Set<Id>> isElementTreeConflicted, + Function<Id, Date> stagePublishTimeGetter, + Action stageAction) { + ElementEntity elementTreeRoot = findRootElementOfChange(context, elementContext, + elementStore, isElementExist, element); + + Set<Id> elementTreeIds = new HashSet<>(); + elementTreeIds.add(elementTreeRoot.getId()); + + Set<Id> subElementIds = stageElementSubs(context, elementContext, elementStore, elementTreeRoot, + stagePublishTimeGetter, stageAction); + elementTreeIds.addAll(subElementIds); + + boolean conflicted = isElementTreeConflicted.test(elementTreeIds); + stageElement(context, elementContext, elementTreeRoot, + stagePublishTimeGetter.apply(elementTreeRoot.getId()), stageAction, conflicted, + conflicted ? subElementIds : null); + return elementTreeIds; + } + + private ElementEntity findRootElementOfChange(SessionContext context, + ElementContext elementContext, + ElementStore elementStore, + Predicate<Id> isElementExistOnOppositeStore, + ElementEntity element) { + return element.getId().equals(ROOT_ELEMENTS_PARENT_ID) || + isElementExistOnOppositeStore.test(element.getParentId()) + ? element + : findRootElementOfChange(context, elementContext, elementStore, + isElementExistOnOppositeStore, + elementStore.get(context, elementContext, element.getParentId()) + .orElseThrow(() -> new IllegalStateException( + String.format("Element %s exists while its parent element %s does not", + element.getId(), element.getParentId())))); + } + + private boolean containsDirty(Set<Id> elementIds, + Map<Id, SynchronizationStateEntity> syncStateById) { + return elementIds.stream().anyMatch(elementId -> { + SynchronizationStateEntity privateSyncState = syncStateById.get(elementId); + return privateSyncState != null && privateSyncState.isDirty(); + }); + } + + private Set<Id> stageElementSubs(SessionContext context, ElementContext elementContext, + ElementStore elementStore, ElementEntity parentElement, + Function<Id, Date> stagePublishTimeGetter, Action stageAction) { + Set<Id> elementTreeIds = new HashSet<>(); + for (Id elementId : parentElement.getSubElementIds()) { + ElementEntity element = elementStore.get(context, elementContext, elementId).get(); + + stageElement(context, elementContext, element, stagePublishTimeGetter.apply(elementId), + stageAction, false, null); + + elementTreeIds.add(elementId); + elementTreeIds.addAll( + stageElementSubs(context, elementContext, elementStore, element, stagePublishTimeGetter, + stageAction)); + } + return elementTreeIds; + } + + private void stageElement(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime, Action action, + boolean conflicted, Set<Id> conflictDependents) { + StageEntity<ElementEntity> elementStage = + new StageEntity<>(element, publishTime, action, conflicted); + if (conflictDependents != null) { + elementStage.setConflictDependents( + conflictDependents.stream().map(ElementEntity::new).collect(Collectors.toSet())); + } + elementStageStore.create(context, elementContext, elementStage); + } + + private void stageVersion(SessionContext context, Id itemId, VersionEntity stageVersion, + Action stageAction, Date publishTime) { + versionStageStore + .create(context, itemId, new StageEntity<>(stageVersion, publishTime, stageAction, false)); + } + + private Map<Id, SynchronizationStateEntity> toMapById( + Collection<SynchronizationStateEntity> syncStates) { + return syncStates.stream() + .collect(Collectors.toMap(SynchronizationStateEntity::getId, Function.identity())); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java deleted file mode 100644 index db3066c313..0000000000 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStore.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.openecomp.core.zusammen.plugin.collaboration; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.Space; -import com.amdocs.zusammen.datatypes.item.Action; -import com.amdocs.zusammen.datatypes.itemversion.Tag; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementChange; -import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeChange; -import org.openecomp.core.zusammen.plugin.ZusammenPluginUtil; -import org.openecomp.core.zusammen.plugin.dao.ElementRepository; -import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; -import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; - -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; -import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; - -public class VersionCollaborationStore { - - public void tagItemVersion(SessionContext context, Id itemId, Id versionId, Id changeId, - Tag tag) { - if (changeId != null) { - throw new UnsupportedOperationException( - "In this plugin implementation tag is supported only on versionId"); - } - String space = getSpaceName(context, Space.PRIVATE); - ElementEntityContext targetContext = new ElementEntityContext(space, itemId, versionId); - targetContext.setChangeRef(tag.getName()); - copyElements(context, new ElementEntityContext(space, itemId, versionId), targetContext, - getElementRepository(context)); - } - - public CollaborationMergeChange resetItemVersionHistory(SessionContext context, Id itemId, - Id versionId, String changeRef) { - ElementRepository elementRepository = getElementRepository(context); - - String spaceName = getSpaceName(context, Space.PRIVATE); - ElementEntityContext versionContext = new ElementEntityContext(spaceName, itemId, versionId); - - Collection<ElementEntity> deletedElements = - deleteElements(context, versionContext, elementRepository); - - ElementEntityContext changeRefContext = new ElementEntityContext(spaceName, itemId, versionId); - changeRefContext.setChangeRef(changeRef); - - Collection<ElementEntity> createdElements = - copyElements(context, changeRefContext, versionContext, elementRepository); - - // TODO: 4/19/2017 version change... - return createCollaborationMergeChange(versionContext, deletedElements, createdElements); - } - - private Collection<ElementEntity> deleteElements(SessionContext context, - ElementEntityContext elementContext, - ElementRepository elementRepository) { - Collection<ElementEntity> elements = elementRepository.list(context, elementContext); - elements.forEach(element -> elementRepository - .delete(context, elementContext, new ElementEntity(element.getId()))); - elementRepository.delete(context, elementContext, new ElementEntity(ROOT_ELEMENTS_PARENT_ID)); - return elements; - } - - private Collection<ElementEntity> copyElements(SessionContext context, - ElementEntityContext sourceElementContext, - ElementEntityContext targetElementContext, - ElementRepository elementRepository) { - Collection<ElementEntity> elements = elementRepository.list(context, sourceElementContext); - elements.forEach(elementEntity -> - elementRepository.create(context, targetElementContext, elementEntity)); - return elements; - } - - private CollaborationMergeChange createCollaborationMergeChange( - ElementEntityContext versionContext, - Collection<ElementEntity> deletedElements, - Collection<ElementEntity> createdElements) { - CollaborationMergeChange mergeChange = new CollaborationMergeChange(); - mergeChange.getChangedElements().addAll( - convertToCollaborationElementChanges(versionContext, deletedElements, Action.DELETE)); - mergeChange.getChangedElements().addAll( - convertToCollaborationElementChanges(versionContext, createdElements, Action.CREATE)); - return mergeChange; - } - - private List<CollaborationElementChange> convertToCollaborationElementChanges( - ElementEntityContext elementContext, Collection<ElementEntity> changedElements, - Action action) { - return changedElements.stream() - .map(element -> convertToCollaborationElementChange(element, elementContext, action)) - .collect(Collectors.toList()); - } - - private CollaborationElementChange convertToCollaborationElementChange( - ElementEntity elementEntity, ElementEntityContext elementContext, Action action) { - CollaborationElementChange elementChange = new CollaborationElementChange(); - elementChange - .setElement(ZusammenPluginUtil.getCollaborationElement(elementContext, elementEntity)); - elementChange.setAction(action); - return elementChange; - } - - protected ElementRepository getElementRepository(SessionContext context) { - return ElementRepositoryFactory.getInstance().createInterface(context); - } -} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPrivateStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPrivateStore.java new file mode 100644 index 0000000000..a024327548 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPrivateStore.java @@ -0,0 +1,38 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Date; +import java.util.Optional; + +public interface VersionPrivateStore { + Optional<VersionEntity> get(SessionContext context, Id itemId, Id versionId); + + Optional<SynchronizationStateEntity> getSynchronizationState(SessionContext context, Id itemId, + Id versionId); + + void create(SessionContext context, Id itemId, VersionEntity version); + + void update(SessionContext context, Id itemId, VersionEntity version); + + void update(SessionContext context, Id itemId, VersionEntity version, Date publishTime, + boolean dirty); + + void delete(SessionContext context, Id itemId, VersionEntity version); + + void markAsPublished(SessionContext context, Id itemId, Id versionId, Date publishTime); + + void commitStagedCreate(SessionContext context, Id itemId, VersionEntity version, + Date publishTime); + + void commitStagedUpdate(SessionContext context, Id itemId, VersionEntity version, + Date publishTime); + + void commitStagedIgnore(SessionContext context, Id itemId, VersionEntity version, + Date publishTime); + + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPublicStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPublicStore.java new file mode 100644 index 0000000000..c86db0ec43 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionPublicStore.java @@ -0,0 +1,29 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Date; +import java.util.Map; +import java.util.Optional; + +public interface VersionPublicStore { + + Optional<VersionEntity> get(SessionContext context, Id itemId, Id versionId); + + Optional<SynchronizationStateEntity> getSynchronizationState(SessionContext context, + Id itemId, Id versionId); + + void create(SessionContext context, Id itemId, VersionEntity version, Id revisionId, + Map<Id, Id> versionElementIds, Date publishTime, String message); + + void update(SessionContext context, Id itemId, VersionEntity version, Id revisionId, + Map<Id, Id> versionElementIds, Date publishTime, String message); + + boolean checkHealth(SessionContext context); + + ItemVersionRevisions listItemVersionRevisions(SessionContext context, Id itemId, Id versionId); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionStageStore.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionStageStore.java new file mode 100644 index 0000000000..5058a262cc --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/VersionStageStore.java @@ -0,0 +1,18 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Optional; + +public interface VersionStageStore { + + Optional<StageEntity<VersionEntity>> get(SessionContext context, Id itemId, + VersionEntity versionEntity); + + void create(SessionContext context, Id itemId, StageEntity<VersionEntity> versionStage); + + void delete(SessionContext context, Id itemId, VersionEntity version); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPrivateStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPrivateStoreImpl.java new file mode 100644 index 0000000000..9f54ee3ae2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPrivateStoreImpl.java @@ -0,0 +1,269 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.ZusammenPluginConstants; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPrivateStore; +import org.openecomp.core.zusammen.plugin.dao.ElementRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateElementContext; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateSpaceName; + +public class ElementPrivateStoreImpl implements ElementPrivateStore { + private static final Id REVISION_ID = Id.ZERO; // the private revision id is Id.ZERO 0000000... + + @Override + public Map<Id, Id> listIds(SessionContext context, ElementContext elementContext) { + return getElementRepository(context) + .listIds(context, new ElementEntityContext(getPrivateSpaceName(context), elementContext)); + } + + @Override + public Collection<ElementEntity> listSubs(SessionContext context, ElementContext elementContext, + Id elementId) { + if (elementId == null) { + elementId = ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; + } + + ElementRepository elementRepository = getElementRepository(context); + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + return elementRepository.get(context, privateContext, new ElementEntity(elementId)) + .map(ElementEntity::getSubElementIds).orElse(new HashSet<>()).stream() + .map(subElementId -> elementRepository + .get(context, privateContext, new ElementEntity(subElementId)).get()) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + @Override + public Optional<ElementEntity> get(SessionContext context, ElementContext elementContext, + Id elementId) { + ElementEntityContext privateElementContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateElementContext.setRevisionId(REVISION_ID); + return getElementRepository(context) + .get(context, privateElementContext, + new ElementEntity(elementId)); + } + + @Override + public Optional<ElementEntity> getDescriptor(SessionContext context, + ElementContext elementContext, Id elementId) { + return getElementRepository(context) + .getDescriptor(context, + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext + (elementContext)), + new ElementEntity(elementId)); + } + + @Override + public Collection<SynchronizationStateEntity> listSynchronizationStates(SessionContext context, + ElementContext elementContext) { + ElementEntityContext privateElementContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + return getElementSyncStateRepository(context) + .list(context, privateElementContext); + } + + @Override + public Optional<SynchronizationStateEntity> getSynchronizationState(SessionContext context, + ElementContext elementContext, + Id elementId) { + + ElementEntityContext privateElementContext = + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext + (elementContext)); + return getElementSyncStateRepository(context) + .get(context, privateElementContext, + new SynchronizationStateEntity(elementId, REVISION_ID)); + } + + @Override + public void create(SessionContext context, ElementContext elementContext, ElementEntity element) { + create(context, elementContext, element, true, null); + } + + @Override + public boolean update(SessionContext context, ElementContext elementContext, + ElementEntity element) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + + if (!isElementChanged(context, privateContext, element)) { + return false; + } + + getElementRepository(context).update(context, privateContext, element); + getElementSyncStateRepository(context).markAsDirty(context, privateContext, + new SynchronizationStateEntity(element.getId(), REVISION_ID)); + return true; + } + + @Override + public void delete(SessionContext context, ElementContext elementContext, ElementEntity element) { + + ElementEntityContext privateElementContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateElementContext.setRevisionId(REVISION_ID); + deleteElementHierarchy(context, getElementRepository(context), + getElementSyncStateRepository(context), + privateElementContext, element); + } + + @Override + public void markAsPublished(SessionContext context, ElementContext elementContext, Id elementId, + Date publishTime) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + getElementSyncStateRepository(context).update(context, + privateContext, + new SynchronizationStateEntity(elementId, REVISION_ID, publishTime, false)); + } + + @Override + public void markDeletionAsPublished(SessionContext context, ElementContext elementContext, + Id elementId, Date publishTime) { + + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + getElementSyncStateRepository(context).delete(context, + privateContext, + new SynchronizationStateEntity(elementId, REVISION_ID)); + } + + @Override + public void commitStagedCreate(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + create(context, elementContext, element, false, publishTime); + } + + @Override + public void commitStagedUpdate(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + + getElementRepository(context).update(context, privateContext, element); + // Currently Resolution='Other' is not supported so this is invoked after conflict was + // resolved with Resolution='Theirs' so dirty flag should be turned off. + // (if there was no conflict it's off anyway) + getElementSyncStateRepository(context).update(context, privateContext, + new SynchronizationStateEntity(element.getId(), REVISION_ID, publishTime, false)); + } + + @Override + public void commitStagedDelete(SessionContext context, ElementContext elementContext, + ElementEntity element) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + getElementRepository(context).delete(context, privateContext, element); + getElementSyncStateRepository(context) + .delete(context, privateContext, + new SynchronizationStateEntity(element.getId(), REVISION_ID)); + } + + @Override + public void commitStagedIgnore(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + // publish time - updated to mark that this element was already synced with this publish time + // (even though the local data was preferred) and to prevent this conflict again. + // dirty - turned on because the local data which is different than the public one was + // preferred. It will enable future publication of this data. + getElementSyncStateRepository(context).update(context, + new ElementEntityContext(getPrivateSpaceName(context), elementContext), + new SynchronizationStateEntity(element.getId(), REVISION_ID, publishTime, true)); + } + + private void create(SessionContext context, ElementContext elementContext, + ElementEntity element, boolean dirty, Date publishTime) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), elementContext); + privateContext.setRevisionId(REVISION_ID); + getElementRepository(context).create(context, privateContext, element); + getElementSyncStateRepository(context).create(context, privateContext, + new SynchronizationStateEntity(element.getId(), REVISION_ID, publishTime, dirty)); + } + + + private void deleteElementHierarchy( + SessionContext context, ElementRepository elementRepository, + ElementSynchronizationStateRepository elementSyncStateRepository, + ElementEntityContext elementContext, ElementEntity element) { + + Optional<ElementEntity> retrieved = elementRepository.get(context, elementContext, element); + if (!retrieved.isPresent()) { + return; + } + retrieved.get().getSubElementIds().stream() + .map(ElementEntity::new) + .forEach(subElementEntity -> deleteElementHierarchy( + context, elementRepository, elementSyncStateRepository, elementContext, + subElementEntity)); + + // only for the first one the parentId will populated (so it'll be removed from its parent) + elementRepository.delete(context, elementContext, element); + handleDeletedElementSyncState(context, elementSyncStateRepository, elementContext, element); + } + + private void handleDeletedElementSyncState(SessionContext context, + ElementSynchronizationStateRepository elementSyncStateRepository, + ElementEntityContext elementContext, + ElementEntity element) { + SynchronizationStateEntity elementSyncState = new SynchronizationStateEntity(element.getId(), + REVISION_ID); + if (elementSyncStateRepository.get(context, elementContext, elementSyncState). + orElseThrow( + () -> new IllegalStateException("Synchronization state must exist for an element")) + .getPublishTime() == null) { + elementSyncStateRepository.delete(context, elementContext, elementSyncState); + } else { + elementSyncStateRepository.markAsDirty(context, elementContext, elementSyncState); + } + } + + private boolean isElementChanged(SessionContext context, + ElementEntityContext elementContext, + ElementEntity newElement) { + return getElementHash(context, elementContext, new ElementEntity(newElement.getId())) + .map(existingHash -> !newElement.getElementHash().equals(existingHash)) + .orElse(true); + } + + private Optional<Id> getElementHash(SessionContext context, + ElementEntityContext elementEntityContext, + ElementEntity element) { + return getElementRepository(context).getHash(context, elementEntityContext, element); + } + + protected ElementRepository getElementRepository(SessionContext context) { + return ElementRepositoryFactory.getInstance().createInterface(context); + } + + protected ElementSynchronizationStateRepository getElementSyncStateRepository( + SessionContext context) { + return ElementSynchronizationStateRepositoryFactory.getInstance().createInterface(context); + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPublicStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPublicStoreImpl.java new file mode 100644 index 0000000000..d946a529ce --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementPublicStoreImpl.java @@ -0,0 +1,189 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.Space; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPublicStore; +import org.openecomp.core.zusammen.plugin.dao.ElementRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; + +public class ElementPublicStoreImpl implements ElementPublicStore { + + @Override + public Optional<ElementEntity> get(SessionContext context, + ElementContext elementContext, Id elementId) { + return getElementRepository(context) + .get(context, new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext), + new ElementEntity(elementId)); + } + + @Override + public Optional<ElementEntity> getDescriptor(SessionContext context, + ElementContext elementContext, Id elementId) { + return getElementRepository(context).getDescriptor(context, + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext), + new ElementEntity(elementId)); + } + + @Override + public Collection<SynchronizationStateEntity> listSynchronizationStates( + SessionContext context, ElementContext elementContext) { + ElementEntityContext entityContext = new ElementEntityContext(getSpaceName + (context, Space.PUBLIC), elementContext); + + ElementSynchronizationStateRepository elementSyncStateRepository = + getElementSyncStateRepository(context); + Map<Id, Id> ids = getElementRepository(context).listIds(context, entityContext); + + Collection<SynchronizationStateEntity> synchronizationStateEntities = new HashSet<>(); + for (Map.Entry<Id, Id> elementEntry : ids.entrySet()) { + Optional<SynchronizationStateEntity> synchronizationStateEntity = elementSyncStateRepository. + get(context, entityContext, new SynchronizationStateEntity(elementEntry.getKey(), + elementEntry.getValue())); + if (synchronizationStateEntity.isPresent()) { + synchronizationStateEntities.add(synchronizationStateEntity.get()); + } else { + /*throw new IllegalStateException(String.format( + "list Synchronization States error: " + "element %s revision %s, which appears as an " + + "element of " + + "item" + + " %s version %s, does not exist", + elementEntry.getKey(), elementEntry.getValue(), elementContext.getItemId().getValue(), + elementContext.getVersionId().getValue()));*/ + } + } + + return synchronizationStateEntities; + } + + @Override + public void create(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + ElementEntityContext publicContext = + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext); + + + if (element.getParentId() != null) { + createParentElement(context, elementContext, element.getParentId(), publishTime); + } + getElementRepository(context).create(context, publicContext, element); + getElementSyncStateRepository(context).create(context, publicContext, + new SynchronizationStateEntity(element.getId(), elementContext.getRevisionId(), + publishTime, false)); + } + + @Override + public void update(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + //todo - update in public should be create new entry with new revision_id in public - this is a + // new revision + ElementEntityContext publicContext = + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext); + + Optional<ElementEntity> publicElement = getElementRepository(context).get(context, + publicContext, new ElementEntity(element.getId())); + if (publicElement.isPresent()) { + getElementRepository(context).update(context, publicContext, element); + } else { + publicElement = get(context,new ElementContext(publicContext.getItemId(),publicContext + .getVersionId()),element.getId()); + element.setSubElementIds(publicElement.get().getSubElementIds()); + getElementRepository(context).create(context, publicContext, element); + } + getElementSyncStateRepository(context).update(context, publicContext, + new SynchronizationStateEntity(element.getId(), elementContext.getRevisionId(), publishTime, + false)); + } + + @Override + public void delete(SessionContext context, ElementContext elementContext, + ElementEntity element, Date publishTime) { + ElementEntityContext publicContext = + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext); + + if (element.getParentId() != null) { + Optional<ElementEntity> parentElement = get(context, elementContext, element.getParentId()); + if (parentElement.isPresent()) { + createParentElement(context, elementContext, element.getParentId(), publishTime); + } + } + + getElementRepository(context).delete(context, publicContext, element); + getElementSyncStateRepository(context) + .delete(context, publicContext, new SynchronizationStateEntity(element.getId(), + elementContext.getRevisionId())); + } + + @Override + public Map<Id, Id> listIds(SessionContext context, ElementContext elementContext) { + + return getElementRepository(context) + .listIds(context, + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext)); + + } + + private void createParentElement(SessionContext context, ElementContext elementContext, + Id parentElementId, Date publishTime + ) { + ElementEntityContext publicContext = + new ElementEntityContext(getSpaceName(context, Space.PUBLIC), elementContext); + + Optional<ElementEntity> parentElement = + getElementRepository(context).get(context, new ElementEntityContext + (publicContext.getSpace(), publicContext.getItemId(), publicContext.getVersionId(), + elementContext.getRevisionId()), + new ElementEntity(parentElementId)); + if(parentElement.isPresent()) { + update(context, elementContext, parentElement.get(), publishTime); + } + + + /* Id elementRevisionId = getElementRevision(context, publicContext, elementContext.getRevisionId() + , parentElementId); + + if (elementRevisionId != null && !elementRevisionId.equals(elementContext.getRevisionId())) { + Optional<ElementEntity> parentElement = + getElementRepository(context).get(context, new ElementEntityContext + (publicContext.getSpace(), publicContext.getItemId(), publicContext.getVersionId(), + elementContext.getRevisionId()), + new ElementEntity(parentElementId)); + elementRevisionId = getElementRevision(context, publicContext, elementContext.getRevisionId() + , parentElement.get().getId()); + if (elementRevisionId != null) { + update(context, elementContext, parentElement.get(), publishTime); + } else { + create(context, elementContext, parentElement.get(), publishTime); + } + + }*/ + } + + + + + protected ElementRepository getElementRepository(SessionContext context) { + return ElementRepositoryFactory.getInstance().createInterface(context); + } + + protected ElementSynchronizationStateRepository getElementSyncStateRepository( + SessionContext context) { + return ElementSynchronizationStateRepositoryFactory.getInstance().createInterface(context); + } + + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImpl.java new file mode 100644 index 0000000000..f6c29432df --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImpl.java @@ -0,0 +1,133 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Resolution; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.collaboration.ElementStageStore; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.util.Collection; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateElementContext; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateSpaceName; + +public class ElementStageStoreImpl implements ElementStageStore { + + @Override + public Collection<ElementEntity> listIds(SessionContext context, ElementContext elementContext) { + return getElementStageRepository(context) + .listIds(context, new ElementEntityContext(getPrivateSpaceName(context), + getPrivateElementContext(elementContext))); + } + + @Override + public Optional<StageEntity<ElementEntity>> get(SessionContext context, + ElementContext elementContext, + ElementEntity element) { + return getElementStageRepository(context).get(context, + new ElementEntityContext(getPrivateSpaceName(context), + getPrivateElementContext(elementContext)), + element); + } + + @Override + public Optional<StageEntity<ElementEntity>> getConflicted(SessionContext context, + ElementContext elementContext, + ElementEntity element) { + return get(context, elementContext, element).filter(StageEntity::isConflicted); + } + + @Override + public boolean hasConflicts(SessionContext context, ElementContext elementContext) { + return !getElementStageRepository(context).listConflictedIds(context, + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext(elementContext))).isEmpty(); + } + + @Override + public Collection<StageEntity<ElementEntity>> listConflictedDescriptors(SessionContext context, + ElementContext elementContext) { + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext + (elementContext)); + ElementStageRepository elementStageRepository = getElementStageRepository(context); + + return elementStageRepository.listConflictedIds(context, privateContext).stream() + .map(conflictedElement -> elementStageRepository + .getDescriptor(context, privateContext, conflictedElement).get()) + .collect(Collectors.toList()); + } + + @Override + public void create(SessionContext context, ElementContext elementContext, + StageEntity<ElementEntity> elementStage) { + getElementStageRepository(context) + .create(context, + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext(elementContext)), + elementStage); + } + + @Override + public void delete(SessionContext context, ElementContext elementContext, ElementEntity element) { + getElementStageRepository(context) + .delete(context, + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext(elementContext)), + element); + } + + + @Override + public void resolveConflict(SessionContext context, ElementContext elementContext, + ElementEntity element, Resolution resolution) { + Optional<StageEntity<ElementEntity>> stagedElement = + getConflicted(context, elementContext, element); + if (!stagedElement.isPresent()) { + return; + } + + ElementEntityContext privateContext = + new ElementEntityContext(getPrivateSpaceName(context), getPrivateElementContext + (elementContext)); + + switch (resolution) { + case YOURS: + resolveConflictByYours(context, privateContext, stagedElement.get()); + break; + case THEIRS: + resolveConflictByTheirs(context, privateContext, stagedElement.get()); + break; + case OTHER: // other = data updates only? no data deletions? if so, then: + // conflicted = false + // element = the input of resolve + // action = update + throw new UnsupportedOperationException("'Other' conflict resolution is not yet supported"); + default: + break; + } + } + + private void resolveConflictByYours(SessionContext context, ElementEntityContext privateContext, + StageEntity<ElementEntity> stagedElement) { + getElementStageRepository(context) + .markAsNotConflicted(context, privateContext, stagedElement.getEntity(), Action.IGNORE); + stagedElement.getConflictDependents().forEach(conflictDependant -> + getElementStageRepository(context) + .markAsNotConflicted(context, privateContext, conflictDependant, Action.IGNORE)); + } + + private void resolveConflictByTheirs(SessionContext context, ElementEntityContext privateContext, + StageEntity<ElementEntity> stagedElement) { + getElementStageRepository(context) + .markAsNotConflicted(context, privateContext, stagedElement.getEntity()); + } + + protected ElementStageRepository getElementStageRepository(SessionContext context) { + return ElementStageRepositoryFactory.getInstance().createInterface(context); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPrivateStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPrivateStoreImpl.java new file mode 100644 index 0000000000..11e61ab5a9 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPrivateStoreImpl.java @@ -0,0 +1,117 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.collaboration.VersionPrivateStore; +import org.openecomp.core.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Date; +import java.util.Optional; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateSpaceName; + +public class VersionPrivateStoreImpl implements VersionPrivateStore { + + Id revisionId = Id.ZERO; + + @Override + public Optional<VersionEntity> get(SessionContext context, Id itemId, Id versionId) { + return getVersionDao(context).get(context, getPrivateSpaceName(context), itemId, versionId); + } + + @Override + public Optional<SynchronizationStateEntity> getSynchronizationState(SessionContext context, + Id itemId, Id versionId) { + + return getVersionSyncStateRepository(context) + .get(context, new VersionContext(getPrivateSpaceName(context), itemId), + new SynchronizationStateEntity(versionId, revisionId)); + } + + @Override + public void create(SessionContext context, Id itemId, VersionEntity version) { + String privateSpace = getPrivateSpaceName(context); + + + getVersionDao(context).create(context, privateSpace, itemId, version); + getVersionSyncStateRepository(context).create(context, new VersionContext(privateSpace, + itemId), + new SynchronizationStateEntity(version.getId(), revisionId, null, true)); + } + + @Override + public void update(SessionContext context, Id itemId, VersionEntity version) { + + getVersionDao(context) + .updateModificationTime(context, getPrivateSpaceName(context), itemId, version.getId(), + version.getModificationTime()); + } + + @Override + public void update(SessionContext context, Id itemId, VersionEntity version, Date publishTime, + boolean dirty) { + getVersionSyncStateRepository(context).updatePublishTime(context, + new VersionContext(getPrivateSpaceName(context), itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, dirty)); + } + + @Override + public void delete(SessionContext context, Id itemId, VersionEntity version) { + String privateSpace = getPrivateSpaceName(context); + + getVersionDao(context).delete(context, privateSpace, itemId, version.getId()); + getVersionSyncStateRepository(context).delete(context, new VersionContext(privateSpace, + itemId), + new SynchronizationStateEntity(version.getId(), revisionId)); + } + + @Override + public void markAsPublished(SessionContext context, Id itemId, Id versionId, Date publishTime) { + getVersionSyncStateRepository(context) + .updatePublishTime(context, new VersionContext(getPrivateSpaceName(context), itemId), + new SynchronizationStateEntity(versionId, revisionId, publishTime, false)); + } + + @Override + public void commitStagedCreate(SessionContext context, Id itemId, VersionEntity version, + Date publishTime) { + String privateSpace = getPrivateSpaceName(context); + + getVersionDao(context).create(context, privateSpace, itemId, version); + getVersionSyncStateRepository(context).create(context, new VersionContext(privateSpace, + itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, false)); + } + + @Override + public void commitStagedUpdate(SessionContext context, Id itemId, VersionEntity version, + Date publishTime) { + update(context, itemId, version, publishTime, false); + } + + @Override + public void commitStagedIgnore(SessionContext context, Id itemId, VersionEntity version, + Date publishTime) { + getVersionSyncStateRepository(context).updatePublishTime(context, + new VersionContext(getPrivateSpaceName(context), itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, false)); + } + + + + + protected VersionDao getVersionDao(SessionContext context) { + return VersionDaoFactory.getInstance().createInterface(context); + } + + protected VersionSynchronizationStateRepository getVersionSyncStateRepository( + SessionContext context) { + return VersionSynchronizationStateRepositoryFactory.getInstance().createInterface(context); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPublicStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPublicStoreImpl.java new file mode 100644 index 0000000000..aa628eb706 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionPublicStoreImpl.java @@ -0,0 +1,135 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.Space; +import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; +import com.amdocs.zusammen.datatypes.itemversion.Revision; +import org.openecomp.core.zusammen.plugin.collaboration.VersionPublicStore; +import org.openecomp.core.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; + +public class VersionPublicStoreImpl implements VersionPublicStore { + @Override + public Optional<VersionEntity> get(SessionContext context, Id itemId, Id versionId) { + return getVersionDao(context) + .get(context, getSpaceName(context, Space.PUBLIC), itemId, versionId); + } + + @Override + public Optional<SynchronizationStateEntity> getSynchronizationState(SessionContext context, + Id itemId, Id versionId) { + Id revisionId = getLastItemVersionRevision(context, itemId, + versionId); + if (revisionId == null) { + return Optional.empty(); + } + + return getVersionSyncStateRepository(context) + .get(context, new VersionContext(getSpaceName(context, Space.PUBLIC), itemId), + new SynchronizationStateEntity(versionId, revisionId)); + } + + + @Override + public void create(SessionContext context, Id itemId, VersionEntity version, Id revisionId, + Map<Id, Id> versionElementIds, Date + publishTime, String message) { + String publicSpace = getSpaceName(context, Space.PUBLIC); + + getVersionDao(context).create(context, publicSpace, itemId, version); + + getVersionDao(context).createVersionElements(context, publicSpace, itemId, version.getId(), + revisionId, versionElementIds, publishTime,message); + + getVersionSyncStateRepository(context).create(context, new VersionContext(publicSpace, + itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, false)); + } + + @Override + public void update(SessionContext context, Id itemId, VersionEntity version, + Id revisionId, Map<Id, Id> versionElementIds, Date publishTime, String message) { + String publicSpace = getSpaceName(context, Space.PUBLIC); + + getVersionDao(context). + createVersionElements(context, publicSpace, itemId, version.getId(), + revisionId, versionElementIds, publishTime,message); + + getVersionSyncStateRepository(context). + updatePublishTime(context, new VersionContext(publicSpace, itemId), + new SynchronizationStateEntity(version.getId(), revisionId, publishTime, false)); + } + + @Override + public boolean checkHealth(SessionContext context) { + return getVersionDao(context).checkHealth(context); + } + + @Override + public ItemVersionRevisions listItemVersionRevisions(SessionContext context, Id itemId, + Id versionId) { + VersionContext entityContext = new VersionContext(getSpaceName(context, Space.PUBLIC), itemId); + List<SynchronizationStateEntity> versionRevisions = getVersionSyncStateRepository(context) + .list(context, entityContext, new VersionEntity(versionId)); + + if (versionRevisions == null || versionRevisions.size() == 0) { + return null; + } + + versionRevisions.sort(new Comparator<SynchronizationStateEntity>() { + @Override + public int compare(SynchronizationStateEntity o1, SynchronizationStateEntity o2) { + if (o1.getPublishTime().after(o2.getPublishTime())) { + return -1; + } else { + return 1; + } + } + }); + ItemVersionRevisions itemVersionRevisions = new ItemVersionRevisions(); + versionRevisions.forEach(synchronizationStateEntity -> itemVersionRevisions.addChange + (convertSyncState2Revision(synchronizationStateEntity))); + return itemVersionRevisions; + } + + private Revision convertSyncState2Revision( + SynchronizationStateEntity synchronizationStateEntity) { + Revision revision = new Revision(); + revision.setRevisionId(synchronizationStateEntity.getRevisionId()); + revision.setTime(synchronizationStateEntity.getPublishTime()); + revision.setMessage(synchronizationStateEntity.getMessage()); + revision.setUser(synchronizationStateEntity.getUser()); + return revision; + } + + + private Id getLastItemVersionRevision(SessionContext context, Id itemId, Id versionId) { + + ItemVersionRevisions versionRevisions = listItemVersionRevisions(context, itemId, versionId); + if(versionRevisions ==null ) return null; + return versionRevisions.getItemVersionRevisions().get(0).getRevisionId(); + } + + protected VersionDao getVersionDao(SessionContext context) { + return VersionDaoFactory.getInstance().createInterface(context); + } + + protected VersionSynchronizationStateRepository getVersionSyncStateRepository( + SessionContext context) { + return VersionSynchronizationStateRepositoryFactory.getInstance().createInterface(context); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionStageStoreImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionStageStoreImpl.java new file mode 100644 index 0000000000..dac9d257ea --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/collaboration/impl/VersionStageStoreImpl.java @@ -0,0 +1,39 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.collaboration.VersionStageStore; +import org.openecomp.core.zusammen.plugin.dao.VersionStageRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionStageRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Optional; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getPrivateSpaceName; + +public class VersionStageStoreImpl implements VersionStageStore { + @Override + public Optional<StageEntity<VersionEntity>> get(SessionContext context, Id itemId, + VersionEntity versionEntity) { + return getVersionStageRepository(context) + .get(context, new VersionContext(getPrivateSpaceName(context), itemId), versionEntity); + } + + @Override + public void create(SessionContext context, Id itemId, StageEntity<VersionEntity> versionStage) { + getVersionStageRepository(context) + .create(context, new VersionContext(getPrivateSpaceName(context), itemId), versionStage); + } + + @Override + public void delete(SessionContext context, Id itemId, VersionEntity version) { + getVersionStageRepository(context) + .delete(context, new VersionContext(getPrivateSpaceName(context), itemId), version); + } + + protected VersionStageRepository getVersionStageRepository(SessionContext context) { + return VersionStageRepositoryFactory.getInstance().createInterface(context); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementRepository.java index 967814c4d8..7681327e40 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementRepository.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementRepository.java @@ -1,15 +1,18 @@ package org.openecomp.core.zusammen.plugin.dao; +import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; -import java.util.Collection; +import java.util.Map; import java.util.Optional; public interface ElementRepository { - Collection<ElementEntity> list(SessionContext context, ElementEntityContext elementContext); + Map<Id,Id> listIds(SessionContext context, ElementEntityContext elementContext); + +/* void createVersionData(SessionContext context, ElementEntityContext elementContext, VersionDataElement element);*/ void create(SessionContext context, ElementEntityContext elementContext, ElementEntity element); @@ -20,8 +23,28 @@ public interface ElementRepository { Optional<ElementEntity> get(SessionContext context, ElementEntityContext elementContext, ElementEntity element); + Optional<ElementEntity> getDescriptor(SessionContext context, ElementEntityContext elementContext, + ElementEntity element); + void createNamespace(SessionContext context, ElementEntityContext elementContext, ElementEntity element); - boolean checkHealth(SessionContext context); + Optional<Id> getHash(SessionContext context, ElementEntityContext elementEntityContext, + ElementEntity element); + + + + +/* Collection<SynchronizationStateEntity> listSynchronizationStates(SessionContext context, + ElementEntityContext elementContext); + + void updateSynchronizationState(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState); + + void markAsDirty(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState); + + Optional<SynchronizationStateEntity> getSynchronizationState(SessionContext context, + ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState);*/ } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepository.java new file mode 100644 index 0000000000..ac3dc4e4bf --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepository.java @@ -0,0 +1,34 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.util.Collection; +import java.util.Optional; + +public interface ElementStageRepository + extends StageRepository<ElementEntityContext, ElementEntity> { + + Optional<StageEntity<ElementEntity>> getDescriptor(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element); + + Collection<ElementEntity> listIds(SessionContext context, + ElementEntityContext elementContext); + + Collection<ElementEntity> listConflictedIds(SessionContext context, + ElementEntityContext elementContext); + + void markAsNotConflicted(SessionContext context, ElementEntityContext entityContext, + ElementEntity entity, Action action); + + void markAsNotConflicted(SessionContext context, ElementEntityContext entityContext, + ElementEntity entity); + + void update(SessionContext context, ElementEntityContext entityContext, ElementEntity entity, + Action action, boolean conflicted); + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepositoryFactory.java new file mode 100644 index 0000000000..1e41308ff2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementStageRepositoryFactory.java @@ -0,0 +1,14 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class ElementStageRepositoryFactory + extends AbstractComponentFactory<ElementStageRepository> { + public static ElementStageRepositoryFactory getInstance() { + return AbstractFactory.getInstance(ElementStageRepositoryFactory.class); + } + + public abstract ElementStageRepository createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepository.java new file mode 100644 index 0000000000..53c029bb6f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepository.java @@ -0,0 +1,21 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; + +public interface ElementSynchronizationStateRepository + extends SynchronizationStateRepository<ElementEntityContext> { + + Collection<SynchronizationStateEntity> list(SessionContext context, + ElementEntityContext elementContext); + + void update(SessionContext context, ElementEntityContext entityContext, + SynchronizationStateEntity syncStateEntity); + + void markAsDirty(SessionContext context, ElementEntityContext entityContext, + SynchronizationStateEntity syncStateEntity); + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepositoryFactory.java new file mode 100644 index 0000000000..26f3bb4f56 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/ElementSynchronizationStateRepositoryFactory.java @@ -0,0 +1,14 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class ElementSynchronizationStateRepositoryFactory + extends AbstractComponentFactory<ElementSynchronizationStateRepository> { + public static ElementSynchronizationStateRepositoryFactory getInstance() { + return AbstractFactory.getInstance(ElementSynchronizationStateRepositoryFactory.class); + } + + public abstract ElementSynchronizationStateRepository createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/StageRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/StageRepository.java new file mode 100644 index 0000000000..98b0d8242c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/StageRepository.java @@ -0,0 +1,15 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.util.Optional; + +public interface StageRepository<C, E> { + + Optional<StageEntity<E>> get(SessionContext context, C entityContext, E entity); + + void create(SessionContext context, C entityContext, StageEntity<E> stageEntity); + + void delete(SessionContext context, C entityContext, E entity); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/SynchronizationStateRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/SynchronizationStateRepository.java new file mode 100644 index 0000000000..f227b0c925 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/SynchronizationStateRepository.java @@ -0,0 +1,16 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Optional; + +public interface SynchronizationStateRepository<C> { + + void create(SessionContext context, C entityContext, SynchronizationStateEntity syncStateEntity); + + void delete(SessionContext context, C entityContext, SynchronizationStateEntity syncStateEntity); + + Optional<SynchronizationStateEntity> get(SessionContext context, C entityContext, + SynchronizationStateEntity syncStateEntity); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDao.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDao.java new file mode 100644 index 0000000000..f8ad0405b2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDao.java @@ -0,0 +1,29 @@ +package org.openecomp.core.zusammen.plugin.dao; + + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Collection; +import java.util.Date; +import java.util.Map; +import java.util.Optional; + +public interface VersionDao { + Collection<VersionEntity> list(SessionContext context, String space, Id itemId); + + Optional<VersionEntity> get(SessionContext context, String space, Id itemId, Id versionId); + + void create(SessionContext context, String space, Id itemId, VersionEntity version); + + void updateModificationTime(SessionContext context, String space, Id itemId, Id versionId, Date modificationTime); + + void delete(SessionContext context, String space, Id itemId, Id versionId); + + boolean checkHealth(SessionContext context); + + void createVersionElements(SessionContext context, String publicSpace, Id itemId, Id versionId, + Id revisionId, Map<Id, Id> versionElementIds, Date publishTime, + String message); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDaoFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDaoFactory.java new file mode 100644 index 0000000000..2847959f8f --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionDaoFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class VersionDaoFactory extends AbstractComponentFactory<VersionDao> { + public static VersionDaoFactory getInstance() { + return AbstractFactory.getInstance(VersionDaoFactory.class); + } + + public abstract VersionDao createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepository.java new file mode 100644 index 0000000000..568e0c9d2b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepository.java @@ -0,0 +1,9 @@ +package org.openecomp.core.zusammen.plugin.dao; + + +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +public interface VersionStageRepository extends StageRepository<VersionContext, VersionEntity> { + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepositoryFactory.java new file mode 100644 index 0000000000..fc9e7725eb --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionStageRepositoryFactory.java @@ -0,0 +1,13 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class VersionStageRepositoryFactory extends AbstractComponentFactory<VersionStageRepository> { + public static VersionStageRepositoryFactory getInstance() { + return AbstractFactory.getInstance(VersionStageRepositoryFactory.class); + } + + public abstract VersionStageRepository createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepository.java new file mode 100644 index 0000000000..9134392d3b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepository.java @@ -0,0 +1,18 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.List; + +public interface VersionSynchronizationStateRepository + extends SynchronizationStateRepository<VersionContext> { + + void updatePublishTime(SessionContext context, VersionContext entityContext, + SynchronizationStateEntity syncStateEntity); + + List<SynchronizationStateEntity> list(SessionContext context, VersionContext entityContext, + VersionEntity versionEntity); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepositoryFactory.java new file mode 100644 index 0000000000..dfedb5897b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/VersionSynchronizationStateRepositoryFactory.java @@ -0,0 +1,14 @@ +package org.openecomp.core.zusammen.plugin.dao; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.utils.facade.api.AbstractComponentFactory; +import com.amdocs.zusammen.utils.facade.api.AbstractFactory; + +public abstract class VersionSynchronizationStateRepositoryFactory + extends AbstractComponentFactory<VersionSynchronizationStateRepository> { + public static VersionSynchronizationStateRepositoryFactory getInstance() { + return AbstractFactory.getInstance(VersionSynchronizationStateRepositoryFactory.class); + } + + public abstract VersionSynchronizationStateRepository createInterface(SessionContext context); +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java deleted file mode 100644 index 6cc1350444..0000000000 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepository.java +++ /dev/null @@ -1,375 +0,0 @@ -/* - * Copyright © 2016-2017 European Support Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.openecomp.core.zusammen.plugin.dao.impl; - -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.Namespace; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.Relation; -import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; -import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.mapping.annotations.Accessor; -import com.datastax.driver.mapping.annotations.Param; -import com.datastax.driver.mapping.annotations.Query; -import com.google.gson.reflect.TypeToken; -import org.openecomp.core.zusammen.plugin.dao.ElementRepository; -import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; - -import java.lang.reflect.Type; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -public class CassandraElementRepository implements ElementRepository { - - private static final String VERSION_ELEMENT_NOT_EXIST_ERROR_MSG = - "List version elements error: " + - "element %s, which appears as an element of item %s version %s, does not exist"; - - @Override - public Collection<ElementEntity> list(SessionContext context, - ElementEntityContext elementContext) { - Set<String> elementIds = getVersionElementIds(context, elementContext); - - Collection<ElementEntity> elements = new ArrayList<>(); - for (String elementId : elementIds) { - elements.add(get(context, elementContext, new ElementEntity(new Id(elementId))) - .orElseThrow( - () -> new IllegalStateException(String.format(VERSION_ELEMENT_NOT_EXIST_ERROR_MSG, - elementId, elementContext.getItemId().getValue(), - getVersionId(elementContext))))); - } - return elements; - } - - @Override - public void create(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - createElement(context, elementContext, element); - addElementToParent(context, elementContext, element); - } - - @Override - public void update(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - updateElement(context, elementContext, element); - } - - @Override - public void delete(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - removeElementFromParent(context, elementContext, element); - deleteElement(context, elementContext, element); - } - - @Override - public Optional<ElementEntity> get(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - Row row = getElementAccessor(context).get( - elementContext.getSpace(), - elementContext.getItemId().toString(), - getVersionId(elementContext), - element.getId().toString()).one(); - - return row == null ? Optional.empty() : Optional.of(getElementEntity(element, row)); - } - - @Override - public void createNamespace(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - getElementNamespaceAccessor(context).create( - elementContext.getSpace(), - elementContext.getItemId().toString(), - element.getId().toString(), - element.getNamespace().toString()); - } - - @Override - public boolean checkHealth(SessionContext context) { - ResultSet resultSet = getVersionElementsAccessor(context).checkHealth(); - return resultSet.getColumnDefinitions().contains("element_ids"); - } - - private String getVersionId(ElementEntityContext elementContext) { - return elementContext.getChangeRef() == null - ? elementContext.getVersionId().toString() - : elementContext.getChangeRef(); - } - - private ElementNamespaceAccessor getElementNamespaceAccessor(SessionContext context) { - return CassandraDaoUtils.getAccessor(context, ElementNamespaceAccessor.class); - } - - private ElementAccessor getElementAccessor(SessionContext context) { - return CassandraDaoUtils.getAccessor(context, ElementAccessor.class); - } - - private VersionElementsAccessor getVersionElementsAccessor(SessionContext context) { - return CassandraDaoUtils.getAccessor(context, VersionElementsAccessor.class); - } - - private void createElement(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - Set<String> subElementIds = - element.getSubElementIds().stream().map(Id::toString).collect(Collectors.toSet()); - String versionId = getVersionId(elementContext); - - getElementAccessor(context).create( - elementContext.getSpace(), - elementContext.getItemId().toString(), - versionId, - element.getId().toString(), - element.getParentId().toString(), - element.getNamespace().toString(), - JsonUtil.object2Json(element.getInfo()), - JsonUtil.object2Json(element.getRelations()), - element.getData(), - element.getSearchableData(), - element.getVisualization(), - subElementIds); - - getVersionElementsAccessor(context).addElements( - Collections.singleton(element.getId().toString()), - elementContext.getSpace(), - elementContext.getItemId().toString(), - versionId); - } - - private void updateElement(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - getElementAccessor(context).update( - JsonUtil.object2Json(element.getInfo()), - JsonUtil.object2Json(element.getRelations()), - element.getData(), - element.getSearchableData(), - element.getVisualization(), - elementContext.getSpace(), - elementContext.getItemId().toString(), - elementContext.getVersionId().toString(), - element.getId().toString()); - } - - private void deleteElement(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - String versionId = getVersionId(elementContext); - - getElementAccessor(context).delete( - elementContext.getSpace(), - elementContext.getItemId().toString(), - versionId, - element.getId().toString()); - - getVersionElementsAccessor(context).removeElements( - Collections.singleton(element.getId().toString()), - elementContext.getSpace(), - elementContext.getItemId().toString(), - versionId); - } - - private void addElementToParent(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - getElementAccessor(context).addSubElements( - Collections.singleton(element.getId().toString()), - elementContext.getSpace(), - elementContext.getItemId().toString(), - getVersionId(elementContext), - element.getParentId().toString()); - } - - private void removeElementFromParent(SessionContext context, ElementEntityContext elementContext, - ElementEntity element) { - if (element.getParentId() == null) { - return; - } - getElementAccessor(context).removeSubElements( - Collections.singleton(element.getId().toString()), - elementContext.getSpace(), - elementContext.getItemId().toString(), - getVersionId(elementContext), - element.getParentId().toString()); - } - - private ElementEntity getElementEntity(ElementEntity element, Row row) { - element.setNamespace(getNamespace(row.getString(ElementField.NAMESPACE))); - element.setParentId(new Id(row.getString(ElementField.PARENT_ID))); - element.setInfo(json2Object(row.getString(ElementField.INFO), Info.class)); - element.setRelations( - json2Object(row.getString(ElementField.RELATIONS), new TypeToken<ArrayList<Relation>>() { - }.getType())); - element.setData(row.getBytes(ElementField.DATA)); - element.setSearchableData(row.getBytes(ElementField.SEARCHABLE_DATA)); - element.setVisualization(row.getBytes(ElementField.VISUALIZATION)); - element.setSubElementIds(row.getSet(ElementField.SUB_ELEMENT_IDS, String.class) - .stream().map(Id::new).collect(Collectors.toSet())); - return element; - } - - private Namespace getNamespace(String namespaceStr) { - Namespace namespace = new Namespace(); - if (namespaceStr != null) { - namespace.setValue(namespaceStr); - } - return namespace; - } - - private static <T> T json2Object(String json, Type typeOfT) { - return json == null ? null : JsonUtil.json2Object(json, typeOfT); - } - - private Set<String> getVersionElementIds(SessionContext context, - ElementEntityContext elementContext) { - Row row = getVersionElementsAccessor(context).get( - elementContext.getSpace(), - elementContext.getItemId().toString(), - getVersionId(elementContext)).one(); - return row == null - ? new HashSet<>() - : row.getSet(CassandraElementRepository.VersionElementsField.ELEMENT_IDS, String.class); - } - - /* -CREATE TABLE IF NOT EXISTS element_namespace ( - space text, - item_id text, - element_id text, - namespace text, - PRIMARY KEY (( space, item_id, element_id )) -); - */ - @Accessor - interface ElementNamespaceAccessor { - @Query( - "UPDATE element_namespace SET namespace=:ns " + - "WHERE space=:space AND item_id=:item AND element_id=:id ") - void create(@Param("space") String space, - @Param("item") String itemId, - @Param("id") String elementId, - @Param("ns") String namespace); - } - - /* -CREATE TABLE IF NOT EXISTS element ( - space text, - item_id text, - version_id text, - element_id text, - parent_id text, - namespace text, - info text, - relations text, - data blob, - searchable_data blob, - visualization blob, - sub_element_ids set<text>, - PRIMARY KEY (( space, item_id, version_id, element_id )) -); - */ - @Accessor - interface ElementAccessor { - @Query( - "UPDATE element SET parent_id=:parentId, namespace=:ns, info=:info, relations=:rels, " + - "data=:data, searchable_data=:searchableData, visualization=:visualization, " + - "sub_element_ids=sub_element_ids+:subs " + - "WHERE space=:space AND item_id=:item AND version_id=:ver AND element_id=:id ") - void create(@Param("space") String space, - @Param("item") String itemId, - @Param("ver") String versionId, - @Param("id") String elementId, - @Param("parentId") String parentElementId, - @Param("ns") String namespace, - @Param("info") String info, - @Param("rels") String relations, - @Param("data") ByteBuffer data, - @Param("searchableData") ByteBuffer searchableData, - @Param("visualization") ByteBuffer visualization, - @Param("subs") Set<String> subElementIds); - - @Query("UPDATE element SET info=?, relations=?, data=?, searchable_data=?, visualization=?" + - " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") - void update(String info, String relations, ByteBuffer data, ByteBuffer searchableData, - ByteBuffer visualization, String space, String itemId, String versionId, - String elementId); - - @Query("DELETE FROM element WHERE space=? AND item_id=? AND version_id=? AND element_id=?") - void delete(String space, String itemId, String versionId, String elementId); - - @Query("SELECT parent_id, namespace, info, relations, data, searchable_data, visualization, " + - "sub_element_ids FROM element " + - "WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") - ResultSet get(String space, String itemId, String versionId, String elementId); - - @Query("UPDATE element SET sub_element_ids=sub_element_ids+? " + - " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") - void addSubElements(Set<String> subElementIds, String space, String itemId, String versionId, - String elementId); - - @Query("UPDATE element SET sub_element_ids=sub_element_ids-? " + - " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") - void removeSubElements(Set<String> subElementIds, String space, String itemId, String versionId, - String elementId); - } - - private static final class ElementField { - private static final String NAMESPACE = "namespace"; - private static final String PARENT_ID = "parent_id"; - private static final String INFO = "info"; - private static final String RELATIONS = "relations"; - private static final String DATA = "data"; - private static final String SEARCHABLE_DATA = "searchable_data"; - private static final String VISUALIZATION = "visualization"; - private static final String SUB_ELEMENT_IDS = "sub_element_ids"; - } - - /* - CREATE TABLE IF NOT EXISTS version_elements ( - space text, - item_id text, - version_id text, - element_ids set<text>, - PRIMARY KEY (( space, item_id, version_id )) - ); - */ - @Accessor - interface VersionElementsAccessor { - - @Query("UPDATE version_elements SET element_ids=element_ids+? " + - "WHERE space=? AND item_id=? AND version_id=?") - void addElements(Set<String> elementIds, String space, String itemId, String versionId); - - @Query("UPDATE version_elements SET element_ids=element_ids-? " + - "WHERE space=? AND item_id=? AND version_id=?") - void removeElements(Set<String> elementIds, String space, String itemId, String versionId); - - @Query("SELECT element_ids FROM version_elements WHERE space=? AND item_id=? AND version_id=?") - ResultSet get(String space, String itemId, String versionId); - - @Query("SELECT element_ids FROM version_elements LIMIT 1") - ResultSet checkHealth(); - } - - private static final class VersionElementsField { - private static final String ELEMENT_IDS = "element_ids"; - } -} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraDaoUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/CassandraDaoUtils.java index 20a1e1803f..b6cb9e4070 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraDaoUtils.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/CassandraDaoUtils.java @@ -1,9 +1,9 @@ -package org.openecomp.core.zusammen.plugin.dao.impl; +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; -import com.datastax.driver.core.Session; import com.amdocs.zusammen.commons.db.api.cassandra.CassandraConnectorFactory; import com.amdocs.zusammen.commons.db.api.cassandra.types.CassandraContext; import com.amdocs.zusammen.datatypes.SessionContext; +import com.datastax.driver.core.Session; class CassandraDaoUtils { diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepositoryFactory.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryFactoryImpl.java index f3072a6502..8540816f00 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/CassandraElementRepositoryFactory.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryFactoryImpl.java @@ -14,15 +14,15 @@ * limitations under the License. */ -package org.openecomp.core.zusammen.plugin.dao.impl; +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; import com.amdocs.zusammen.datatypes.SessionContext; import org.openecomp.core.zusammen.plugin.dao.ElementRepository; import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; -public class CassandraElementRepositoryFactory extends ElementRepositoryFactory { +public class ElementRepositoryFactoryImpl extends ElementRepositoryFactory { - private static final ElementRepository INSTANCE = new CassandraElementRepository(); + private static final ElementRepository INSTANCE = new ElementRepositoryImpl(); @Override public ElementRepository createInterface(SessionContext context) { diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryImpl.java new file mode 100644 index 0000000000..bb3b1cfa7c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementRepositoryImpl.java @@ -0,0 +1,565 @@ +/* + * Copyright © 2016-2017 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.Namespace; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Relation; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Param; +import com.datastax.driver.mapping.annotations.Query; +import com.google.gson.reflect.TypeToken; +import org.openecomp.core.zusammen.plugin.ZusammenPluginConstants; +import org.openecomp.core.zusammen.plugin.dao.ElementRepository; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; + +import java.lang.reflect.Type; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.TreeMap; +import java.util.stream.Collectors; + +public class ElementRepositoryImpl implements ElementRepository { + + @Override + public Map<Id, Id> listIds(SessionContext context, ElementEntityContext elementContext) { + + if (elementContext.getRevisionId() == null) { + String revisionId = calculateLastRevisionId(context, elementContext); + if (revisionId == null) { + return new HashMap<>(); + } + + elementContext.setRevisionId(new Id(revisionId)); + } + return getVersionElementIds(context, elementContext).entrySet().stream().collect(Collectors + .toMap(entry -> new Id(entry.getKey()), entry -> new Id(entry.getValue()))); + + /* return getVersionElementIds(context, elementContext).stream() + .map(Id::new) + .collect(Collectors.toList());*/ + + } + + @Override + public void create(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + createElement(context, elementContext, element); + addElementToParent(context, elementContext, element); + } + + @Override + public void update(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + Id elementRevisionId = getElementRevision(context, elementContext, element.getId()); + if (elementRevisionId.equals(elementContext.getRevisionId())) { + updateElement(context, elementContext, element); + } else { + createElement(context, elementContext, element); + } + } + + @Override + public void delete(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + removeElementFromParent(context, elementContext, element); + deleteElement(context, elementContext, element); + } + + @Override + public Optional<ElementEntity> get(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + String revisionId = calculateElementRevisionId(context, elementContext, element); + if (revisionId == null) { + return Optional.empty(); + } + + Row row = getElementAccessor(context).get( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString(), + revisionId).one(); + + return row == null ? Optional.empty() : Optional.of(getElementEntity(element, row)); + } + + @Override + public Optional<ElementEntity> getDescriptor(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element) { + String revisionId = calculateElementRevisionId(context, elementContext, element); + if (revisionId == null) { + return Optional.empty(); + } + + Row row = getElementAccessor(context).getDescriptor( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString(), + revisionId).one(); + + return row == null ? Optional.empty() : Optional.of(getElementEntityDescriptor(element, row)); + } + + @Override + public void createNamespace(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + getElementNamespaceAccessor(context).create(elementContext.getItemId().toString(), + element.getId().toString(), + element.getNamespace().toString()); + } + + @Override + public Optional<Id> getHash(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + String revisionId = calculateElementRevisionId(context, elementContext, element); + if (revisionId == null) { + return Optional.empty(); + } + + Row row = getElementAccessor(context).getHash( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString(), + revisionId).one(); + + return row == null ? Optional.empty() : Optional.of(getElementHash(row)); + } + + private String calculateElementRevisionId(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element) { + + if (elementContext.getSpace().equals(ZusammenPluginConstants.PUBLIC_SPACE)) { + + String versionRevision; + if (elementContext.getRevisionId() == null) { + versionRevision = calculateLastRevisionId(context, elementContext); + } else { + versionRevision = elementContext.getRevisionId().getValue(); + } + + elementContext.setRevisionId(new Id(versionRevision)); + Map<String, String> elementIds = getVersionElementIds(context, elementContext); + if (elementIds.containsKey(element.getId().getValue())) { + return elementIds.get(element.getId().getValue()); + } else { + return null; + } + + } else { + return Id.ZERO.getValue(); + } + } + + private String calculateLastRevisionId(SessionContext context, ElementEntityContext + elementContext) { + List<Row> rows = getVersionElementsAccessor(context).listRevisions(elementContext.getSpace(), + elementContext + .getItemId().toString(), elementContext.getVersionId().toString()).all(); + if (rows == null || rows.size() == 0) { + return null; + } + rows.sort((o1, o2) -> o1.getDate(VersionElementsField.PUBLISH_TIME) + .after(o2.getDate(VersionElementsField.PUBLISH_TIME)) ? -1 : 1); + return rows.get(0).getString(VersionElementsField.REVISION_ID); + } + + /*private static String getVersionId(ElementEntityContext elementContext) { + return elementContext.getRevisionId() == null + ? elementContext.getVersionId().toString() + : elementContext.getRevisionId().getValue(); + }*/ + + private ElementNamespaceAccessor getElementNamespaceAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, ElementNamespaceAccessor.class); + } + + private ElementAccessor getElementAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, ElementAccessor.class); + } + + private VersionElementsAccessor getVersionElementsAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionElementsAccessor.class); + } + + private void createElement(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + createElementRow(context, elementContext, element); + + Map<String, String> elementIds = new TreeMap<>(); + elementIds.put(element.getId().toString(), elementContext.getRevisionId().getValue()); + getVersionElementsAccessor(context).addElements( + elementIds, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + private void createElementRow(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + Set<String> subElementIds = + element.getSubElementIds().stream().map(Id::toString).collect(Collectors.toSet()); + + getElementAccessor(context).create( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString(), + elementContext.getRevisionId().getValue(), + element.getParentId() == null ? null : element.getParentId().toString(), + element.getNamespace() == null ? null : element.getNamespace().toString(), + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + subElementIds, + element.getElementHash().getValue()); + } + + private void updateElement(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + + if (element.getParentId() == null) { + getElementAccessor(context).update( + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + element.getElementHash().getValue(), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString(), + elementContext.getRevisionId().getValue()); + } else { + getElementAccessor(context).update( + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + element.getElementHash().getValue(), + element.getParentId().getValue(), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().getValue(), + elementContext.getRevisionId().getValue()); + } + + Map<String, String> elementIds = new TreeMap<>(); + elementIds.put(element.getId().getValue(), elementContext.getRevisionId().getValue()); + getVersionElementsAccessor(context).addElements( + elementIds, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + private void deleteElement(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + + getElementAccessor(context).delete( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString(), + elementContext.getRevisionId().getValue()); + + getVersionElementsAccessor(context).removeElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + private void addElementToParent(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + if (element.getParentId() == null) { + return; + } + + + getElementAccessor(context).addSubElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getParentId().toString(), + elementContext.getRevisionId().getValue()); + + Map<String, String> elementIds = new TreeMap<>(); + elementIds.put(element.getParentId().toString(), elementContext.getRevisionId().getValue()); + getVersionElementsAccessor(context).addElements(elementIds, elementContext.getSpace(), + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + private void removeElementFromParent(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + if (element.getParentId() == null) { + return; + } + + Optional<ElementEntity> parentElement = + get(context, elementContext, new ElementEntity(element.getParentId())); + if (!parentElement.isPresent()) { + return; + } + getElementAccessor(context).removeSubElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getParentId().toString(), + elementContext.getRevisionId().getValue()); + + getVersionElementsAccessor(context) + .removeElements(Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + + Map<String, String> elementIds = new TreeMap<>(); + elementIds.put(element.getParentId().toString(), elementContext.getRevisionId().getValue()); + getVersionElementsAccessor(context).addElements(elementIds, elementContext.getSpace(), + elementContext.getItemId().getValue(), elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + static ElementEntity getElementEntityDescriptor(ElementEntity element, Row row) { + element.setNamespace(getNamespace(row.getString(ElementField.NAMESPACE))); + element.setParentId(getParentId(row.getString(ElementField.PARENT_ID))); + element.setInfo(json2Object(row.getString(ElementField.INFO), Info.class)); + element.setRelations( + json2Object(row.getString(ElementField.RELATIONS), new TypeToken<ArrayList<Relation>>() { + }.getType())); + + element.setSubElementIds(row.getSet(ElementField.SUB_ELEMENT_IDS, String.class) + .stream().map(Id::new).collect(Collectors.toSet())); + return element; + } + + static ElementEntity getElementEntity(ElementEntity element, Row row) { + getElementEntityDescriptor(element, row); + + element.setData(row.getBytes(ElementField.DATA)); + element.setSearchableData(row.getBytes(ElementField.SEARCHABLE_DATA)); + element.setVisualization(row.getBytes(ElementField.VISUALIZATION)); + element.setElementHash(new Id(row.getString(ElementField.ELEMENT_HASH))); + return element; + } + + private Id getElementHash(Row row) { + return new Id(row.getString(ElementField.ELEMENT_HASH)); + } + + private static Id getParentId(String parentIdStr) { + return parentIdStr == null ? null : new Id(parentIdStr); + } + + private static Namespace getNamespace(String namespaceStr) { + Namespace namespace = new Namespace(); + if (namespaceStr != null) { + namespace.setValue(namespaceStr); + } + return namespace; + } + + private static <T> T json2Object(String json, Type typeOfT) { + return json == null ? null : JsonUtil.json2Object(json, typeOfT); + } + + private Map<String, String> getVersionElementIds(SessionContext context, + ElementEntityContext elementContext) { + Row row = getVersionElementsAccessor(context).get( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()).one(); + return row == null + ? new HashMap<>() + : row.getMap(ElementRepositoryImpl.VersionElementsField.ELEMENT_IDS, String.class, String + .class); + } + + private Id getElementRevision(SessionContext context, ElementEntityContext elementContext + , Id elementId) { + Map<Id, Id> versionElementIds = + listIds(context, new ElementEntityContext + (elementContext.getSpace(), elementContext.getItemId(), elementContext.getVersionId(), + elementContext.getRevisionId())); + return versionElementIds.get(elementId); + + } + + + /* +CREATE TABLE IF NOT EXISTS element_namespace ( + item_id text, + element_id text, + namespace text, + PRIMARY KEY (( item_id, element_id )) +); + */ + @Accessor + interface ElementNamespaceAccessor { + @Query("UPDATE element_namespace SET namespace=:ns " + + "WHERE item_id=:item AND element_id=:id ") + void create(@Param("item") String itemId, + @Param("id") String elementId, + @Param("ns") String namespace); + } + + @Accessor + interface ElementAccessor { + @Query( + "UPDATE element SET parent_id=:parentId, namespace=:ns, info=:info, relations=:rels, " + + "data=:data, searchable_data=:searchableData, visualization=:visualization, " + + "sub_element_ids=sub_element_ids+:subs , element_hash=:elementHash " + + " WHERE space=:space AND item_id=:item AND version_id=:ver AND element_id=:id AND " + + "revision_id=:rev ") + void create(@Param("space") String space, + @Param("item") String itemId, + @Param("ver") String versionId, + @Param("id") String elementId, + @Param("rev") String revisionId, + @Param("parentId") String parentElementId, + @Param("ns") String namespace, + @Param("info") String info, + @Param("rels") String relations, + @Param("data") ByteBuffer data, + @Param("searchableData") ByteBuffer searchableData, + @Param("visualization") ByteBuffer visualization, + @Param("subs") Set<String> subElementIds, + @Param("elementHash") String elementHash); + + + @Query("UPDATE element SET info=?, relations=?, data=?, searchable_data=?, visualization=? ," + + "element_hash=? , parent_id=? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void update(String info, String relations, ByteBuffer data, ByteBuffer searchableData, + ByteBuffer visualization, String elementHash, String parentId, String space, String + itemId, String + versionId, String elementId, String revisionId); + + @Query("UPDATE element SET info=?, relations=?, data=?, searchable_data=?, visualization=? ," + + "element_hash=? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void update(String info, String relations, ByteBuffer data, ByteBuffer searchableData, + ByteBuffer visualization, String elementHash, String space, String + itemId, String + versionId, String elementId, String revisionId); + + @Query( + "DELETE FROM element WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void delete(String space, String itemId, String versionId, String elementId, String revisionId); + + @Query("SELECT parent_id, namespace, info, relations, data, searchable_data, visualization, " + + "sub_element_ids,element_hash FROM element " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + ResultSet get(String space, String itemId, String versionId, String elementId, String + revisionId); + + @Query("SELECT parent_id, namespace, info, relations, sub_element_ids FROM element " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + ResultSet getDescriptor(String space, String itemId, String versionId, String elementId, + String revisionId); + + @Query("UPDATE element SET sub_element_ids=sub_element_ids+? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void addSubElements(Set<String> subElementIds, String space, String itemId, String versionId, + String elementId, String revisionId); + + @Query("UPDATE element SET sub_element_ids=sub_element_ids-? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + void removeSubElements(Set<String> subElementIds, String space, String itemId, String versionId, + String elementId, String revisionId); + + @Query("SELECT element_hash FROM element " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id=? ") + ResultSet getHash(String space, String itemId, String versionId, String elementId, String + revisionId); + } + + private static final class ElementField { + private static final String NAMESPACE = "namespace"; + private static final String PARENT_ID = "parent_id"; + private static final String INFO = "info"; + private static final String RELATIONS = "relations"; + private static final String DATA = "data"; + private static final String SEARCHABLE_DATA = "searchable_data"; + private static final String VISUALIZATION = "visualization"; + private static final String SUB_ELEMENT_IDS = "sub_element_ids"; + private static final String ELEMENT_HASH = "element_hash"; + } + + @Accessor + interface VersionElementsAccessor { + + @Query("UPDATE version_elements SET element_ids=element_ids+ ? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void addElements(Map<String, String> elementIds, String space, String itemId, String versionId, + String versionRevisionId); + + @Query("UPDATE version_elements SET element_ids=element_ids-? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=?") + void removeElements(Set<String> elementIds, String space, String itemId, String versionId, + String revisionId); + + @Query( + "SELECT element_ids FROM version_elements WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + ResultSet get(String space, String itemId, String versionId, String revisionId); + + @Query( + "SELECT revision_id,publish_time FROM version_elements WHERE space=? AND item_id=? AND " + + "version_id=? ") + ResultSet listRevisions(String space, String itemId, String versionId); + + } + + private static final class VersionElementsField { + private static final String ELEMENT_IDS = "element_ids"; + private static final String REVISION_ID = "revision_id"; + private static final String PUBLISH_TIME = "publish_time"; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryFactoryImpl.java new file mode 100644 index 0000000000..02bec12302 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryFactoryImpl.java @@ -0,0 +1,31 @@ +/* + * Copyright © 2016-2017 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepositoryFactory; + +public class ElementStageRepositoryFactoryImpl extends ElementStageRepositoryFactory { + + private static final ElementStageRepository INSTANCE = new ElementStageRepositoryImpl(); + + @Override + public ElementStageRepository createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryImpl.java new file mode 100644 index 0000000000..c215f825a6 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementStageRepositoryImpl.java @@ -0,0 +1,423 @@ +/* + * Copyright © 2016-2017 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import com.amdocs.zusammen.utils.fileutils.json.JsonUtil; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Param; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepository; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; + +import java.nio.ByteBuffer; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +public class ElementStageRepositoryImpl implements ElementStageRepository { + + @Override + public Collection<ElementEntity> listIds(SessionContext context, + ElementEntityContext elementContext) { + return getElements(getStageElementIds(context, elementContext)); + } + + @Override + public Collection<ElementEntity> listConflictedIds(SessionContext context, + ElementEntityContext elementContext) { + return getElements(getConflictedElementIds(context, elementContext)); + } + + @Override + public void create(SessionContext context, ElementEntityContext elementContext, + StageEntity<ElementEntity> elementStage) { + createElement(context, elementContext, elementStage); + addElementToParent(context, elementContext, elementStage.getEntity()); + } + + @Override + public void markAsNotConflicted(SessionContext context, ElementEntityContext elementContext, + ElementEntity element, Action action) { + getElementStageAccessor(context).updateState(action, false, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString()); + + getStageElementsAccessor(context).removeConflictElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + @Override + public void markAsNotConflicted(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + getElementStageAccessor(context).markAsNotConflicted( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString()); + + getStageElementsAccessor(context).removeConflictElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + @Override + public void update(SessionContext context, ElementEntityContext elementContext, + ElementEntity element, Action action, boolean conflicted) { + getElementStageAccessor(context).update( + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + element.getElementHash().getValue(), + action, + conflicted, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + element.getId().toString()); + + if (!conflicted) { + getStageElementsAccessor(context).removeConflictElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + } + + @Override + public void delete(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + removeElementFromParent(context, elementContext, element); + deleteElement(context, elementContext, element); + } + + @Override + public Optional<StageEntity<ElementEntity>> get(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element) { + Row row = getElementStageAccessor(context).get( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString()).one(); + + return row == null ? Optional.empty() : Optional.of(getStageElement(row)); + } + + @Override + public Optional<StageEntity<ElementEntity>> getDescriptor(SessionContext context, + ElementEntityContext elementContext, + ElementEntity element) { + Row row = getElementStageAccessor(context).getDescriptor( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString()).one(); + + return row == null ? Optional.empty() : Optional.of(getStageElementDescriptor(row)); + } + + + + private Collection<ElementEntity> getElements(Set<String> elementIds) { + return elementIds.stream() + .map(id -> new ElementEntity(new Id(id))) + .collect(Collectors.toList()); + } + + private void createElement(SessionContext context, ElementEntityContext elementContext, + StageEntity<ElementEntity> elementStage) { + + + ElementEntity element = elementStage.getEntity(); + Set<String> subElementIds = + element.getSubElementIds().stream().map(Id::toString).collect(Collectors.toSet()); + Set<String> conflictDependents = elementStage.getConflictDependents().stream() + .map(conflictDependent -> conflictDependent.getId().getValue()) + .collect(Collectors.toSet()); + + getElementStageAccessor(context).create( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString(), + element.getParentId() == null ? null : element.getParentId().toString(), + element.getNamespace() == null ? null : element.getNamespace().toString(), + JsonUtil.object2Json(element.getInfo()), + JsonUtil.object2Json(element.getRelations()), + element.getData(), + element.getSearchableData(), + element.getVisualization(), + subElementIds, + element.getElementHash() == null ? null : element.getElementHash().getValue(), + elementStage.getPublishTime(), + elementStage.getAction(), + elementStage.isConflicted(), + conflictDependents); + + getStageElementsAccessor(context).add( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + + if (elementStage.isConflicted()) { + getStageElementsAccessor(context).addConflictElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + } + + private void deleteElement(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + + + getElementStageAccessor(context).delete( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getId().toString()); + + getStageElementsAccessor(context).remove( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()); + } + + private void addElementToParent(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + if (element.getParentId() == null) { + return; + } + getElementStageAccessor(context).addSubElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getParentId().toString()); + } + + private void removeElementFromParent(SessionContext context, ElementEntityContext elementContext, + ElementEntity element) { + if (element.getParentId() == null) { + return; + } + getElementStageAccessor(context).removeSubElements( + Collections.singleton(element.getId().toString()), + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + element.getParentId().toString()); + } + + private StageEntity<ElementEntity> getStageElementDescriptor(Row row) { + return buildStageElement(ElementRepositoryImpl.getElementEntityDescriptor( + new ElementEntity(new Id(row.getString(ElementStageField.ID))), row), row); + } + + private StageEntity<ElementEntity> getStageElement(Row row) { + return buildStageElement(ElementRepositoryImpl.getElementEntity( + new ElementEntity(new Id(row.getString(ElementStageField.ID))), row), row); + } + + + private StageEntity<ElementEntity> buildStageElement(ElementEntity element, Row row) { + StageEntity<ElementEntity> elementStage = + new StageEntity<>(element, row.getDate(ElementStageField.PUBLISH_TIME)); + elementStage.setAction(Action.valueOf(row.getString(ElementStageField.ACTION))); + elementStage.setConflicted(row.getBool(ElementStageField.CONFLICTED)); + elementStage.setConflictDependents( + row.getSet(ElementStageField.CONFLICT_DEPENDENTS, String.class).stream() + .map(conflictDependentId -> new ElementEntity(new Id(conflictDependentId))) + .collect(Collectors.toSet())); + return elementStage; + } + + private Set<String> getStageElementIds(SessionContext context, + ElementEntityContext elementContext) { + Row row = getStageElementsAccessor(context).get( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()).one(); + return row == null ? new HashSet<>() + : row.getSet(StageElementsField.STAGE_ELEMENT_IDS, String.class); + } + + private Set<String> getConflictedElementIds(SessionContext context, + ElementEntityContext elementContext) { + Row row = getStageElementsAccessor(context).getConflicted( + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().getValue(), + elementContext.getRevisionId().getValue()).one(); + return row == null ? new HashSet<>() + : row.getSet(StageElementsField.CONFLICT_ELEMENT_IDS, String.class); + } + + private ElementStageAccessor getElementStageAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, ElementStageAccessor.class); + } + + private StageElementsAccessor getStageElementsAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, StageElementsAccessor.class); + } + + @Accessor + interface ElementStageAccessor { + @Query( + "UPDATE element_stage SET parent_id=:parentId, namespace=:ns, info=:info, relations=:rels, " + + "data=:data, searchable_data=:searchableData, visualization=:visualization, " + + "publish_time=:publishTime, action=:action, " + + "conflicted=:conflicted, conflict_dependent_ids=:conflictDependents, " + + "sub_element_ids=sub_element_ids+:subs, element_hash=:elementHash " + + "WHERE space=:space AND item_id=:item AND version_id=:ver AND element_id=:id ") + void create(@Param("space") String space, + @Param("item") String itemId, + @Param("ver") String versionId, + @Param("id") String elementId, + @Param("parentId") String parentElementId, + @Param("ns") String namespace, + @Param("info") String info, + @Param("rels") String relations, + @Param("data") ByteBuffer data, + @Param("searchableData") ByteBuffer searchableData, + @Param("visualization") ByteBuffer visualization, + @Param("subs") Set<String> subElementIds, + @Param("elementHash") String elementHash, + @Param("publishTime") Date publishTime, + @Param("action") Action action, + @Param("conflicted") boolean conflicted, + @Param("conflictDependents") Set<String> conflictDependents); + + @Query("UPDATE element_stage SET info=?, relations=?, data=?, searchable_data=?, " + + "visualization=?,element_hash=?, action=?, conflicted=? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void update(String info, String relations, ByteBuffer data, ByteBuffer searchableData, + ByteBuffer visualization, String elementHash, Action action, boolean conflicted, + String space, + String itemId, String versionId, String elementId); + + @Query("UPDATE element_stage SET action=?, conflicted=? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void updateState(Action action, boolean conflicted, String space, String itemId, + String versionId, String elementId); + + @Query("UPDATE element_stage SET conflicted=false " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void markAsNotConflicted(String space, String itemId, String versionId, String elementId); + + @Query( + "DELETE FROM element_stage WHERE space=? AND item_id=? AND version_id=? AND element_id=?") + void delete(String space, String itemId, String versionId, String elementId); + + @Query("SELECT element_id, parent_id, namespace, info, relations, data, searchable_data, " + + "visualization, sub_element_ids,element_hash, publish_time, action, " + + "conflicted, conflict_dependent_ids FROM element_stage " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + ResultSet get(String space, String itemId, String versionId, String elementId); + + @Query("SELECT element_id, parent_id, namespace, info, relations, " + + "sub_element_ids, publish_time, action, conflicted, conflict_dependent_ids " + + "FROM element_stage WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + ResultSet getDescriptor(String space, String itemId, String versionId, String elementId); + + @Query("UPDATE element_stage SET sub_element_ids=sub_element_ids+? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void addSubElements(Set<String> subElementIds, String space, String itemId, String versionId, + String elementId); + + @Query("UPDATE element_stage SET sub_element_ids=sub_element_ids-? " + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? ") + void removeSubElements(Set<String> subElementIds, String space, String itemId, String versionId, + String elementId); + } + + private static final class ElementStageField { + private static final String ID = "element_id"; + private static final String PUBLISH_TIME = "publish_time"; + private static final String ACTION = "action"; + private static final String CONFLICTED = "conflicted"; + private static final String CONFLICT_DEPENDENTS = "conflict_dependent_ids"; + } + + @Accessor + interface StageElementsAccessor { + + @Query("UPDATE version_elements SET stage_element_ids=stage_element_ids+? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void add(Set<String> elementIds, String space, String itemId, String versionId, String + revisionId); + + @Query("UPDATE version_elements SET stage_element_ids=stage_element_ids-? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void remove(Set<String> elementIds, String space, String itemId, String versionId, String + revisionId); + + @Query("SELECT stage_element_ids FROM version_elements " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=?") + ResultSet get(String space, String itemId, String versionId, String revisionId); + + @Query("UPDATE version_elements SET conflict_element_ids=conflict_element_ids+? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void addConflictElements(Set<String> elementIds, String space, String itemId, String + versionId, String revisionId); + + @Query("UPDATE version_elements SET conflict_element_ids=conflict_element_ids-? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void removeConflictElements(Set<String> elementIds, String space, String itemId, + String versionId, String revisionId); + + @Query("SELECT conflict_element_ids FROM version_elements " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + ResultSet getConflicted(String space, String itemId, String versionId, String revisionId); + } + + private static final class StageElementsField { + private static final String STAGE_ELEMENT_IDS = "stage_element_ids"; + private static final String CONFLICT_ELEMENT_IDS = "conflict_element_ids"; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryFactoryImpl.java new file mode 100644 index 0000000000..ec7e1c30ae --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryFactoryImpl.java @@ -0,0 +1,33 @@ +/* + * Copyright © 2016-2017 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepositoryFactory; + +public class ElementSynchronizationStateRepositoryFactoryImpl + extends ElementSynchronizationStateRepositoryFactory { + + private static final ElementSynchronizationStateRepository INSTANCE = + new ElementSynchronizationStateRepositoryImpl(); + + @Override + public ElementSynchronizationStateRepository createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryImpl.java new file mode 100644 index 0000000000..d41d3d73b1 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/ElementSynchronizationStateRepositoryImpl.java @@ -0,0 +1,209 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; + +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +public class ElementSynchronizationStateRepositoryImpl + implements ElementSynchronizationStateRepository { + + @Override + public Collection<SynchronizationStateEntity> list(SessionContext context, + ElementEntityContext elementContext) { + List<Row> rows = getAccessor(context) + .list(elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString()).all(); + return rows == null ? new HashSet<>() + : rows.stream().map(this::getSynchronizationStateEntity).collect(Collectors.toSet()); + + } + + @Override + public void create(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + update(context, elementContext.getSpace(), + elementContext.getItemId(), + elementContext.getVersionId(), + elementContext.getRevisionId(), + elementSyncState.getRevisionId(), + elementSyncState.getId(), + elementSyncState.getPublishTime(), + elementSyncState.isDirty() + + ); + } + + @Override + public void update(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + update(context, elementContext.getSpace(), + elementContext.getItemId(), + elementContext.getVersionId(), + elementContext.getRevisionId(), + elementSyncState.getRevisionId(), + elementSyncState.getId(), + elementSyncState.getPublishTime(), + elementSyncState.isDirty() + + ); + } + + @Override + public void markAsDirty(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + + + getAccessor(context).updateDirty(true, + elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementSyncState.getId().toString(), + elementContext.getRevisionId().getValue()); + + getVersionElementsAccessor(context).addDirtyElements( + Collections.singleton(elementSyncState.getId().toString()), elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + @Override + public void delete(SessionContext context, ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + getAccessor(context).delete(elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementSyncState.getId().toString(), + elementContext.getRevisionId().getValue()); + + getVersionElementsAccessor(context).removeDirtyElements( + Collections.singleton(elementSyncState.getId().toString()), elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementContext.getRevisionId().getValue()); + } + + @Override + public Optional<SynchronizationStateEntity> get(SessionContext context, + ElementEntityContext elementContext, + SynchronizationStateEntity elementSyncState) { + + Row row = getAccessor(context) + .get(elementContext.getSpace(), + elementContext.getItemId().toString(), + elementContext.getVersionId().toString(), + elementSyncState.getId().toString(), + elementSyncState.getRevisionId().getValue()).one(); + + return row == null ? Optional.empty() : Optional.of(getSynchronizationStateEntity(row)); + } + + private void update(SessionContext context, String space, Id itemId, Id versionId, Id + versionRevisionId,Id elementRevisionId,Id elementId, Date publishTime, boolean isDirty) { + getAccessor(context).update(publishTime, + isDirty, + space, + itemId.toString(), + versionId.toString(), + elementId.toString(), + elementRevisionId.getValue()); + + if (isDirty) { + getVersionElementsAccessor(context).addDirtyElements( + Collections.singleton(elementId.toString()), space, + itemId.toString(), + versionId.toString(), + versionRevisionId.getValue()); + } else { + getVersionElementsAccessor(context).removeDirtyElements( + Collections.singleton(elementId.toString()), space, + itemId.toString(), + versionId.toString(), + versionRevisionId.getValue()); + } + } + + + private SynchronizationStateEntity getSynchronizationStateEntity(Row row) { + SynchronizationStateEntity entity = + new SynchronizationStateEntity(new Id(row.getString(SynchronizationStateField.ID)), + new Id(row.getString(SynchronizationStateField.REVISION_ID)), + row.getDate(SynchronizationStateField.PUBLISH_TIME), + row.getBool(SynchronizationStateField.DIRTY)); + entity.setRevisionId(new Id(row.getString(SynchronizationStateField.REVISION_ID))); + + return entity; + + } + + private ElementSynchronizationStateAccessor getAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, ElementSynchronizationStateAccessor.class); + } + + private VersionElementsAccessor getVersionElementsAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionElementsAccessor.class); + } + + @Accessor + interface ElementSynchronizationStateAccessor { + @Query("UPDATE element_synchronization_state SET publish_time=?, dirty=? " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id = ? ") + void update(Date publishTime, boolean dirty, String space, String itemId, String versionId, + String elementId, String revisionId); + + @Query("UPDATE element_synchronization_state SET dirty=? " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id = ? ") + void updateDirty(boolean dirty, String space, String itemId, String versionId, + String elementId, String revisionId); + + @Query("DELETE FROM element_synchronization_state " + + "WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id = ? ") + void delete(String space, String itemId, String versionId, String elementId, String revisionId); + + @Query("SELECT element_id,revision_id, publish_time, dirty FROM element_synchronization_state" + + " WHERE space=? AND item_id=? AND version_id=?") + ResultSet list(String space, String itemId, String versionId); + + @Query("SELECT element_id,revision_id, publish_time, dirty FROM element_synchronization_state" + + " WHERE space=? AND item_id=? AND version_id=? AND element_id=? AND revision_id = ? ") + ResultSet get(String space, String itemId, String versionId, String elementId, String + revisionId); + } + + private static final class SynchronizationStateField { + private static final String ID = "element_id"; + private static final String PUBLISH_TIME = "publish_time"; + private static final String DIRTY = "dirty"; + private static final String REVISION_ID = "revision_id"; + } + + @Accessor + interface VersionElementsAccessor { + + @Query("UPDATE version_elements SET dirty_element_ids=dirty_element_ids+? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=?") + void addDirtyElements(Set<String> elementIds, String space, String itemId, String versionId, + String revisionId); + + @Query("UPDATE version_elements SET dirty_element_ids=dirty_element_ids-? " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + void removeDirtyElements(Set<String> elementIds, String space, String itemId, String + versionId, String revisionId); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoFactoryImpl.java new file mode 100644 index 0000000000..60dc9d1765 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoFactoryImpl.java @@ -0,0 +1,15 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory; + +public class VersionDaoFactoryImpl extends VersionDaoFactory { + + private static final VersionDao INSTANCE = new VersionDaoImpl(); + + @Override + public VersionDao createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoImpl.java new file mode 100644 index 0000000000..bba2ddf267 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionDaoImpl.java @@ -0,0 +1,185 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; + +import static java.util.stream.Collectors.toMap; + +public class VersionDaoImpl implements VersionDao { + + @Override + public void create(SessionContext context, String space, Id itemId, VersionEntity version) { + String baseVersion = version.getBaseId() != null ? version.getBaseId().toString() : null; + + getAccessor(context) + .create(space, itemId.toString(), version.getId().toString(), + baseVersion, + version.getCreationTime(), version.getModificationTime()); + + } + + @Override + public void delete(SessionContext context, String space, Id itemId, Id versionId) { + + getAccessor(context).delete(space, itemId.toString(), versionId.toString()); + } + + @Override + public void updateModificationTime(SessionContext context, String space, Id itemId, + Id versionId, Date modificationTime) { + getAccessor(context) + .updateModificationTime(modificationTime, space, itemId.toString(), versionId.toString()); + } + + + @Override + public Collection<VersionEntity> list(SessionContext context, String space, Id itemId) { + List<Row> rows = getAccessor(context).list(space, itemId.toString()).all(); + return rows == null ? new ArrayList<>() : + rows.stream().map(VersionDaoImpl::convertToVersionEntity).collect(Collectors.toList()); + } + + + @Override + public Optional<VersionEntity> get(SessionContext context, String space, Id itemId, + Id versionId) { + Row row; + + row = getAccessor(context).get(space, itemId.toString(), versionId.toString()).one(); + + + return row == null ? Optional.empty() : Optional.of(convertToVersionEntity(row)); + } + + @Override + public boolean checkHealth(SessionContext context) { + return getAccessor(context).checkHealth().getColumnDefinitions() + .contains(VersionField.VERSION_ID); + } + + @Override + public void createVersionElements(SessionContext context, String space, Id itemId, + Id versionId, Id revisionId, Map<Id, Id> versionElementIds, + Date publishTime, String message) { + Map<String, String> elementIds = versionElementIds==null?null:versionElementIds. + entrySet(). + stream(). + collect(toMap((Map.Entry<Id, Id>entry)->entry.getKey().getValue(), + (Map.Entry<Id, Id>entry)->entry.getValue().getValue())); + + getVersionElementsAccessor(context).create(space,itemId.toString(),versionId.toString(), + revisionId.getValue(),elementIds,publishTime,message,context.getUser().getUserName()); + } + + + private static VersionEntity convertToVersionEntity(Row row) { + + /*Id revisionId = row.getColumnDefinitions().contains("revision_id")?new Id(row.getString + (VersionField.REVISION_ID)):null;*/ + + VersionEntity version = new VersionEntity(new Id(row.getString(VersionField.VERSION_ID))); + return enrichVersionEntity(version, row); + } + + static VersionEntity enrichVersionEntity(VersionEntity version, Row row) { + version.setBaseId(new Id(row.getString(VersionField.BASE_VERSION_ID))); + version.setCreationTime(row.getDate(VersionField.CREATION_TIME)); + version.setModificationTime(row.getDate(VersionField.MODIFICATION_TIME)); + return version; + } + + private VersionAccessor getAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionAccessor.class); + } + + private VersionElementsAccessor getVersionElementsAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionElementsAccessor.class); + } + + @Accessor + interface VersionAccessor { + + @Query( + "INSERT INTO version (space, item_id, version_id, base_version_id, " + + "creation_time, " + + "modification_time) " + + "VALUES (?, ?, ?, ?, ?, ?)") + void create(String space, String itemId, String versionId, String baseVersionId, + Date creationTime, Date modificationTime); + + @Query("UPDATE version SET modification_time=? WHERE space=? AND item_id=? AND version_id=? ") + void updateModificationTime(Date modificationTime, String space, String itemId, + String versionId); + + @Query("DELETE FROM version WHERE space=? AND item_id=? AND version_id=? ") + void delete(String space, String itemId, String versionId); + + @Query("SELECT version_id, base_version_id, creation_time, modification_time " + + "FROM version WHERE space=? AND item_id=? AND version_id=? ") + ResultSet get(String space, String itemId, String versionId); + + /*@Query("SELECT version_id, base_version_id, creation_time, modification_time " + + "FROM version WHERE space=? AND item_id=? AND version_id=? ") + ResultSet get(String space, String itemId, String versionId);*/ + + + @Query("SELECT version_id, base_version_id, creation_time, modification_time " + + "FROM version WHERE space=? AND item_id=?") + ResultSet list(String space, String itemId); + + @Query("SELECT version_id FROM version LIMIT 1") + ResultSet checkHealth(); + } + + private static final class VersionField { + private static final String VERSION_ID = "version_id"; + private static final String BASE_VERSION_ID = "base_version_id"; + private static final String CREATION_TIME = "creation_time"; + private static final String MODIFICATION_TIME = "modification_time"; + //private static final String REVISION_ID = "revision_id"; + } + + @Accessor + interface VersionElementsAccessor { + + @Query("INSERT INTO version_elements (space,item_id,version_id,revision_id,element_ids," + + "publish_time,message,user) " + + "VALUES (?,?,?,?,?,?,?,?)") + void create(String space, + String itemId, + String versionId, + String versionRevisionId, + Map<String,String> elementIds, + Date publishTime, + String message, + String user); + + + + } + + /* public static final class VersionElementsField { + private static final String SPACE = "space"; + private static final String ITEM_ID = "item_id"; + private static final String VERSION_ID = "version_id"; + private static final String ELEMENT_IDS = "element_ids"; + private static final String REVISION_ID = "revision_id"; + + }*/ + + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryFactoryImpl.java new file mode 100644 index 0000000000..547bf6a06c --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryFactoryImpl.java @@ -0,0 +1,15 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.VersionStageRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionStageRepositoryFactory; + +public class VersionStageRepositoryFactoryImpl extends VersionStageRepositoryFactory { + + private static final VersionStageRepository INSTANCE = new VersionStageRepositoryImpl(); + + @Override + public VersionStageRepository createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryImpl.java new file mode 100644 index 0000000000..353f37b91b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionStageRepositoryImpl.java @@ -0,0 +1,82 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.zusammen.plugin.dao.VersionStageRepository; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.Date; +import java.util.Optional; + +public class VersionStageRepositoryImpl implements VersionStageRepository { + + @Override + public Optional<StageEntity<VersionEntity>> get(SessionContext context, + VersionContext entityContext, + VersionEntity entity) { + Row row = getAccessor(context) + .get(entityContext.getSpace(), entityContext.getItemId().toString(), + entity.getId().toString()).one(); + return row == null ? Optional.empty() : Optional.of(convertToVersionStage(entity, row)); + } + + @Override + public void create(SessionContext context, VersionContext entityContext, + StageEntity<VersionEntity> stageEntity) { + VersionEntity entity = stageEntity.getEntity(); + getAccessor(context).create(entityContext.getSpace(), + entityContext.getItemId().toString(), + entity.getId().toString(), + entity.getBaseId() == null ? null : entity.getBaseId().toString(), + entity.getCreationTime() == null ? null : entity.getCreationTime(), + entity.getModificationTime() == null ? null : entity.getModificationTime(), + stageEntity.getPublishTime(), + stageEntity.getAction()); + } + + @Override + public void delete(SessionContext context, VersionContext entityContext, VersionEntity entity) { + getAccessor(context).delete(entityContext.getSpace(), entityContext.getItemId().toString(), + entity.getId().toString()); + } + + private StageEntity<VersionEntity> convertToVersionStage(VersionEntity version, Row row) { + StageEntity<VersionEntity> versionStage = + new StageEntity<>(VersionDaoImpl.enrichVersionEntity(version, row), + row.getDate(VersionStageField.PUBLISH_TIME)); + versionStage.setAction(Action.valueOf(row.getString(VersionStageField.ACTION))); + return versionStage; + } + + private VersionStageAccessor getAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionStageAccessor.class); + } + + @Accessor + interface VersionStageAccessor { + + @Query("INSERT INTO version_stage (space, item_id, version_id, base_version_id, " + + "creation_time, modification_time, publish_time, action) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)") + void create(String space, String itemId, String versionId, String baseVersionId, + Date creationTime, Date modificationTime, Date publishTime, Action action); + + @Query("DELETE FROM version_stage WHERE space=? AND item_id=? AND version_id=?") + void delete(String space, String itemId, String versionId); + + @Query("SELECT base_version_id, creation_time, modification_time, publish_time, action " + + "FROM version_stage WHERE space=? AND item_id=? AND version_id=?") + ResultSet get(String space, String itemId, String versionId); + } + + private static final class VersionStageField { + private static final String PUBLISH_TIME = "publish_time"; + private static final String ACTION = "action"; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryFactoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryFactoryImpl.java new file mode 100644 index 0000000000..95c3ec2730 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryFactoryImpl.java @@ -0,0 +1,33 @@ +/* + * Copyright © 2016-2017 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.SessionContext; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepositoryFactory; + +public class VersionSynchronizationStateRepositoryFactoryImpl + extends VersionSynchronizationStateRepositoryFactory { + + private static final VersionSynchronizationStateRepository INSTANCE = + new VersionSynchronizationStateRepositoryImpl(); + + @Override + public VersionSynchronizationStateRepository createInterface(SessionContext context) { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryImpl.java new file mode 100644 index 0000000000..5fb9779bc2 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/impl/cassandra/VersionSynchronizationStateRepositoryImpl.java @@ -0,0 +1,137 @@ +package org.openecomp.core.zusammen.plugin.dao.impl.cassandra; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepository; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionContext; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +public class VersionSynchronizationStateRepositoryImpl + implements VersionSynchronizationStateRepository { + + @Override + public void create(SessionContext context, VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + updatePublishTime(context, entityContext, syncStateEntity); + } + + @Override + public void updatePublishTime(SessionContext context, VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + getAccessor(context) + .updatePublishTime(syncStateEntity.getPublishTime(), entityContext.getSpace(), + entityContext.getItemId().toString(), syncStateEntity.getId().toString(), + syncStateEntity.getRevisionId().getValue()); + } + + @Override + public List<SynchronizationStateEntity> list(SessionContext context, VersionContext + entityContext, VersionEntity versionEntity) { + + List<Row> rows = getAccessor(context).list(entityContext.getSpace(), entityContext.getItemId().toString + (),versionEntity.getId().toString()).all(); + return rows == null ? new ArrayList<>(): + rows.stream().map(VersionSynchronizationStateRepositoryImpl::getSynchronizationStateEntity).collect(Collectors.toList()); + } + + + + /*@Override + public List<SynchronizationStateEntity> listRevisions(SessionContext context, + VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + List<Row> rows = getAccessor(context).list(entityContext.getSpace(), entityContext.getItemId() + .toString(), syncStateEntity.getId().toString()).all(); + return rows == null ? new ArrayList<>() :rows.stream() + .map(VersionSynchronizationStateRepositoryImpl::getSynchronizationStateEntity) + .collect(Collectors.toList()); + + + + + //forEach(row -> getSynchronizationStateEntity(syncStateEntity.getId(), row)); + + + }*/ + + + @Override + public void delete(SessionContext context, VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + // done by version dao + } + + @Override + public Optional<SynchronizationStateEntity> get(SessionContext context, + VersionContext entityContext, + SynchronizationStateEntity syncStateEntity) { + Row row = + getAccessor(context).get(entityContext.getSpace(), entityContext.getItemId().toString(), + syncStateEntity.getId().toString(), syncStateEntity.getRevisionId().getValue()).one(); + + return row == null ? Optional.empty() + : Optional.of(getSynchronizationStateEntity(syncStateEntity.getId(), row)); + } + + private SynchronizationStateEntity getSynchronizationStateEntity(Id entityId, Row row) { + SynchronizationStateEntity syncStateEntity = new SynchronizationStateEntity(entityId, + new Id(row.getString(REVISION_ID_FIELD))); + syncStateEntity.setPublishTime(row.getDate(PUBLISH_TIME_FIELD)); + syncStateEntity.setDirty(!row.getSet(DIRTY_ELEMENT_FIELD, String.class).isEmpty()); + return syncStateEntity; + } + + private static SynchronizationStateEntity getSynchronizationStateEntity(Row row) { + Id entityId = new Id(row.getColumnDefinitions().contains("version_id") ? row.getString + ("version_id") : row.getString("element_id")); + SynchronizationStateEntity syncStateEntity = new SynchronizationStateEntity(entityId, + new Id(row.getString(REVISION_ID_FIELD))); + syncStateEntity.setPublishTime(row.getDate(PUBLISH_TIME_FIELD)); + syncStateEntity.setDirty(!row.getSet(DIRTY_ELEMENT_FIELD, String.class).isEmpty()); + syncStateEntity.setRevisionId(new Id(row.getString(REVISION_ID_FIELD))); + syncStateEntity.setUser(row.getString(USER)); + syncStateEntity.setMessage(row.getString(MESSAGE)); + return syncStateEntity; + } + + private VersionSyncStateAccessor getAccessor(SessionContext context) { + return CassandraDaoUtils.getAccessor(context, VersionSyncStateAccessor.class); + } + + @Accessor + interface VersionSyncStateAccessor { + @Query( + "UPDATE version_elements SET publish_time=? WHERE space=? AND item_id=? AND version_id=? " + + "AND revision_id=? ") + void updatePublishTime(Date publishTime, String space, String itemId, String versionId, String + revisionId); + + @Query("SELECT version_id,revision_id,publish_time, dirty_element_ids FROM version_elements " + + "WHERE space=? AND item_id=? AND version_id=? AND revision_id=? ") + ResultSet get(String space, String itemId, String versionId, String revisionId); + + @Query("SELECT version_id,revision_id,publish_time,user,message, dirty_element_ids FROM " + + "version_elements " + + "WHERE space=? AND item_id=? AND version_id=? ") + ResultSet list(String space, String itemId, String versionId); + + } + + + private static final String PUBLISH_TIME_FIELD = "publish_time"; + private static final String DIRTY_ELEMENT_FIELD = "dirty_element_ids"; + private static final String REVISION_ID_FIELD = "revision_id"; + private static final String USER = "user"; + private static final String MESSAGE = "message"; +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/ElementEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/ElementEntity.java index 1663d83427..1cd15102f2 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/ElementEntity.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/ElementEntity.java @@ -30,6 +30,7 @@ public class ElementEntity { private Id id; private Id parentId; private Namespace namespace; + private Id elementHash; private Info info; private Collection<Relation> relations = Collections.emptyList(); private ByteBuffer data; @@ -41,6 +42,10 @@ public class ElementEntity { this.id = id; } + public Id getId() { + return id; + } + public Id getParentId() { return parentId; } @@ -49,14 +54,6 @@ public class ElementEntity { this.parentId = parentId; } - public Id getId() { - return id; - } - - public void setId(Id id) { - this.id = id; - } - public Namespace getNamespace() { return namespace; } @@ -127,8 +124,17 @@ public class ElementEntity { return id.equals(that.id); } + public Id getElementHash() { + return elementHash; + } + + public void setElementHash(Id elementHash) { + this.elementHash = elementHash; + } + @Override public int hashCode() { return id.hashCode(); } + } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/StageEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/StageEntity.java new file mode 100644 index 0000000000..58ac0a918a --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/StageEntity.java @@ -0,0 +1,60 @@ +package org.openecomp.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.item.Action; + +import java.util.Collections; +import java.util.Date; +import java.util.Set; + +public class StageEntity<E> { + private E entity; + private Date publishTime; + private Action action = Action.IGNORE; + private boolean conflicted; + private Set<E> conflictDependents = Collections.emptySet(); + + // used by sync on stage creation + public StageEntity(E entity, Date publishTime) { + this.entity = entity; + this.publishTime = publishTime; + } + + public StageEntity(E entity, Date publishTime, Action action, boolean conflicted) { + this.entity = entity; + this.publishTime = publishTime; + this.action = action; + this.conflicted = conflicted; + } + + public E getEntity() { + return entity; + } + + public Date getPublishTime() { + return publishTime; + } + + public Action getAction() { + return action; + } + + public void setAction(Action action) { + this.action = action; + } + + public boolean isConflicted() { + return conflicted; + } + + public void setConflicted(boolean conflicted) { + this.conflicted = conflicted; + } + + public Set<E> getConflictDependents() { + return conflictDependents; + } + + public void setConflictDependents(Set<E> conflictDependents) { + this.conflictDependents = conflictDependents; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/SynchronizationStateEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/SynchronizationStateEntity.java new file mode 100644 index 0000000000..510cef820b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/SynchronizationStateEntity.java @@ -0,0 +1,116 @@ +/* + * Copyright © 2016-2017 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.Id; + +import java.util.Date; + +/** + * Synchronization state of an entity: + * <ul> + * <li>On private entity edit (create/update/delete): marked as dirty</li> + * <li>On entity publication: + * <ul> + * <li>if the private entity exists - updated with the publish time, marked as not dirty</li> + * <li>Otherwise - deleted</li> + * </ul> + * </li> + * </ul> + */ +public class SynchronizationStateEntity { + private Id id; + private Id revisionId; + private Date publishTime; + private boolean dirty; + private String user; + private String message; + + public SynchronizationStateEntity(Id id,Id revisionId) { + this.id = id; + this.revisionId = revisionId; + } + + public SynchronizationStateEntity(Id id,Id revisionId, Date publishTime, boolean dirty) { + this(id,revisionId); + this.publishTime = publishTime; + this.dirty = dirty; + } + + public Id getId() { + return id; + } + + public Date getPublishTime() { + return publishTime; + } + + public void setPublishTime(Date publishTime) { + this.publishTime = publishTime; + } + + public boolean isDirty() { + return dirty; + } + + public void setDirty(boolean dirty) { + this.dirty = dirty; + } + + public Id getRevisionId() { + return revisionId; + } + + public void setRevisionId(Id revisionId) { + this.revisionId = revisionId; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + SynchronizationStateEntity that = (SynchronizationStateEntity) o; + + return id.equals(that.id); + } + + @Override + public int hashCode() { + return id.hashCode(); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionContext.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionContext.java new file mode 100644 index 0000000000..41a3e66e0e --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionContext.java @@ -0,0 +1,23 @@ +package org.openecomp.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.Id; + +public class VersionContext { + private String space; + private Id itemId; + + + public VersionContext(String space, Id itemId) { + this.space = space; + this.itemId = itemId; + } + + public String getSpace() { + return space; + } + + public Id getItemId() { + return itemId; + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionDataElement.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionDataElement.java new file mode 100644 index 0000000000..48a52c0d85 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionDataElement.java @@ -0,0 +1,21 @@ +package org.openecomp.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import org.openecomp.core.zusammen.plugin.ZusammenPluginConstants; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.calculateElementHash; + +public class VersionDataElement extends ElementEntity { + + public VersionDataElement() { + super(ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID); + } + + public VersionDataElement(ItemVersionData itemVersionData) { + this(); + setInfo(itemVersionData.getInfo()); + setRelations(itemVersionData.getRelations()); + setElementHash(new Id(calculateElementHash(this))); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionEntity.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionEntity.java new file mode 100644 index 0000000000..aeed998d96 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/dao/types/VersionEntity.java @@ -0,0 +1,45 @@ +package org.openecomp.core.zusammen.plugin.dao.types; + +import com.amdocs.zusammen.datatypes.Id; + +import java.util.Date; + +public class VersionEntity { + private Id id; + private Id baseId; + private Date creationTime; + private Date modificationTime; + + public VersionEntity(Id id) { + this.id = id; + } + + public Id getId() { + return id; + } + + public Id getBaseId() { + return baseId; + } + + public void setBaseId(Id baseId) { + this.baseId = baseId; + } + + public Date getCreationTime() { + return creationTime; + } + + public void setCreationTime(Date creationTime) { + this.creationTime = creationTime; + } + + public Date getModificationTime() { + return modificationTime; + } + + public void setModificationTime(Date modificationTime) { + this.modificationTime = modificationTime; + } + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraCollaborationStorePluginImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraCollaborationStorePluginImpl.java index 90fd3366fe..f9b65224e0 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraCollaborationStorePluginImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraCollaborationStorePluginImpl.java @@ -21,97 +21,302 @@ import com.amdocs.zusammen.commons.health.data.HealthStatus; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.Namespace; import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.Space; +import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.ItemVersion; import com.amdocs.zusammen.datatypes.item.ItemVersionData; -import com.amdocs.zusammen.datatypes.itemversion.ItemVersionHistory; +import com.amdocs.zusammen.datatypes.item.ItemVersionDataConflict; +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus; +import com.amdocs.zusammen.datatypes.item.Resolution; +import com.amdocs.zusammen.datatypes.itemversion.ItemVersionRevisions; +import com.amdocs.zusammen.datatypes.itemversion.Revision; import com.amdocs.zusammen.datatypes.itemversion.Tag; +import com.amdocs.zusammen.datatypes.response.ErrorCode; +import com.amdocs.zusammen.datatypes.response.Module; import com.amdocs.zusammen.datatypes.response.Response; +import com.amdocs.zusammen.datatypes.response.ReturnCode; import com.amdocs.zusammen.datatypes.response.ZusammenException; import com.amdocs.zusammen.sdk.collaboration.CollaborationStore; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElement; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementChange; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationElementConflict; +import com.amdocs.zusammen.sdk.collaboration.types.CollaborationItemVersionConflict; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeChange; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationMergeResult; import com.amdocs.zusammen.sdk.collaboration.types.CollaborationPublishResult; -import org.openecomp.core.zusammen.plugin.collaboration.ElementCollaborationStore; -import org.openecomp.core.zusammen.plugin.collaboration.VersionCollaborationStore; +import com.amdocs.zusammen.sdk.types.ElementConflictDescriptor; +import com.amdocs.zusammen.sdk.types.ElementDescriptor; +import org.openecomp.core.zusammen.plugin.ZusammenPluginUtil; +import org.openecomp.core.zusammen.plugin.collaboration.CommitStagingService; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPrivateStore; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPublicStore; +import org.openecomp.core.zusammen.plugin.collaboration.ElementStageStore; +import org.openecomp.core.zusammen.plugin.collaboration.PublishService; +import org.openecomp.core.zusammen.plugin.collaboration.RevertService; +import org.openecomp.core.zusammen.plugin.collaboration.SyncService; +import org.openecomp.core.zusammen.plugin.collaboration.VersionPrivateStore; +import org.openecomp.core.zusammen.plugin.collaboration.VersionPublicStore; +import org.openecomp.core.zusammen.plugin.collaboration.VersionStageStore; +import org.openecomp.core.zusammen.plugin.collaboration.impl.ElementPrivateStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.ElementPublicStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.ElementStageStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.VersionPrivateStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.VersionPublicStoreImpl; +import org.openecomp.core.zusammen.plugin.collaboration.impl.VersionStageStoreImpl; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.openecomp.core.zusammen.plugin.dao.types.SynchronizationStateEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionDataElement; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static com.amdocs.zusammen.datatypes.item.SynchronizationStatus.MERGING; +import static com.amdocs.zusammen.datatypes.item.SynchronizationStatus.OUT_OF_SYNC; +import static com.amdocs.zusammen.datatypes.item.SynchronizationStatus.UP_TO_DATE; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginConstants.ROOT_ELEMENTS_PARENT_ID; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToCollaborationElement; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToElementChange; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToElementDescriptor; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToElementEntity; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToItemVersion; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToVersionData; +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToVersionEntity; public class CassandraCollaborationStorePluginImpl implements CollaborationStore { + // TODO: 8/15/2017 inject + + private VersionPrivateStore versionPrivateStore = new VersionPrivateStoreImpl(); + private VersionPublicStore versionPublicStore = new VersionPublicStoreImpl(); + private VersionStageStore versionStageStore = new VersionStageStoreImpl(); + + private ElementPrivateStore elementPrivateStore = new ElementPrivateStoreImpl(); + private ElementPublicStore elementPublicStore = new ElementPublicStoreImpl(); + private ElementStageStore elementStageStore = new ElementStageStoreImpl(); - private VersionCollaborationStore versionCollaborationStore = new VersionCollaborationStore(); - private ElementCollaborationStore elementCollaborationStore = new ElementCollaborationStore(); + // TODO: 9/4/2017 + private CommitStagingService commitStagingService = + new CommitStagingService(versionPrivateStore, versionStageStore, elementPrivateStore, + elementStageStore); + private PublishService publishService = + new PublishService(versionPublicStore, versionPrivateStore, elementPublicStore, + elementPrivateStore); + private SyncService syncService = + new SyncService(versionPublicStore, versionPrivateStore, versionStageStore, + elementPublicStore, elementPrivateStore, elementStageStore); + + private RevertService revertService = + new RevertService(elementPublicStore, elementPrivateStore); @Override - public Response<Void> createItem(SessionContext context, Id id, Info info) { + public Response<Void> createItem(SessionContext context, Id itemId, Info info) { // done by state store return new Response(Void.TYPE); } @Override - public Response<Void> deleteItem(SessionContext context, Id id) { + public Response<Void> deleteItem(SessionContext context, Id itemId) { // done by state store return new Response(Void.TYPE); } @Override - public Response<Void> createItemVersion(SessionContext context, Id itemId, Id versionId, Id id2, - ItemVersionData itemVersionData) { - // done by state store + public Response<Void> createItemVersion(SessionContext context, Id itemId, Id baseVersionId, + Id versionId, ItemVersionData itemVersionData) { + Date creationTime = new Date(); + versionPrivateStore.create(context, itemId, + convertToVersionEntity(versionId, baseVersionId, creationTime, creationTime)); + + ElementContext elementContext = new ElementContext(itemId, versionId); + VersionDataElement versionData = new VersionDataElement(itemVersionData); + + if (baseVersionId == null) { + elementPrivateStore.create(context, elementContext, versionData); + } else { + copyElements(context, new ElementContext(itemId, baseVersionId), elementContext); + elementPrivateStore.update(context, elementContext, versionData); + } + return new Response(Void.TYPE); } @Override public Response<Void> updateItemVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData) { - // done by state store + + if (elementPrivateStore.update(context, new ElementContext(itemId, versionId), + new VersionDataElement(itemVersionData))) { + + VersionEntity version = new VersionEntity(versionId); + version.setModificationTime(new Date()); + versionPrivateStore.update(context, itemId, version); + } + return new Response(Void.TYPE); } @Override public Response<Void> deleteItemVersion(SessionContext context, Id itemId, Id versionId) { - // done by state store + elementPrivateStore + .delete(context, new ElementContext(itemId, versionId), new VersionDataElement()); + + versionPrivateStore.delete(context, itemId, new VersionEntity(versionId)); return new Response(Void.TYPE); } @Override - public Response<Void> tagItemVersion(SessionContext context, Id itemId, Id versionId, Id changeId, + public Response<ItemVersionStatus> getItemVersionStatus(SessionContext context, Id itemId, + Id versionId) { + if (versionStageStore.get(context, itemId, new VersionEntity(versionId)).isPresent()) { + return new Response<>(new ItemVersionStatus(MERGING, true)); + } + + Optional<SynchronizationStateEntity> publicSyncState = + versionPublicStore.getSynchronizationState(context, itemId, versionId); + + if (!publicSyncState.isPresent()) { + return new Response<>(new ItemVersionStatus(UP_TO_DATE, true)); + } + + SynchronizationStateEntity privateSyncState = + versionPrivateStore.getSynchronizationState(context, itemId, versionId) + // TODO: 7/18/2017 ? + .orElseThrow(() -> new IllegalStateException("private version must exist")); + + return new Response<>(new ItemVersionStatus( + privateSyncState.getPublishTime().equals(publicSyncState.get().getPublishTime()) + ? UP_TO_DATE + : OUT_OF_SYNC, + privateSyncState.isDirty())); + } + + @Override + public Response<Void> tagItemVersion(SessionContext context, Id itemId, Id versionId, + Id revisionId, Tag tag) { - versionCollaborationStore.tagItemVersion(context, itemId, versionId, changeId, tag); + /* if (revisionId != null) { + throw new UnsupportedOperationException( + "In this plugin implementation tag is supported only on versionId"); + } + + copyElements(context, + new ElementContext(itemId, versionId), + new ElementContext(itemId, versionId, tag.getName()));*/ + return new Response(Void.TYPE); } @Override public Response<CollaborationPublishResult> publishItemVersion(SessionContext context, Id itemId, Id versionId, - String s) { - throw new UnsupportedOperationException("publishItemVersion"); + String message) { + try { + return new Response<>(publishService.publish(context, itemId, versionId, message)); + } catch (ZusammenException ze) { + return new Response<>( + new ReturnCode(ErrorCode.CL_ITEM_VERSION_PUBLISH, Module.ZCSP, null, ze.getReturnCode())); + } + } + + @Override + public Response<CollaborationMergeResult> syncItemVersion(SessionContext context, Id itemId, + Id versionId) { + CollaborationMergeResult result = syncService.sync(context, itemId, versionId, false); + commitStagingService.commitStaging(context, itemId, versionId); + + return new Response<>(result); } @Override - public Response<CollaborationMergeResult> syncItemVersion(SessionContext context, Id id, - Id id1) { - throw new UnsupportedOperationException("syncItemVersion"); + public Response<CollaborationMergeResult> forceSyncItemVersion(SessionContext context, Id itemId, + Id versionId) { + CollaborationMergeResult result = syncService.sync(context, itemId, versionId, true); + commitStagingService.commitStaging(context, itemId, versionId); + + return new Response<>(result); } @Override - public Response<CollaborationMergeResult> mergeItemVersion(SessionContext context, Id id, - Id id1, Id id2) { + public Response<CollaborationMergeResult> mergeItemVersion(SessionContext context, Id itemId, + Id versionId, Id sourceVersionId) { throw new UnsupportedOperationException("mergeItemVersion"); } @Override - public Response<ItemVersionHistory> listItemVersionHistory(SessionContext context, Id id, - Id id1) { - throw new UnsupportedOperationException("listItemVersionHistory"); + public Response<CollaborationItemVersionConflict> getItemVersionConflict(SessionContext context, + Id itemId, + Id versionId) { + ElementContext elementContext = new ElementContext(itemId, versionId, Id.ZERO); + + Collection<StageEntity<ElementEntity>> conflictedStagedElementDescriptors = + elementStageStore.listConflictedDescriptors(context, elementContext); + + CollaborationItemVersionConflict result = new CollaborationItemVersionConflict(); + for (StageEntity<ElementEntity> stagedElementDescriptor : conflictedStagedElementDescriptors) { + if (ROOT_ELEMENTS_PARENT_ID.equals(stagedElementDescriptor.getEntity().getId())) { + result.setVersionDataConflict( + getVersionDataConflict(context, elementContext, stagedElementDescriptor)); + } else { + result.getElementConflictDescriptors() + .add(getElementConflictDescriptor(context, elementContext, stagedElementDescriptor)); + } + } + return new Response<>(result); + } + + @Override + public Response<ItemVersionRevisions> listItemVersionRevisions(SessionContext context, Id itemId, + Id versionId) { + return new Response<>(versionPublicStore.listItemVersionRevisions(context, itemId, versionId)); } @Override - public Response<CollaborationMergeChange> resetItemVersionHistory(SessionContext context, - Id itemId, Id versionId, - String changeRef) { - return new Response<>(versionCollaborationStore.resetItemVersionHistory(context, itemId, versionId, changeRef)); + public Response<Revision> getItemVersionRevision(SessionContext context, Id itemId, Id versionId, + Id revisionId) { + throw new UnsupportedOperationException( + "get revision is not supported in the current cassandra plugin"); + } + + @Override + public Response<CollaborationMergeChange> resetItemVersionRevision(SessionContext context, + Id itemId, Id versionId, + Id revisionId) { + throw new UnsupportedOperationException("resetItemVersionRevision function not supported"); + + } + + @Override + public Response<CollaborationMergeChange> revertItemVersionRevision(SessionContext context, + Id itemId, Id versionId, + Id revisionId) { + Optional<ItemVersion> itemVersion = getItemVersion(context, itemId, versionId, revisionId); + if (!itemVersion.isPresent()) { + throw new RuntimeException(String + .format("Item %s, version %s: Cannot revert to revision %s since it is not found", + itemId, versionId, revisionId)); + } + + // TODO: 12/4/2017 force sync is done in order to clear dirty element on private + // this is temp solution that should be fixed. + forceSyncItemVersion(context, itemId, versionId); + + //updateItemVersion(context, itemId, versionId, itemVersion.get().getData()); + revertService.revert(context, itemId, versionId, revisionId); + + return new Response<>(new CollaborationMergeChange()); + } + + + @Override + public Response<Void> commitElements(SessionContext context, Id itemId, Id versionId, String s) { + // not needed + return new Response(Void.TYPE); } @Override @@ -119,52 +324,198 @@ public class CassandraCollaborationStorePluginImpl implements CollaborationStore ElementContext elementContext, Namespace namespace, Id elementId) { - return new Response<>( - elementCollaborationStore.listElements(context, elementContext, elementId)); + return new Response<>(elementPrivateStore.listSubs(context, elementContext, elementId).stream() + .map(elementEntity -> convertToCollaborationElement(elementContext, elementEntity)) + .collect(Collectors.toList())); } @Override public Response<CollaborationElement> getElement(SessionContext context, ElementContext elementContext, Namespace namespace, Id elementId) { - return new Response<>(elementCollaborationStore.getElement(context, elementContext, elementId)); + return new Response<>(elementPrivateStore.get(context, elementContext, elementId) + .map(elementEntity -> convertToCollaborationElement(elementContext, elementEntity)) + .orElse(null)); + } + + @Override + public Response<CollaborationElementConflict> getElementConflict(SessionContext context, + ElementContext elementContext, + Namespace namespace, + Id elementId) { + Optional<StageEntity<ElementEntity>> conflictedStagedElement = + elementStageStore + .getConflicted(context, elementContext, new ElementEntity(elementId)); + + return new Response<>(conflictedStagedElement + .map(stagedElement -> getElementConflict(context, elementContext, stagedElement)) + .orElse(null)); } @Override public Response<Void> createElement(SessionContext context, CollaborationElement element) { - elementCollaborationStore.createElement(context, element); + elementPrivateStore.create(context, + new ElementContext(element.getItemId(), element.getVersionId()), + convertToElementEntity(element)); return new Response(Void.TYPE); } @Override public Response<Void> updateElement(SessionContext context, CollaborationElement element) { - elementCollaborationStore.updateElement(context, element); + elementPrivateStore.update(context, + new ElementContext(element.getItemId(), element.getVersionId()), + convertToElementEntity(element)); return new Response(Void.TYPE); } @Override public Response<Void> deleteElement(SessionContext context, CollaborationElement element) { - elementCollaborationStore.deleteElement(context, element); + elementPrivateStore + .delete(context, new ElementContext(element.getItemId(), element.getVersionId()), + convertToElementEntity(element)); + return new Response(Void.TYPE); } @Override - public Response<Void> commitElements(SessionContext context, Id itemId, Id versionId, String s) { - // not needed - return new Response(Void.TYPE); + public Response<CollaborationMergeResult> resolveElementConflict(SessionContext context, + CollaborationElement element, + Resolution resolution) { + ElementContext elementContext = new ElementContext(element.getItemId(), element.getVersionId()); + elementStageStore + .resolveConflict(context, elementContext, convertToElementEntity(element), resolution); + commitStagingService.commitStaging(context, element.getItemId(), element.getVersionId()); + + return new Response<>(new CollaborationMergeResult()); } @Override - public Response<HealthInfo> checkHealth(SessionContext sessionContext) throws ZusammenException { + public Response<ItemVersion> getItemVersion(SessionContext context, Space space, Id itemId, + Id versionId, Id revisionId) { + return new Response<>(getItemVersion(context, itemId, versionId, revisionId).orElse(null)); + } - boolean health = elementCollaborationStore.checkHealth(sessionContext); - HealthInfo healthInfo ; - if (health){ - healthInfo = new HealthInfo("Collaboration", HealthStatus.UP,""); - } else { - healthInfo = new HealthInfo("Collaboration", HealthStatus.DOWN,"No Schema Available"); + @Override + public Response<HealthInfo> checkHealth(SessionContext context) throws ZusammenException { + HealthInfo healthInfo = versionPublicStore.checkHealth(context) + ? new HealthInfo(Module.ZCSP.getDescription(), HealthStatus.UP, "") + : new HealthInfo(Module.ZCSP.getDescription(), HealthStatus.DOWN, "No Schema Available"); + + return new Response<>(healthInfo); + } + + private Optional<ItemVersion> getItemVersion(SessionContext context, Id itemId, Id versionId, + Id revisionId) { + // since revisions are kept only on public - get from there + Optional<VersionEntity> versionEntity = versionPublicStore.get(context, itemId, versionId); + if (!versionEntity.isPresent()) { + return Optional.empty(); + } + + return elementPublicStore + .getDescriptor(context, new ElementContext(itemId, versionId, revisionId), + ROOT_ELEMENTS_PARENT_ID) + .map(ZusammenPluginUtil::convertToVersionData) + .map(itemVersionData -> convertToItemVersion(versionEntity.get(), itemVersionData)); + } + + private List<ElementEntity> listVersionElements(SessionContext context, + ElementContext elementContext) { + return elementPrivateStore.listIds(context, elementContext).entrySet().stream() // TODO: + // 9/5/2017 parallel + .map(entry -> elementPrivateStore.get(context, elementContext, entry.getKey()).get()) + .collect(Collectors.toList()); + } + + private void copyElements(SessionContext context, + ElementContext sourceContext, ElementContext targetContext) { + listVersionElements(context, sourceContext).forEach(element -> { + // publishTime copied as is and dirty is off + Date publishTime = + elementPrivateStore.getSynchronizationState(context, sourceContext, element.getId()) + .get().getPublishTime(); + elementPrivateStore.commitStagedCreate(context, targetContext, element, publishTime); + }); + } + + private ItemVersionDataConflict getVersionDataConflict(SessionContext context, + ElementContext elementContext, + StageEntity<ElementEntity> stagedElementDescriptor) { + ItemVersionDataConflict versionConflict = new ItemVersionDataConflict(); + versionConflict.setRemoteData(convertToVersionData(stagedElementDescriptor.getEntity())); + if (stagedElementDescriptor.getAction() == Action.UPDATE) { + versionConflict.setLocalData(getPrivateVersionData(context, elementContext)); } - return new Response<HealthInfo>(healthInfo); + return versionConflict; + } + private ItemVersionData getPrivateVersionData(SessionContext context, + ElementContext elementContext) { + return elementPrivateStore.getDescriptor(context, elementContext, ROOT_ELEMENTS_PARENT_ID) + .map(ZusammenPluginUtil::convertToVersionData) + .orElseThrow(() -> new IllegalStateException("Version must have data")); + } + + private ElementConflictDescriptor getElementConflictDescriptor(SessionContext context, + ElementContext elementContext, + StageEntity<ElementEntity> stagedElementDescriptor) { + ElementDescriptor elementDescriptorFromStage = + convertToElementDescriptor(elementContext, (stagedElementDescriptor.getEntity())); + + ElementConflictDescriptor conflictDescriptor = new ElementConflictDescriptor(); + switch (stagedElementDescriptor.getAction()) { + case CREATE: + conflictDescriptor.setRemoteElementDescriptor(elementDescriptorFromStage); + break; + case UPDATE: + conflictDescriptor.setRemoteElementDescriptor(elementDescriptorFromStage); + conflictDescriptor.setLocalElementDescriptor(convertToElementDescriptor(elementContext, + elementPrivateStore + .getDescriptor(context, elementContext, stagedElementDescriptor.getEntity().getId()) + .orElse(null)));// updated on public while deleted from private + break; + case DELETE: + conflictDescriptor.setLocalElementDescriptor(elementDescriptorFromStage); + break; + default: + break; + } + return conflictDescriptor; + } + + private void addElementsToChangedElements(ElementContext elementContext, + Collection<ElementEntity> elements, + Collection<CollaborationElementChange> changedElements, + Action action) { + elements.stream() + .map(elementEntity -> convertToElementChange(elementContext, elementEntity, action)) + .forEach(changedElements::add); + } + + private CollaborationElementConflict getElementConflict(SessionContext context, + ElementContext entityContext, + StageEntity<ElementEntity> stagedElement) { + CollaborationElement elementFromStage = + convertToCollaborationElement(entityContext, (stagedElement.getEntity())); + + CollaborationElementConflict conflict = new CollaborationElementConflict(); + switch (stagedElement.getAction()) { + case CREATE: + conflict.setRemoteElement(elementFromStage); + break; + case UPDATE: + conflict.setRemoteElement(elementFromStage); + conflict.setLocalElement( + elementPrivateStore.get(context, entityContext, stagedElement.getEntity().getId()) + .map(element -> convertToCollaborationElement(entityContext, element)) + .orElse(null));// updated on public while deleted from private + break; + case DELETE: + conflict.setLocalElement(elementFromStage); + break; + default: + break; + } + return conflict; } }
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraStateStorePluginImpl.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraStateStorePluginImpl.java index b4767b2872..3ed668e331 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraStateStorePluginImpl.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/java/org/openecomp/core/zusammen/plugin/main/CassandraStateStorePluginImpl.java @@ -17,18 +17,87 @@ package org.openecomp.core.zusammen.plugin.main; +import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.Space; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; import com.amdocs.zusammen.datatypes.response.Response; import com.amdocs.zusammen.plugin.statestore.cassandra.StateStoreImpl; import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; import com.amdocs.zusammen.sdk.state.types.StateElement; +import org.openecomp.core.zusammen.plugin.ZusammenPluginUtil; +import org.openecomp.core.zusammen.plugin.collaboration.ElementPrivateStore; +import org.openecomp.core.zusammen.plugin.collaboration.impl.ElementPrivateStoreImpl; +import org.openecomp.core.zusammen.plugin.dao.ElementRepository; import org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory; +import org.openecomp.core.zusammen.plugin.dao.VersionDao; +import org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory; import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.VersionDataElement; +import org.openecomp.core.zusammen.plugin.dao.types.VersionEntity; +import java.util.Collection; +import java.util.Date; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.convertToItemVersion; import static org.openecomp.core.zusammen.plugin.ZusammenPluginUtil.getSpaceName; public class CassandraStateStorePluginImpl extends StateStoreImpl { + private ElementPrivateStore elementPrivateStore = new ElementPrivateStoreImpl(); + + @Override + public Response<Collection<ItemVersion>> listItemVersions(SessionContext context, Space space, + Id itemId) { + String spaceName = getSpaceName(context, space); + return new Response<>(getVersionDao(context).list(context, spaceName, itemId).stream() + .map(versionEntity -> getItemVersion(context, spaceName, itemId, versionEntity)) + .collect(Collectors.toList())); + } + + @Override + public Response<Boolean> isItemVersionExist(SessionContext context, Space space, Id itemId, + Id versionId) { + return new Response<>( + getVersionDao(context).get(context, getSpaceName(context, space), itemId, versionId) + .isPresent()); + } + + @Override + public Response<ItemVersion> getItemVersion(SessionContext context, Space space, Id itemId, + Id versionId) { + String spaceName = getSpaceName(context, space); + return new Response<>(getVersionDao(context).get(context, spaceName, itemId, versionId) + .map(versionEntity -> getItemVersion(context, spaceName, itemId, versionEntity)) + .orElse(null)); + } + + @Override + public Response<Void> createItemVersion(SessionContext context, Space space, Id itemId, + Id baseVersionId, Id versionId, ItemVersionData data, + Date creationTime) { + // done by collaboration store + return new Response(Void.TYPE); + } + + @Override + public Response<Void> updateItemVersion(SessionContext context, Space space, Id itemId, + Id versionId, ItemVersionData data, + Date modificationTime) { + // done by collaboration store + return new Response(Void.TYPE); + } + + @Override + public Response<Void> deleteItemVersion(SessionContext context, Space space, Id itemId, + Id versionId) { + // done by collaboration store + return new Response(Void.TYPE); + } + @Override public Response<Void> createElement(SessionContext context, StateElement element) { ElementEntity elementEntity = new ElementEntity(element.getId()); @@ -37,8 +106,7 @@ public class CassandraStateStorePluginImpl extends StateStoreImpl { ElementRepositoryFactory.getInstance().createInterface(context) .createNamespace(context, new ElementEntityContext(getSpaceName(context, element.getSpace()), - element.getItemId(), element.getVersionId()), - elementEntity); + element.getItemId(), element.getVersionId()), elementEntity); // create element is done by collaboration store return new Response(Void.TYPE); } @@ -55,4 +123,46 @@ public class CassandraStateStorePluginImpl extends StateStoreImpl { return new Response(Void.TYPE); } + @Override + public Response<Collection<StateElement>> listElements(SessionContext context, + ElementContext elementContext, + Id elementId) { + return new Response(elementPrivateStore.listSubs(context, elementContext, elementId).stream() + .map(elementEntity -> ZusammenPluginUtil.getStateElement(elementContext, elementEntity)) + .collect(Collectors.toList())); + + } + + @Override + public Response<StateElement> getElement(SessionContext context, ElementContext elementContext, + Id elementId) { + + return new Response(elementPrivateStore.get(context, elementContext, elementId) + .map(elementEntity -> ZusammenPluginUtil + .getStateElement(elementContext, elementEntity)) + .orElse + (null)); + + + } + + private ItemVersion getItemVersion(SessionContext context, String spaceName, Id itemId, + VersionEntity versionEntity) { + + ItemVersionData itemVersionData = getElementRepository(context) + .get(context, new ElementEntityContext(spaceName, itemId, versionEntity.getId(), null), + new VersionDataElement()) + .map(ZusammenPluginUtil::convertToVersionData) + .orElseThrow(() -> new IllegalStateException("Version must have data")); + + return convertToItemVersion(versionEntity, itemVersionData); + } + + protected VersionDao getVersionDao(SessionContext context) { + return VersionDaoFactory.getInstance().createInterface(context); + } + + protected ElementRepository getElementRepository(SessionContext context) { + return ElementRepositoryFactory.getInstance().createInterface(context); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/resources/factoryConfiguration.json index cd1e293b4b..841e005709 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/resources/factoryConfiguration.json +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/main/resources/factoryConfiguration.json @@ -1,3 +1,8 @@ { - "org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.CassandraElementRepositoryFactory" + "org.openecomp.core.zusammen.plugin.dao.VersionDaoFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.VersionDaoFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.ElementRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.ElementRepositoryFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.VersionSynchronizationStateRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.VersionSynchronizationStateRepositoryFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.ElementSynchronizationStateRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.ElementSynchronizationStateRepositoryFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.VersionStageRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.VersionStageRepositoryFactoryImpl", + "org.openecomp.core.zusammen.plugin.dao.ElementStageRepositoryFactory": "org.openecomp.core.zusammen.plugin.dao.impl.cassandra.ElementStageRepositoryFactoryImpl" }
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/TestUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/TestUtils.java new file mode 100644 index 0000000000..79e918c808 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/TestUtils.java @@ -0,0 +1,64 @@ +/* + * Copyright © 2016-2017 European Support Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openecomp.core.zusammen.plugin.collaboration; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.UserInfo; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.Relation; + +import java.util.Arrays; + +public class TestUtils { + + public static SessionContext createSessionContext(UserInfo user, String tenant) { + SessionContext context = new SessionContext(); + context.setUser(user); + context.setTenant(tenant); + return context; + } + + public static ElementContext createElementContext(Id itemId, Id versionId) { + ElementContext elementContext = new ElementContext(); + elementContext.setItemId(itemId); + elementContext.setVersionId(versionId); + return elementContext; + } + + public static Info createInfo(String value) { + Info info = new Info(); + info.setName(value); + info.addProperty("Name", "name_" + value); + info.addProperty("Desc", "desc_" + value); + return info; + } + + public static ItemVersion createItemVersion(Id id, Id baseId, String name, boolean dirty) { + ItemVersion version = new ItemVersion(); + version.setId(id); + version.setBaseId(baseId); + ItemVersionData data = new ItemVersionData(); + data.setInfo(TestUtils.createInfo(name)); + data.setRelations(Arrays.asList(new Relation(), new Relation())); + version.setData(data); + return version; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStoreTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStoreTest.java new file mode 100644 index 0000000000..4c4621e98b --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/VersionCollaborationStoreTest.java @@ -0,0 +1,237 @@ +package org.openecomp.core.zusammen.plugin.collaboration; + +public class VersionCollaborationStoreTest {/* + private static final String TENANT = "test"; + private static final String USER = "ItemStateStoreTest_user"; + private static final SessionContext context = + TestUtils.createSessionContext(new UserInfo(USER), TENANT); + + @Mock + private VersionDao versionDaoMock; + @Mock + private ElementStore elementCollaborationStore; + @Spy + @InjectMocks + private VersionStore versionCollaborationStore; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + when(versionCollaborationStore.getVersionDao(anyObject())).thenReturn(versionDaoMock); + } +*//* + @Test + public void testListPrivateItemVersions() throws Exception { + testListItemVersions(Space.PRIVATE, USER); + } + + @Test + public void testListPublicItemVersions() throws Exception { + testListItemVersions(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + @Test + public void testIsPrivateItemVersionExist() throws Exception { + testIsItemVersionExist(Space.PRIVATE, USER); + } + + @Test + public void testIsPublicItemVersionExist() throws Exception { + testIsItemVersionExist(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + @Test + public void testIsItemVersionExistWhenNot() throws Exception { + Id itemId = new Id(); + Id versionId = new Id(); + doReturn(Optional.empty()).when(versionDaoMock).get(context, USER, itemId, versionId); + + boolean itemExist = + versionCollaborationStore.isItemVersionExist(context, Space.PRIVATE, itemId, versionId); + Assert.assertFalse(itemExist); + } + + @Test + public void testGetPrivateItemVersion() throws Exception { + testGetItemVersion(Space.PRIVATE, USER); + } + + @Test + public void testGetPublicItemVersion() throws Exception { + testGetItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + + @Test + public void testGetNonExistingItemVersion() throws Exception { + Id itemId = new Id(); + Id versionId = new Id(); + doReturn(Optional.empty()).when(versionDaoMock).get(context, USER, itemId, versionId); + + ItemVersion itemVersion = + versionCollaborationStore.getItemVersion(context, Space.PRIVATE, itemId, versionId); + Assert.assertNull(itemVersion); + }*//* + + @Test + public void testCreatePrivateItemVersion() throws Exception { + testCreateItemVersion(Space.PRIVATE, USER, null); + } + + @Test + public void testCreatePrivateItemVersionBasedOn() throws Exception { + testCreateItemVersion(Space.PRIVATE, USER, new Id()); + } + + @Test + public void testCreatePublicItemVersion() throws Exception { + testCreateItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE, null); + } + + @Test + public void testCreatePublicItemVersionBasedOn() throws Exception { + testCreateItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE, new Id()); + } + + @Test + public void testUpdatePrivateItemVersion() throws Exception { + testUpdateItemVersion(Space.PRIVATE, USER); + } + + @Test + public void testUpdatePublicItemVersion() throws Exception { + testUpdateItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + @Test + public void testDeletePrivateItemVersion() throws Exception { + testDeleteItemVersion(Space.PRIVATE, USER); + } + + @Test + public void testDeletePublicItemVersion() throws Exception { + testDeleteItemVersion(Space.PUBLIC, ZusammenPluginConstants.PUBLIC_SPACE); + } + + @Test + public void testPublishItemVersionWhenNotDirty() throws Exception { + Id itemId = new Id(); + ItemVersion version = TestUtils.createItemVersion(new Id(), null, "v1", false); + doReturn(Optional.of(version)).when(versionDaoMock).get(context, USER, itemId, version.getId()); + + versionCollaborationStore.publishItemVersion(context, itemId, version.getId(), "message"); + + } +*//* + private void testIsItemVersionExist(Space space, String spaceName) { + Id itemId = new Id(); + ItemVersion retrievedVersion = TestUtils.createItemVersion(new Id(), null, "v1"); + doReturn(Optional.of(retrievedVersion)).when(versionDaoMock) + .get(context, spaceName, itemId, retrievedVersion.getId()); + + boolean itemExist = + versionCollaborationStore + .isItemVersionExist(context, space, itemId, retrievedVersion.getId()); + Assert.assertTrue(itemExist); + } + + private void testGetItemVersion(Space space, String spaceName) throws Exception { + Id itemId = new Id(); + ItemVersion retrievedVersion = TestUtils.createItemVersion(new Id(), null, "v1"); + doReturn(Optional.of(retrievedVersion)).when(versionDaoMock) + .get(context, spaceName, itemId, retrievedVersion.getId()); + + ItemVersion itemVersion = + versionCollaborationStore.getItemVersion(context, space, itemId, retrievedVersion.getId()); + Assert.assertEquals(itemVersion, retrievedVersion); + } + + private void testListItemVersions(Space space, String spaceName) { + Id itemId = new Id(); + ItemVersion v1 = TestUtils.createItemVersion(new Id(), null, "v1"); + ItemVersion v2 = TestUtils.createItemVersion(new Id(), v1.getId(), "v2"); + ItemVersion v3 = TestUtils.createItemVersion(new Id(), v2.getId(), "v3"); + List<ItemVersion> retrievedVersions = Arrays.asList(v1, v2, v3); + doReturn(retrievedVersions).when(versionDaoMock).list(context, spaceName, itemId); + + Collection<ItemVersion> itemVersions = + versionCollaborationStore.listItemVersions(context, space, itemId); + Assert.assertEquals(itemVersions, retrievedVersions); + }*//* + + private void testCreateItemVersion(Space space, String spaceName, Id baseId) { + Id itemId = new Id(); + ItemVersion v1 = TestUtils.createItemVersion(new Id(), baseId, "v1", false); + List<ElementEntity> baseVersionElements = mockVersionElements(spaceName, itemId, baseId); + + ArgumentCaptor<ItemVersion> versionCaptor = ArgumentCaptor.forClass(ItemVersion.class); + + Date creationTime = new Date(); + versionCollaborationStore + .createItemVersion(context, space, itemId, baseId, v1.getId(), v1.getData(), creationTime); + + verify(versionDaoMock).create(eq(context), eq(spaceName), eq(itemId), versionCaptor.capture()); + //baseId, v1.getId(),v1.getData(), creationTime); + + ItemVersion capturedVersion = versionCaptor.getValue(); + Assert.assertEquals(baseId, capturedVersion.getBaseId()); + Assert.assertEquals(v1.getId(), capturedVersion.getId()); + Assert.assertEquals(v1.getData(), capturedVersion.getData()); + Assert.assertEquals(creationTime, capturedVersion.getCreationTime()); +*//* verify(versionDaoMock) + .create(anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), anyObject(), + anyObject());*//* + +*//* if (baseId != null) { + baseVersionElements.forEach(element -> + verify(elementCollaborationStore).create(eq(context), + eq(new ElementEntityContext(spaceName, itemId, v1.getId())), + eq(element))); + } else { + verifyZeroInteractions(elementCollaborationStore); + }*//* + } + + private void testUpdateItemVersion(Space space, String spaceName) { + Id itemId = new Id(); + ItemVersion retrievedVersion = TestUtils.createItemVersion(new Id(), null, "v1", false); + doReturn(Optional.of(retrievedVersion)).when(versionDaoMock) + .get(context, spaceName, itemId, retrievedVersion.getId()); + + ItemVersionData updatedData = new ItemVersionData(); + updatedData.setInfo(TestUtils.createInfo("v1 updated")); + updatedData.setRelations( + Arrays.asList(new Relation(), new Relation(), new Relation(), new Relation())); + versionCollaborationStore.updateItemVersion( + context, space, itemId, retrievedVersion.getId(), updatedData, new Date()); + + *//*verify(versionDaoMock) + .update(context, spaceName, itemId, retrievedVersion.getId(), updatedData, modificationTime);*//* + verify(versionDaoMock) + .update(anyObject(), anyObject(), anyObject(), anyObject()); + + } + + private void testDeleteItemVersion(Space space, String spaceName) { + Id itemId = new Id(); + Id versionId = new Id(); + + List<ElementEntity> versionElements = mockVersionElements(spaceName, itemId, versionId); + versionCollaborationStore.deleteItemVersion(context, space, itemId, versionId); + +*//* versionElements.forEach(element -> + verify(elementCollaborationStore).delete(eq(context), + eq(new ElementEntityContext(spaceName, itemId, versionId)), + eq(element)));*//* + verify(versionDaoMock).delete(context, spaceName, itemId, versionId); + } + + private List<ElementEntity> mockVersionElements(String spaceName, Id itemId, Id versionId) { + ElementEntity elm1 = new ElementEntity(new Id()); + ElementEntity elm2 = new ElementEntity(new Id()); + List<ElementEntity> baseVersionElements = Arrays.asList(elm1, elm2); +*//* doReturn(baseVersionElements).when(elementCollaborationStore) + .list(eq(context), eq(new ElementEntityContext(spaceName, itemId, versionId)));*//* + return baseVersionElements; + }*/ +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImplTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImplTest.java new file mode 100644 index 0000000000..7f137b01b0 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-zusammen-lib/openecomp-zusammen-plugin/src/test/java/org/openecomp/core/zusammen/plugin/collaboration/impl/ElementStageStoreImplTest.java @@ -0,0 +1,167 @@ +package org.openecomp.core.zusammen.plugin.collaboration.impl; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.UserInfo; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Resolution; +import com.amdocs.zusammen.plugin.statestore.cassandra.dao.types.ElementEntityContext; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.core.zusammen.plugin.collaboration.TestUtils; +import org.openecomp.core.zusammen.plugin.dao.ElementStageRepository; +import org.openecomp.core.zusammen.plugin.dao.types.ElementEntity; +import org.openecomp.core.zusammen.plugin.dao.types.StageEntity; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Date; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.same; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class ElementStageStoreImplTest { + private static final UserInfo USER = new UserInfo("user"); + private static final SessionContext context = TestUtils.createSessionContext(USER, "test"); + private static final ElementContext elementContext = + TestUtils.createElementContext(new Id(), new Id()); + + @Mock + private ElementStageRepository elementStageRepositoryMock; + @Spy + private ElementStageStoreImpl elementStageStore; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + when(elementStageStore.getElementStageRepository(anyObject())) + .thenReturn(elementStageRepositoryMock); + } + + @Test + public void testListIds() throws Exception { + + } + + @Test + public void testGet() throws Exception { + + } + + @Test + public void testGetConflicted() throws Exception { + + } + + @Test + public void testHasConflicts() throws Exception { + + } + + @Test + public void testListConflictedDescriptors() throws Exception { + + } + + @Test + public void testCreate() throws Exception { + + } + + @Test + public void testDelete() throws Exception { + + } + + @Test + public void testResolveConflictWhenNotStaged() throws Exception { + doReturn(Optional.empty()) + .when(elementStageRepositoryMock).get(anyObject(), anyObject(), anyObject()); + elementStageStore + .resolveConflict(context, elementContext, new ElementEntity(new Id()), Resolution.YOURS); + } + + @Test + public void testResolveConflictWhenNotConflicted() throws Exception { + Id elementId = new Id(); + StageEntity<ElementEntity> stagedElement = + new StageEntity<>(new ElementEntity(elementId), new Date()); + doReturn(Optional.of(stagedElement)) + .when(elementStageRepositoryMock).get(anyObject(), anyObject(), anyObject()); + elementStageStore + .resolveConflict(context, elementContext, new ElementEntity(elementId), Resolution.YOURS); + } + + @Test + public void testResolveConflictByYours() throws Exception { + Id elementId = new Id(); + StageEntity<ElementEntity> stagedElement = + new StageEntity<>(new ElementEntity(elementId), new Date()); + stagedElement.setAction(Action.UPDATE); + stagedElement.setConflicted(true); + + doReturn(Optional.of(stagedElement)) + .when(elementStageRepositoryMock).get(anyObject(), anyObject(), anyObject()); + + elementStageStore + .resolveConflict(context, elementContext, new ElementEntity(elementId), Resolution.YOURS); + + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), + eq(new ElementEntityContext(USER.getUserName(), elementContext)), + same(stagedElement.getEntity()), same(Action.IGNORE)); + } + + @Test + public void testResolveConflictByYoursWithRelated() throws Exception { + Id elementId = new Id(); + StageEntity<ElementEntity> stagedElement = + new StageEntity<>(new ElementEntity(elementId), new Date()); + stagedElement.setAction(Action.UPDATE); + stagedElement.setConflicted(true); + ElementEntity relatedElement1 = new ElementEntity(new Id()); + ElementEntity relatedElement2 = new ElementEntity(new Id()); + ElementEntity relatedElement3 = new ElementEntity(new Id()); + Set<ElementEntity> relatedElements = new HashSet<>(); + relatedElements.add(relatedElement1); + relatedElements.add(relatedElement2); + relatedElements.add(relatedElement3); + stagedElement.setConflictDependents(relatedElements); + + doReturn(Optional.of(stagedElement)) + .when(elementStageRepositoryMock).get(anyObject(), anyObject(), anyObject()); + + elementStageStore + .resolveConflict(context, elementContext, new ElementEntity(elementId), Resolution.YOURS); + + ElementEntityContext elementEntityContext = + new ElementEntityContext(USER.getUserName(), elementContext); + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), eq(elementEntityContext), + same(stagedElement.getEntity()), same(Action.IGNORE)); + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), eq(elementEntityContext), + same(relatedElement1), same(Action.IGNORE)); + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), eq(elementEntityContext), + same(relatedElement2), same(Action.IGNORE)); + verify(elementStageRepositoryMock).markAsNotConflicted(same(context), eq(elementEntityContext), + same(relatedElement3), same(Action.IGNORE)); + } + + @Test + public void testResolveConflictByTheirs() throws Exception { + + } + + @Test + public void testResolveConflictByTheirsWithRelated() throws Exception { + + } + +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/pom.xml b/openecomp-be/lib/openecomp-core-lib/pom.xml index 3784593668..51faa10566 100644 --- a/openecomp-be/lib/openecomp-core-lib/pom.xml +++ b/openecomp-be/lib/openecomp-core-lib/pom.xml @@ -20,5 +20,6 @@ <module>/openecomp-utilities-lib</module> <module>/openecomp-config-lib</module> <module>/openecomp-zusammen-lib</module> + <module>/openecomp-session-lib</module> </modules> </project> diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/pom.xml b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/pom.xml index 2900785b55..fa3533fde9 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/pom.xml +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/pom.xml @@ -14,6 +14,23 @@ <dependencies> <dependency> + <groupId>org.openecomp.sdc.common</groupId> + <artifactId>openecomp-configuration-management-core</artifactId> + <version>${openecomp.sdc.common.version}</version> + <scope>runtime</scope> + <exclusions> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.openecomp.sdc.common</groupId> + <artifactId>openecomp-configuration-management-api</artifactId> + <version>${openecomp.sdc.common.version}</version> + </dependency> + <dependency> <groupId>org.openecomp.sdc.core</groupId> <artifactId>openecomp-facade-core</artifactId> <version>${project.version}</version> @@ -33,6 +50,11 @@ <artifactId>openecomp-sdc-versioning-api</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-core</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> </project> diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/api/HealingManager.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/api/HealingManager.java index 211d9a21b2..ca0a3c79d7 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/api/HealingManager.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/api/HealingManager.java @@ -20,16 +20,24 @@ package org.openecomp.sdc.healing.api; +import org.openecomp.sdc.datatypes.model.ItemType; import org.openecomp.sdc.healing.types.HealCode; +import org.openecomp.sdc.healing.types.HealerType; +import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Map; import java.util.Optional; /** * Created by Talio on 11/29/2016. */ public interface HealingManager { - Object heal(HealCode code, Map<String, Object> healParameters); - Optional<String> healAll(Map<String, Object> healParameters); + /** + * @return healed version, if healing was not performed - Optional.empty. + */ + Optional<Version> healItemVersion(String itemId, Version version, ItemType itemType, + boolean force); + + Object heal(String itemId, Version version, HealerType healerType, HealCode code, + ItemType itemType); } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/dao/HealingDao.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/dao/HealingDao.java new file mode 100644 index 0000000000..b766bd8d88 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/dao/HealingDao.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.healing.dao; + +import java.util.Optional; + +/** + * Created by ayalaben on 10/17/2017 + */ +public interface HealingDao { + + Optional<Boolean> getItemHealingFlag(String space, String itemId, String versionId); + + void setItemHealingFlag(boolean healingNeededFlag, String space, String itemId, String versionId); +} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/factory/HealingManagerFactory.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/factory/HealingManagerFactory.java index 8e8d633b42..5e375ee046 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/factory/HealingManagerFactory.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/factory/HealingManagerFactory.java @@ -20,9 +20,9 @@ package org.openecomp.sdc.healing.factory; -import org.openecomp.sdc.healing.api.HealingManager; import org.openecomp.core.factory.api.AbstractComponentFactory; import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.sdc.healing.api.HealingManager; /** * Created by Talio on 11/29/2016. diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/interfaces/Healer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/interfaces/Healer.java index eb2f9a74d2..38afd1342a 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/interfaces/Healer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/interfaces/Healer.java @@ -20,11 +20,11 @@ package org.openecomp.sdc.healing.interfaces; -import java.util.Map; +import org.openecomp.sdc.versioning.dao.types.Version; /** * Created by Talio on 11/29/2016. */ public interface Healer { - Object heal(Map<String, Object> healingParams) throws Exception; + Object heal(String itemId, Version version) throws Exception; } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/ConfigConstants.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/ConfigConstants.java new file mode 100644 index 0000000000..06301279a9 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/ConfigConstants.java @@ -0,0 +1,5 @@ +package org.openecomp.sdc.healing.types; + +public class ConfigConstants { + public static final String HEALING_NAMESPACE = "healing"; +} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java new file mode 100644 index 0000000000..3355a3cd92 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealerType.java @@ -0,0 +1,6 @@ +package org.openecomp.sdc.healing.types; + +public enum HealerType { + data, + structure +} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealingContext.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealingContext.java deleted file mode 100644 index 2ad143a0ec..0000000000 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealingContext.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.openecomp.sdc.healing.types; -import org.openecomp.sdc.versioning.dao.types.Version; - -/** - * Created by TALIO on 7/3/2017. - */ -public class HealingContext { - private String vspId; - private Version version; - private String user; - - public HealingContext(String vspId, Version version, String user) { - this.vspId = vspId; - this.version = version; - this.user = user; - } - - public String getVspId() { - return vspId; - } - - public void setVspId(String vspId) { - this.vspId = vspId; - } - - public Version getVersion() { - return version; - } - - public void setVersion(Version version) { - this.version = version; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } -} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/dao/impl/HealingDaoImpl.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/dao/impl/HealingDaoImpl.java new file mode 100644 index 0000000000..921f418118 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/dao/impl/HealingDaoImpl.java @@ -0,0 +1,46 @@ +package org.openecomp.sdc.healing.dao.impl; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; +import org.openecomp.sdc.healing.dao.HealingDao; + +import java.util.Optional; + +/** + * Created by ayalaben on 10/17/2017 + */ +public class HealingDaoImpl implements HealingDao { + + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static HealingAccessor accessor = + noSqlDb.getMappingManager().createAccessor(HealingAccessor.class); + + @Override + public Optional<Boolean> getItemHealingFlag(String space, String itemId, String versionId) { + ResultSet result = accessor.getItemHealingFlag(space, itemId, versionId); + return result.getAvailableWithoutFetching() < 1 + ? Optional.empty() + : Optional.of(result.one().getBool("healing_needed")); + } + + @Override + public void setItemHealingFlag(boolean healingNeededFlag, String space, String itemId, + String versionId) { + accessor.setItemHealingFlag(healingNeededFlag, space, itemId, versionId); + } + + + @Accessor + interface HealingAccessor { + + @Query("SELECT healing_needed FROM healing WHERE space=? AND item_id=? AND version_id=?") + ResultSet getItemHealingFlag(String space, String itemId, String versionId); + + @Query("UPDATE healing SET healing_needed=? WHERE space=? AND item_id=? AND version_id=?") + void setItemHealingFlag(boolean flag, String space, String itemId, String versionId); + + } +} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerFactoryImpl.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerFactoryImpl.java index 84aff4327d..5a283f954b 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerFactoryImpl.java @@ -21,15 +21,17 @@ package org.openecomp.sdc.healing.impl; import org.openecomp.sdc.healing.api.HealingManager; +import org.openecomp.sdc.healing.dao.impl.HealingDaoImpl; import org.openecomp.sdc.healing.factory.HealingManagerFactory; +import org.openecomp.sdc.versioning.VersioningManagerFactory; /** * Created by Talio on 11/29/2016. */ public class HealingManagerFactoryImpl extends HealingManagerFactory { - @Override public HealingManager createInterface() { - return new HealingManagerImpl(); + return new HealingManagerImpl( + VersioningManagerFactory.getInstance().createInterface(), new HealingDaoImpl()); } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerImpl.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerImpl.java index 1c895ffc6f..59c6732cab 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerImpl.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/impl/HealingManagerImpl.java @@ -24,34 +24,147 @@ import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.model.ItemType; import org.openecomp.sdc.healing.api.HealingManager; +import org.openecomp.sdc.healing.dao.HealingDao; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.healing.types.HealCode; +import org.openecomp.sdc.healing.types.HealerType; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.versioning.VersioningManager; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.VersionCreationMethod; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; +import java.util.Collection; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; /** * Created by Talio on 11/29/2016. */ public class HealingManagerImpl implements HealingManager { - private static String HEALING_CONF_FILE = "healingConfiguration.json"; - private static Map<String, String> healerCodeToImplClass = initHealers(); + + private static final String HEALERS_BY_ENTITY_TYPE_FILE = "entityHealingConfiguration.json"; + private static final String HEALING_USER_SUFFIX = "_healer"; + private static final String PUBLIC_USER = "public"; + + private HealingDao healingDao; + private VersioningManager versioningManager; + + public HealingManagerImpl(VersioningManager versioningManager, HealingDao healingDao) { + this.versioningManager = versioningManager; + this.healingDao = healingDao; + } + + @Override + public Optional<Version> healItemVersion(String itemId, Version version, ItemType itemType, + boolean force) { + String user = getUser(); + if (force || isPrivateHealingNeededByFlag(itemId, version.getId(), user)) { + version = versioningManager.get(itemId, version); + Version origVersion = version; + if (version.getStatus() == VersionStatus.Certified) { + Optional<Version> newVersion = createNewVersion(itemId, version); + if (!newVersion.isPresent()) { + // do NOT turn off flag here (in thought of saving version calculate performance next + // time) because maybe next time the next version will be available (due to deletion of + // the taken one) + return Optional.empty(); + } + version = newVersion.get(); + } + + doHeal(itemId, version, origVersion, itemType, user, force); + return Optional.of(version); + } + return Optional.empty(); + } + + private void doHeal(String itemId, Version version, Version origVersion, + ItemType itemType, String user, boolean force) { + Optional<String> privateFailureMessages = + healPrivate(itemId, version, origVersion, getItemHealers(itemType), user); + + Optional<String> publicFailureMessages = + force || origVersion.getStatus() == VersionStatus.Certified || + isPublicHealingNeededByFlag(itemId, origVersion.getId()) + ? healPublic(itemId, version, origVersion, getItemHealers(itemType), user) + : Optional.empty(); + + if (privateFailureMessages.isPresent() || publicFailureMessages.isPresent()) { + throw new RuntimeException( + publicFailureMessages.orElse("") + " " + privateFailureMessages.orElse("")); + } + } + + private Optional<String> healPrivate(String itemId, Version version, Version origVersion, + Map<String, Map<String, String>> itemHealers, String user) { + if (origVersion.getStatus() != VersionStatus.Certified) { + itemHealers.remove(HealerType.structure.name()); + } + + Optional<String> privateHealingFailureMessages = executeHealers(itemId, version, itemHealers); + markAsHealed(itemId, origVersion.getId(), user); + return privateHealingFailureMessages; + } + + private Optional<String> healPublic(String itemId, Version version, Version origVersion, + Map<String, Map<String, String>> itemHealers, String user) { + Optional<String> healingFailureMessages = origVersion.getStatus() == VersionStatus.Certified + ? Optional.empty() + : healPublic(itemId, version, itemHealers, user); + + markAsHealed(itemId, origVersion.getId(), PUBLIC_USER); + return healingFailureMessages; + } + + private Optional<String> healPublic(String itemId, Version version, + Map<String, Map<String, String>> itemHealers, String user) { + SessionContextProviderFactory.getInstance().createInterface() + .create(user + HEALING_USER_SUFFIX); + + versioningManager.sync(itemId, version); + + Optional<String> healingFailureMessages = executeHealers(itemId, version, itemHealers); + Version publicVersion = versioningManager.get(itemId, version); + + if (Objects.nonNull(publicVersion.getState()) && publicVersion.getState().isDirty()) { + versioningManager.publish(itemId, version, "Healing vsp"); + } + + SessionContextProviderFactory.getInstance().createInterface().create(user); + return healingFailureMessages; + } + + private Optional<Version> createNewVersion(String itemId, Version version) { + Version newVersion = new Version(); + newVersion.setBaseId(version.getId()); + try { + return Optional.of(versioningManager.create(itemId, newVersion, VersionCreationMethod.major)); + } catch (Exception e) { + return Optional.empty(); + } + } @Override - public Object heal(HealCode code, Map<String, Object> healParameters) { + public Object heal(String itemId, Version version, HealerType healerType, HealCode code, + ItemType itemType) { + String healerClassName = getItemHealers(itemType).get(healerType.name()).get(code.name()); ArrayList<String> healingFailureMessages = new ArrayList<>(); - Object result = - heal(healParameters, healerCodeToImplClass.get(code.name()), healingFailureMessages); + Object result = executeHealer(itemId, version, healerClassName, healingFailureMessages); if (!healingFailureMessages.isEmpty()) { throw new RuntimeException(CommonMethods.listToSeparatedString(healingFailureMessages, '\n')); @@ -59,46 +172,77 @@ public class HealingManagerImpl implements HealingManager { return result; } - @Override - public Optional<String> healAll(Map<String, Object> healParameters) { - ArrayList<String> healingFailureMessages = new ArrayList<>(); + private Optional<String> executeHealers(String itemId, Version version, + Map<String, Map<String, String>> itemHealers) { + List<String> healers = itemHealers.values().stream() + .map(Map::values) + .flatMap(Collection::stream) + .collect(Collectors.toList()); - for (String implClassName : healerCodeToImplClass.values()) { - heal(healParameters, implClassName, healingFailureMessages); + List<String> healingFailureMessages = new ArrayList<>(); + for (String implClassName : healers) { + executeHealer(itemId, version, implClassName, healingFailureMessages); } - return healingFailureMessages.isEmpty() ? Optional.empty() + return healingFailureMessages.isEmpty() + ? Optional.empty() : Optional.of(CommonMethods.listToSeparatedString(healingFailureMessages, '\n')); } - private Object heal(Map<String, Object> healParameters, String healerImplClassName, - ArrayList<String> healingFailureMessages) { - Healer healerImpl; + + private Object executeHealer(String itemId, Version version, String healerClassName, + List<String> healingFailureMessages) { + Healer healer; try { - healerImpl = getHealerImplInstance(healerImplClassName); + healer = getHealerImplInstance(healerClassName); } catch (Exception e) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.SELF_HEALING, ErrorLevel.ERROR.name(), LoggerErrorCode .DATA_ERROR.getErrorCode(), LoggerErrorDescription.CANT_HEAL); healingFailureMessages .add(String.format(Messages.CANT_LOAD_HEALING_CLASS.getErrorMessage(), - healerImplClassName)); + healerClassName)); return null; } try { - return healerImpl.heal(healParameters); + return healer.heal(itemId, version); } catch (Exception e) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.SELF_HEALING, ErrorLevel.ERROR.name(), LoggerErrorCode .DATA_ERROR.getErrorCode(), LoggerErrorDescription.CANT_HEAL); - healingFailureMessages.add(e.getMessage() + " ,healer name :" + healerImplClassName); + healingFailureMessages.add(e.getMessage() + " ,healer name :" + healerClassName); } return null; } - private static Map<String, String> initHealers() { - return FileUtils.readViaInputStream(HEALING_CONF_FILE, stream -> JsonUtil.json2Object(stream, Map.class)); + private boolean isPrivateHealingNeededByFlag(String itemId, String version, String user) { + Optional<Boolean> userHealingFlag = getHealingFlag(itemId, version, user); + return userHealingFlag.isPresent() + ? userHealingFlag.get() + : isPublicHealingNeededByFlag(itemId, version); + } + + private boolean isPublicHealingNeededByFlag(String itemId, String versionId) { + Optional<Boolean> publicHealingFlag = getHealingFlag(itemId, versionId, PUBLIC_USER); + return publicHealingFlag.isPresent() && publicHealingFlag.get(); + } + + private Optional<Boolean> getHealingFlag(String itemId, String version, String user) { + return healingDao.getItemHealingFlag(user, itemId, version); + } + + private void markAsHealed(String itemId, String versionId, String user) { + healingDao.setItemHealingFlag(false, user, itemId, versionId); + } + + private Map<String, Map<String, String>> getItemHealers(ItemType itemType) { + // TODO: 11/29/2017 create objects to hold this configuration + + // load once from the json file and use the relevant healers (by itemType, healerType) as needed. + Map healingConfig = FileUtils + .readViaInputStream(HEALERS_BY_ENTITY_TYPE_FILE, + stream -> JsonUtil.json2Object(stream, Map.class)); + return (Map<String, Map<String, String>>) healingConfig.get(itemType.name()); } private Healer getHealerImplInstance(String implClassName) @@ -106,4 +250,9 @@ public class HealingManagerImpl implements HealingManager { NoSuchMethodException, ClassNotFoundException { return (Healer) Class.forName(implClassName).getConstructor().newInstance(); } + + private String getUser() { + return SessionContextProviderFactory.getInstance().createInterface().get().getUser() + .getUserId(); + } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/entityHealingConfiguration.json b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/entityHealingConfiguration.json new file mode 100644 index 0000000000..ab8a1dfb4f --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/entityHealingConfiguration.json @@ -0,0 +1,12 @@ +{ + "vsp": { + "structure": { + "ownerHealer": "org.openecomp.sdc.healing.healers.OwnerHealer" + } + }, + "vlm": { + "structure": { + "ownerHealer": "org.openecomp.sdc.healing.healers.OwnerHealer" + } + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/healingConfiguration.json b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/healingConfiguration.json index 4e1b0df97a..85eec77c56 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/healingConfiguration.json +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/resources/healingConfiguration.json @@ -1,13 +1,19 @@ { - "FILE_DATA_STRUCTURE_HEALER" : "org.openecomp.sdc.healing.healers.FileDataStructureHealer", - "QUESTIONNAIRE_HEALER" : "org.openecomp.sdc.healing.healers.VspQuestionnaireHealer", - "COMPOSITION_DATA_HEALER" : "org.openecomp.sdc.healing.healers.CompositionDataHealer", - "SUB_ENTITIES_HEALER" : "org.openecomp.sdc.healing.healers.SubEntitiesQuestionnaireHealer", - "ONBOARDING_METHOD_HEALER" : "org.openecomp.sdc.healing.healers.VspOnboardingMethodHealer", - "NIC_DATA_HEALER" : "org.openecomp.sdc.healing.healers.NicDataHealer", - "COMPONENT_QUESTIONNAIRE_HEALER" : "org.openecomp.sdc.healing.healers.ComponentQuestionnaireHealer", - "HEAT_TOSCA_TRANSLATION_HEALER" : "org.openecomp.sdc.healing.healers.HeatToToscaTranslationHealer", - "VLM_VERSION_HEALER" : "org.openecomp.sdc.healing.healers.VlmVersionHealer", - "VALIDATION_STRUCTURE_HEALER" : "org.openecomp.sdc.healing.healers.ValidationStructureHealer", - "FORWARDER_CAPABILITY_HEALER" : "org.openecomp.sdc.healing.healers.ForwarderCapabilityHealer" + "VendorSoftwareProduct" : { + "VSP_OWNER_HEALER" : "org.openecomp.sdc.healing.healers.VspOwnerHealer", + "FILE_DATA_STRUCTURE_HEALER" : "org.openecomp.sdc.healing.healers.FileDataStructureHealer", + "QUESTIONNAIRE_HEALER" : "org.openecomp.sdc.healing.healers.VspQuestionnaireHealer", + "COMPOSITION_DATA_HEALER" : "org.openecomp.sdc.healing.healers.CompositionDataHealer", + "SUB_ENTITIES_HEALER" : "org.openecomp.sdc.healing.healers.SubEntitiesQuestionnaireHealer", + "ONBOARDING_METHOD_HEALER" : "org.openecomp.sdc.healing.healers.VspOnboardingMethodHealer", + "NIC_DATA_HEALER" : "org.openecomp.sdc.healing.healers.NicDataHealer", + "COMPONENT_QUESTIONNAIRE_HEALER" : "org.openecomp.sdc.healing.healers.ComponentQuestionnaireHealer", + "HEAT_TOSCA_TRANSLATION_HEALER" : "org.openecomp.sdc.healing.healers.HeatToToscaTranslationHealer", + "VLM_VERSION_HEALER" : "org.openecomp.sdc.healing.healers.VlmVersionHealer", + "VALIDATION_STRUCTURE_HEALER" : "org.openecomp.sdc.healing.healers.ValidationStructureHealer", + "FORWARDER_CAPABILITY_HEALER" : "org.openecomp.sdc.healing.healers.ForwarderCapabilityHealer" + }, + "VendorLicenseModel" : { + "VLM_OWNER_HEALER" : "org.openecomp.sdc.healing.healers.VlmOwnerHealer" + } }
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/pom.xml b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/pom.xml index c54f724b9a..1359e6921d 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/pom.xml +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/pom.xml @@ -39,6 +39,11 @@ <artifactId>openecomp-sdc-vendor-license-api</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-impl</artifactId> + <version>${project.version}</version> + </dependency> </dependencies> diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealer.java index 50e76781b3..83395e015a 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealer.java @@ -4,7 +4,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; @@ -19,7 +18,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; -import java.util.Map; import java.util.Objects; @@ -57,11 +55,9 @@ public class ComponentQuestionnaireHealer implements Healer { } @Override - public Object heal(Map<String, Object> healingParams) throws Exception { - mdcDataDebugMessage.debugEntryMessage("VSP ID", - (String) healingParams.get(SdcCommon.VSP_ID)); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); + public Object heal(String vspId, Version version) throws Exception { + mdcDataDebugMessage.debugEntryMessage("VSP ID", vspId); + Collection<ComponentEntity> componentEntities = componentDao.list(new ComponentEntity(vspId, version, null)); componentEntities.forEach(componentEntity -> { diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java index 6fc8cfef61..e7a5e30f2d 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/CompositionDataHealer.java @@ -31,7 +31,6 @@ import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.common.utils.CommonUtil; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -57,7 +56,7 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionDataExtractorFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionEntityDataManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; @@ -69,7 +68,6 @@ import org.openecomp.sdc.versioning.dao.types.Version; import java.io.IOException; import java.util.Collection; -import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -102,14 +100,10 @@ public class CompositionDataHealer implements Healer { } @Override - public Optional<CompositionData> heal(Map<String, Object> healingParams) throws IOException { + public Optional<CompositionData> heal(String vspId, + Version version) throws IOException { mdcDataDebugMessage.debugEntryMessage(null); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = VERSION00.equals(healingParams.get(SdcCommon.VERSION)) - ? VERSION01 - : (Version) healingParams.get(SdcCommon.VERSION); - Collection<ComponentEntity> componentEntities = componentDao.list(new ComponentEntity(vspId, version, null)); Collection<NicEntity> nicEntities = nicDao.listByVsp(vspId, version); @@ -131,7 +125,7 @@ public class CompositionDataHealer implements Healer { serviceModels.get()) : null; } - if(serviceModels.isPresent()) { + if (serviceModels.isPresent()) { compositionData = getCompositionDataForHealing(vspId, version, serviceModels.get()); HealNfodData(vspId, version, compositionData); @@ -150,16 +144,16 @@ public class CompositionDataHealer implements Healer { if (CollectionUtils.isEmpty(computeEntities) && CollectionUtils.isEmpty(imageEntities)) { for (Component component : compositionData.getComponents()) { String componentId = null; - for (ComponentEntity componentEntity:componentEntities) { + for (ComponentEntity componentEntity : componentEntities) { if (componentEntity.getComponentCompositionData().getName().equals(component.getData() .getName())) { componentId = componentEntity.getId(); break; } } - compositionEntityDataManager.saveComputesFlavorByComponent(vspId,version,component, + compositionEntityDataManager.saveComputesFlavorByComponent(vspId, version, component, componentId); - compositionEntityDataManager.saveImagesByComponent(vspId,version,component, + compositionEntityDataManager.saveImagesByComponent(vspId, version, component, componentId); } @@ -228,13 +222,15 @@ public class CompositionDataHealer implements Healer { } private Optional<Pair<ToscaServiceModel, ToscaServiceModel>> getServiceModelForHealing(String - vspId, Version + vspId, + Version version) throws IOException { mdcDataDebugMessage.debugEntryMessage("VSP id", vspId); - UploadDataEntity uploadData = - orchestrationTemplateDataDao.getOrchestrationTemplate(vspId, version); + /*OrchestrationTemplateEntity uploadData = + vendorSoftwareProductDao.getUploadData(new OrchestrationTemplateEntity(vspId, version));*/ + OrchestrationTemplateEntity uploadData = orchestrationTemplateDataDao.get(vspId, version); if (Objects.isNull(uploadData) || Objects.isNull(uploadData.getContentData())) { return Optional.empty(); @@ -259,7 +255,7 @@ public class CompositionDataHealer implements Healer { .getNonUnifiedToscaServiceModel())); } - private TranslatorOutput getTranslatorOutputForHealing(UploadDataEntity uploadData) { + private TranslatorOutput getTranslatorOutputForHealing(OrchestrationTemplateEntity uploadData) { FileContentHandler fileContentHandler; try { diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/FileDataStructureHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/FileDataStructureHealer.java index 4a0a5f9d63..6e49c9a6cf 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/FileDataStructureHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/FileDataStructureHealer.java @@ -24,33 +24,23 @@ import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.common.utils.CommonUtil; -import org.openecomp.sdc.common.utils.SdcCommon; -import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.factory.CandidateServiceFactory; -import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule.CandidateService; import org.openecomp.sdc.vendorsoftwareproduct.services.utils.CandidateEntityBuilder; import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.HashMap; -import java.util.List; -import java.util.Map; import java.util.Optional; public class FileDataStructureHealer implements Healer { - private static final OrchestrationTemplateDao orchestrationTemplateDataDao = - OrchestrationTemplateDaoFactory.getInstance().createInterface(); - private static CandidateService candidateService = - CandidateServiceFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); @@ -59,64 +49,55 @@ public class FileDataStructureHealer implements Healer { } @Override - public Optional<FilesDataStructure> heal(Map<String, Object> healingParams) throws Exception { - - + public Optional<FilesDataStructure> heal(String vspId, + Version version) throws Exception { mdcDataDebugMessage.debugEntryMessage(null); - Optional<FilesDataStructure> healingResult = Optional.empty(); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - String user = (String) healingParams.get(SdcCommon.USER); + OrchestrationTemplateCandidateDao candidateDao = + OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface(); + + OrchestrationTemplateCandidateData candidateData = candidateDao.get(vspId, version); - UploadDataEntity uploadData = - orchestrationTemplateDataDao.getOrchestrationTemplate(vspId,version); - if (uploadData == null || uploadData.getContentData() == null) { - FilesDataStructure emptyFilesDataStructure = new FilesDataStructure(); - return Optional.of(emptyFilesDataStructure); + if (candidateData == null || candidateData.getContentData() == null || + candidateData.getFilesDataStructure() != null) { + return Optional.of(new FilesDataStructure()); } - Optional<FilesDataStructure> candidateFileDataStructure = - candidateService.getOrchestrationTemplateCandidateFileDataStructure(vspId, version); + Optional<FilesDataStructure> filesDataStructure = + healFilesDataStructure(vspId, version, candidateData); - if (!candidateFileDataStructure.isPresent()) { - healingResult = healFilesDataStructure(vspId, version, user, uploadData); - } + filesDataStructure + .ifPresent(structure -> candidateDao.updateStructure(vspId, version, structure)); mdcDataDebugMessage.debugExitMessage(null); - return healingResult; + return filesDataStructure; } - private Optional<FilesDataStructure> healFilesDataStructure(String vspId, Version version, - String user, - UploadDataEntity uploadData) + private Optional<FilesDataStructure> healFilesDataStructure( + String vspId, Version version, OrchestrationTemplateCandidateData candidateData) throws Exception { - - mdcDataDebugMessage.debugEntryMessage(null); Optional<FilesDataStructure> healingResult; - byte[] byteContentData = uploadData.getContentData().array(); + byte[] byteContentData = candidateData.getContentData().array(); FileContentHandler fileContentHandler; - try{ - fileContentHandler = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, byteContentData); - Map<String, List<ErrorMessage>> errors = new HashMap<>(); - OrchestrationTemplateCandidateData candidateDataEntity = - new CandidateEntityBuilder(candidateService) - .buildCandidateEntityFromZip(new VspDetails(vspId, version), byteContentData, - fileContentHandler, errors, user); - - healingResult = getFileDataStructureFromJson(candidateDataEntity.getFilesDataStructure()); - }catch (Exception e){ + try { + fileContentHandler = + CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, byteContentData); + + String filesDataStructure = + new CandidateEntityBuilder(CandidateServiceFactory.getInstance().createInterface()) + .buildCandidateEntityFromZip(new VspDetails(vspId, version), byteContentData, + fileContentHandler, new HashMap<>()).getFilesDataStructure(); + + healingResult = + Optional.of(JsonUtil.json2Object(filesDataStructure, FilesDataStructure.class)); + } catch (Exception e) { log.debug("", e); - return Optional.empty(); + healingResult = Optional.empty(); } mdcDataDebugMessage.debugExitMessage(null); return healingResult; } - - private Optional<FilesDataStructure> getFileDataStructureFromJson(String fileDataStructureJson) { - return Optional.of(JsonUtil.json2Object(fileDataStructureJson, FilesDataStructure.class)); - } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealer.java index c2d7c2c5e4..7991c5904e 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealer.java @@ -5,7 +5,6 @@ import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.dao.ServiceModelDaoFactory; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.sdc.common.togglz.ToggleableFeature; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; @@ -46,10 +45,7 @@ public class ForwarderCapabilityHealer implements Healer { } @Override - public Object heal(Map<String, Object> healingParams) throws Exception { - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - + public Object heal(String vspId, Version version) throws Exception { if(!ToggleableFeature.FORWARDER_CAPABILITY.isActive()) { return Optional.empty(); } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/HeatToToscaTranslationHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/HeatToToscaTranslationHealer.java index 32cd8cbae3..ddae09fa01 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/HeatToToscaTranslationHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/HeatToToscaTranslationHealer.java @@ -3,14 +3,11 @@ package org.openecomp.sdc.healing.healers; import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.dao.ServiceModelDaoFactory; -import org.openecomp.core.model.dao.ServiceTemplateDaoFactory; -import org.openecomp.core.model.dao.ServiceTemplateDaoInter; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.core.translator.datatypes.TranslatorOutput; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; import org.openecomp.sdc.common.utils.CommonUtil; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -19,37 +16,32 @@ import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Map; import java.util.Objects; import java.util.Optional; -public class HeatToToscaTranslationHealer implements Healer { +public class HeatToToscaTranslationHealer implements Healer { private static final OrchestrationTemplateDao orchestrationTemplateDao = OrchestrationTemplateDaoFactory.getInstance().createInterface(); private static final ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao = ServiceModelDaoFactory.getInstance().createInterface(); - public static final ServiceTemplateDaoInter - templateDao = ServiceTemplateDaoFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - public HeatToToscaTranslationHealer(){ + public HeatToToscaTranslationHealer() { } @Override - public Object heal(Map<String, Object> healingParams) throws Exception { - mdcDataDebugMessage.debugEntryMessage(null, null); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - String user = (String) healingParams.get(SdcCommon.USER); - UploadDataEntity uploadData = - orchestrationTemplateDao.getOrchestrationTemplate(vspId, version); + public Object heal(String vspId, Version version) throws Exception { + mdcDataDebugMessage.debugEntryMessage(null);; + + OrchestrationTemplateEntity uploadData = + orchestrationTemplateDao.get(vspId, version); if (Objects.isNull(uploadData) || Objects.isNull(uploadData.getContentData())) { return Optional.empty(); @@ -58,8 +50,9 @@ public class HeatToToscaTranslationHealer implements Healer { FileContentHandler fileContentHandler; TranslatorOutput translatorOutput; try { - fileContentHandler = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadData - .getContentData().array()); + fileContentHandler = + CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadData + .getContentData().array()); translatorOutput = HeatToToscaUtil.loadAndTranslateTemplateData(fileContentHandler); } catch (Exception e) { diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NicDataHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NicDataHealer.java index 123a943785..b2ef965286 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NicDataHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NicDataHealer.java @@ -1,20 +1,16 @@ package org.openecomp.sdc.healing.healers; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.NetworkType; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Nic; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; -import java.util.Map; public class NicDataHealer implements Healer { /*private static final VendorSoftwareProductDao vendorSoftwareProductDao = @@ -28,11 +24,9 @@ public class NicDataHealer implements Healer { } @Override - public Object heal(Map<String, Object> healingParams) throws Exception { + public Object heal(String vspId, Version version) throws Exception { mdcDataDebugMessage.debugEntryMessage(null, null); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - String user = (String) healingParams.get(SdcCommon.USER); + Collection<NicEntity> nics = nicDao.listByVsp(vspId, version); for (NicEntity nicEntity : nics) { Nic nic = nicEntity.getNicCompositionData(); diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/OwnerHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/OwnerHealer.java new file mode 100644 index 0000000000..acc20c97e4 --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/OwnerHealer.java @@ -0,0 +1,47 @@ +package org.openecomp.sdc.healing.healers; + +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.healing.interfaces.Healer; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDaoFactory; +import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.versioning.dao.types.Version; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; + +/** + * Created by ayalaben on 8/28/2017 + */ +public class OwnerHealer implements Healer { + private static final String HEALING_USER_SUFFIX = "_healer"; + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + private static final ItemPermissionsDao permissionsDao = + ItemPermissionsDaoFactory.getInstance().createInterface(); + + public Object heal(String itemId, Version version) { + mdcDataDebugMessage.debugEntryMessage(null); + + Collection<ItemPermissionsEntity> itemPermissions = permissionsDao.listItemPermissions(itemId); + + if (itemPermissions.stream().noneMatch(this::isOwnerPermission)) { + String currentUserId = + SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId() + .replace(HEALING_USER_SUFFIX, ""); + + permissionsDao.updateItemPermissions(itemId, PermissionTypes.Owner.name(), + Collections.singleton(currentUserId), new HashSet<>()); + + return currentUserId; + } + return itemPermissions.stream().filter(this::isOwnerPermission).findFirst().get().getUserId(); + } + + private boolean isOwnerPermission(ItemPermissionsEntity permissionsEntity) { + return permissionsEntity.getPermission().equals(PermissionTypes.Owner.name()); + } +} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/SubEntitiesQuestionnaireHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/SubEntitiesQuestionnaireHealer.java index 9355eb076f..a1dd80c307 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/SubEntitiesQuestionnaireHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/SubEntitiesQuestionnaireHealer.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.healing.healers; import org.openecomp.core.utilities.json.JsonSchemaDataGenerator; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; @@ -30,8 +29,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; @@ -42,15 +39,12 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.versioning.dao.types.Version; import java.util.Collection; -import java.util.Map; import java.util.Objects; public class SubEntitiesQuestionnaireHealer implements Healer { private static Version version00 = new Version(0, 0); private MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private static final VendorSoftwareProductDao vendorSoftwareProductDao = - VendorSoftwareProductDaoFactory.getInstance().createInterface(); private static ComponentDao componentDao = ComponentDaoFactory.getInstance().createInterface(); private static NicDao nicDao = NicDaoFactory.getInstance().createInterface(); private static NetworkDao networkDao = NetworkDaoFactory.getInstance().createInterface(); @@ -59,22 +53,17 @@ public class SubEntitiesQuestionnaireHealer implements Healer { private static String emptyJson = "{}"; @Override - public Object heal(Map<String, Object> healingParams) throws Exception { + public Object heal(String vspId, Version version) throws Exception { mdcDataDebugMessage.debugEntryMessage(null); - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = version00.equals(healingParams.get(SdcCommon.VERSION)) ? new Version - (0, 1) - : (Version) healingParams.get(SdcCommon.VERSION); - Collection<ComponentEntity> componentEntities = componentDao.listCompositionAndQuestionnaire(vspId, version); networkDao.list(new NetworkEntity(vspId, version, null)); - Collection<NicEntity> nicEntities = vendorSoftwareProductDao.listNicsByVsp(vspId, version); + Collection<NicEntity> nicEntities = nicDao.listByVsp(vspId, version); healCompositionEntityQuestionnaire(componentEntities, version, CompositionEntityType.component); healCompositionEntityQuestionnaire(nicEntities, version, CompositionEntityType.nic); diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ValidationStructureHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ValidationStructureHealer.java index 4bf7e18091..d172432284 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ValidationStructureHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ValidationStructureHealer.java @@ -2,7 +2,6 @@ package org.openecomp.sdc.healing.healers; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.heat.datatypes.manifest.FileData; @@ -13,16 +12,11 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadData; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.types.Version; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -32,78 +26,55 @@ import java.util.Set; */ public class ValidationStructureHealer implements Healer { - private static final VendorSoftwareProductInfoDao vspInfoDao = - VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); + private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class); private static final OrchestrationTemplateDao orchestrationTemplateDao = OrchestrationTemplateDaoFactory.getInstance().createInterface(); - private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class); @Override - public Object heal(Map<String, Object> healingParams) throws Exception { + public Object heal(String vspId, Version version) throws Exception { - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); + OrchestrationTemplateEntity orchestrationTemplate = + orchestrationTemplateDao.get(vspId, version); - VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); - UploadDataEntity orchestrationTemplate = - orchestrationTemplateDao.getOrchestrationTemplate(vspId, version); - - if(Objects.isNull(orchestrationTemplate.getValidationData()) - || !JsonUtil.isValidJson(orchestrationTemplate.getValidationData())){ + if (Objects.isNull(orchestrationTemplate.getValidationData()) + || !JsonUtil.isValidJson(orchestrationTemplate.getValidationData())) { return Optional.empty(); } OldValidationStructureTree oldValidationStructureTree; - try{ - oldValidationStructureTree = - JsonUtil.json2Object(orchestrationTemplate.getValidationData(), OldValidationStructureTree - .class); - } catch (Exception e){ - logger.debug("",e); + try { + oldValidationStructureTree = JsonUtil + .json2Object(orchestrationTemplate.getValidationData(), OldValidationStructureTree.class); + } catch (Exception e) { + logger.debug("", e); return Optional.empty(); } Optional<HeatStructureTree> newHeatStructureTreeFromOldStructureTree = - createNewHeatStructureTreeFromOldStructureTree(oldValidationStructureTree.getImportStructure()); + createNewHeatStructureTreeFromOldStructureTree( + oldValidationStructureTree.getImportStructure()); - if(newHeatStructureTreeFromOldStructureTree.isPresent()){ - ValidationStructureList validationData = new ValidationStructureList - (newHeatStructureTreeFromOldStructureTree.get()); - vspDetails.setValidationDataStructure(validationData); + newHeatStructureTreeFromOldStructureTree.ifPresent(newStructure -> + updateValuesInDb(vspId, version, orchestrationTemplate, + new ValidationStructureList(newStructure))); - updateValuesInDb(vspId, vspDetails, orchestrationTemplate, validationData); - } return newHeatStructureTreeFromOldStructureTree; } - private void updateValuesInDb(String vspId, VspDetails vspDetails, - UploadDataEntity orchestrationTemplate, + private void updateValuesInDb(String vspId, Version version, + OrchestrationTemplateEntity orchestrationTemplate, ValidationStructureList validationData) { - vspInfoDao.update(vspDetails); - UploadData uploadData = getUpdatedUploadData(orchestrationTemplate, validationData); - orchestrationTemplateDao.updateOrchestrationTemplateData(vspId, uploadData); + orchestrationTemplate.setValidationDataStructure(validationData); + orchestrationTemplateDao.update(vspId, version, orchestrationTemplate); } - private UploadData getUpdatedUploadData(UploadDataEntity orchestrationTemplate, - ValidationStructureList validationData) { - UploadData uploadData = new UploadData(); - uploadData.setValidationDataStructure(validationData); - uploadData.setValidationData(JsonUtil.object2Json(validationData)); - uploadData.setContentData(orchestrationTemplate.getContentData()); - uploadData.setId(orchestrationTemplate.getId()); - uploadData.setPackageName(orchestrationTemplate.getPackageName()); - uploadData.setPackageVersion(orchestrationTemplate.getPackageVersion()); - return uploadData; - } - - - private Optional<HeatStructureTree> createNewHeatStructureTreeFromOldStructureTree(OldHeatStructureTree - oldHeatStructureTree){ + private Optional<HeatStructureTree> createNewHeatStructureTreeFromOldStructureTree( + OldHeatStructureTree oldHeatStructureTree) { HeatStructureTree heatStructureTree = new HeatStructureTree(); - if(Objects.isNull(oldHeatStructureTree)){ + if (Objects.isNull(oldHeatStructureTree)) { return Optional.empty(); } @@ -112,11 +83,14 @@ public class ValidationStructureHealer implements Healer { Set<OldHeatStructureTree> heat = oldHeatStructureTree.getHeat() == null ? new HashSet<>() : oldHeatStructureTree.getHeat(); Set<OldHeatStructureTree> volume = - oldHeatStructureTree.getVolume() == null ? new HashSet<>() : oldHeatStructureTree.getVolume(); + oldHeatStructureTree.getVolume() == null ? new HashSet<>() + : oldHeatStructureTree.getVolume(); Set<OldHeatStructureTree> nested = - oldHeatStructureTree.getNested() == null ? new HashSet<>() : oldHeatStructureTree.getNested(); + oldHeatStructureTree.getNested() == null ? new HashSet<>() + : oldHeatStructureTree.getNested(); Set<OldHeatStructureTree> network = - oldHeatStructureTree.getNetwork() == null ? new HashSet<>() : oldHeatStructureTree.getNetwork(); + oldHeatStructureTree.getNetwork() == null ? new HashSet<>() + : oldHeatStructureTree.getNetwork(); heatStructureTree.setHeat(createHeatStructureTreeSetFromOld(heat)); @@ -124,57 +98,47 @@ public class ValidationStructureHealer implements Healer { heatStructureTree.setNested(createHeatStructureTreeSetFromOld(nested)); heatStructureTree.setNetwork(createHeatStructureTreeSetFromOld(network)); - return Optional.of(heatStructureTree); - } - private void mapOldHeatStructureTreeValues( - OldHeatStructureTree oldHeatStructureTree, - HeatStructureTree heatStructureTree) { + private void mapOldHeatStructureTreeValues(OldHeatStructureTree oldHeatStructureTree, + HeatStructureTree heatStructureTree) { heatStructureTree.setFileName(oldHeatStructureTree.getFileName()); heatStructureTree.setBase(oldHeatStructureTree.getBase()); heatStructureTree.setType(oldHeatStructureTree.getType()); heatStructureTree.setArtifacts(oldHeatStructureTree.getArtifacts()); heatStructureTree.setErrors(oldHeatStructureTree.getErrors()); - if(Objects.nonNull(oldHeatStructureTree.getEnv())) { + if (Objects.nonNull(oldHeatStructureTree.getEnv())) { heatStructureTree.setEnv(new HeatStructureTree(oldHeatStructureTree.getEnv(), false)); } } private Set<HeatStructureTree> createHeatStructureTreeSetFromOld(Set<OldHeatStructureTree> - oldHeatStructureTreeSet){ - if(CollectionUtils.isEmpty(oldHeatStructureTreeSet)){ + oldHeatStructureTreeSet) { + if (CollectionUtils.isEmpty(oldHeatStructureTreeSet)) { return null; } Set<HeatStructureTree> newHeatStructureSet = new HashSet<>(); - for(OldHeatStructureTree old : oldHeatStructureTreeSet){ + for (OldHeatStructureTree old : oldHeatStructureTreeSet) { Optional<HeatStructureTree> newHeatStructureTree = createNewHeatStructureTreeFromOldStructureTree(old); - if(newHeatStructureTree.isPresent()){ - newHeatStructureSet.add(newHeatStructureTree.get()); - } + newHeatStructureTree.ifPresent(newHeatStructureSet::add); } return newHeatStructureSet; } - private class OldValidationStructureTree{ + private class OldValidationStructureTree { private OldHeatStructureTree importStructure; - public OldHeatStructureTree getImportStructure() { + OldHeatStructureTree getImportStructure() { return importStructure; } - - public void setImportStructure( - OldHeatStructureTree importStructure) { - this.importStructure = importStructure; - } } - private class OldHeatStructureTree{ + private class OldHeatStructureTree { private String fileName; private FileData.Type type; private Boolean isBase; @@ -190,93 +154,93 @@ public class ValidationStructureHealer implements Healer { public OldHeatStructureTree() { } - public String getFileName() { - return fileName; - } + public String getFileName() { + return fileName; + } - public void setFileName(String fileName) { - this.fileName = fileName; - } + public void setFileName(String fileName) { + this.fileName = fileName; + } - public FileData.Type getType() { - return type; - } + public FileData.Type getType() { + return type; + } - public void setType(FileData.Type type) { - this.type = type; - } + public void setType(FileData.Type type) { + this.type = type; + } - public Boolean getBase() { - return isBase; - } + public Boolean getBase() { + return isBase; + } - public void setBase(Boolean base) { - isBase = base; - } + public void setBase(Boolean base) { + isBase = base; + } - public String getEnv() { - return env; - } + public String getEnv() { + return env; + } - public void setEnv(String env) { - this.env = env; - } + public void setEnv(String env) { + this.env = env; + } - public List<ErrorMessage> getErrors() { - return errors; - } + public List<ErrorMessage> getErrors() { + return errors; + } - public void setErrors(List<ErrorMessage> errors) { - this.errors = errors; - } + public void setErrors(List<ErrorMessage> errors) { + this.errors = errors; + } - public Set<OldHeatStructureTree> getHeat() { - return heat; - } + public Set<OldHeatStructureTree> getHeat() { + return heat; + } - public void setHeat(Set<OldHeatStructureTree> heat) { - this.heat = heat; - } + public void setHeat(Set<OldHeatStructureTree> heat) { + this.heat = heat; + } - public Set<OldHeatStructureTree> getVolume() { - return volume; - } + public Set<OldHeatStructureTree> getVolume() { + return volume; + } - public void setVolume(Set<OldHeatStructureTree> volume) { - this.volume = volume; - } + public void setVolume(Set<OldHeatStructureTree> volume) { + this.volume = volume; + } - public Set<OldHeatStructureTree> getNetwork() { - return network; - } + public Set<OldHeatStructureTree> getNetwork() { + return network; + } - public void setNetwork( - Set<OldHeatStructureTree> network) { - this.network = network; - } + public void setNetwork( + Set<OldHeatStructureTree> network) { + this.network = network; + } - public Set<OldHeatStructureTree> getNested() { - return nested; - } + public Set<OldHeatStructureTree> getNested() { + return nested; + } - public void setNested(Set<OldHeatStructureTree> nested) { - this.nested = nested; - } + public void setNested(Set<OldHeatStructureTree> nested) { + this.nested = nested; + } - public Set<OldHeatStructureTree> getOther() { - return other; - } + public Set<OldHeatStructureTree> getOther() { + return other; + } - public void setOther(Set<OldHeatStructureTree> other) { - this.other = other; - } + public void setOther(Set<OldHeatStructureTree> other) { + this.other = other; + } - public Set<Artifact> getArtifacts() { - return artifacts; - } + public Set<Artifact> getArtifacts() { + return artifacts; + } - public void setArtifacts(Set<Artifact> artifacts) { - this.artifacts = artifacts; + public void setArtifacts(Set<Artifact> artifacts) { + this.artifacts = artifacts; + } } } -} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VlmVersionHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VlmVersionHealer.java index 085923b8a0..a57ac74350 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VlmVersionHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VlmVersionHealer.java @@ -1,26 +1,21 @@ package org.openecomp.sdc.healing.healers; -import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao; import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDaoFactory; import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; -import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; -import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory; -import org.openecomp.sdc.vendorlicense.types.VersionedVendorLicenseModel; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.versioning.VersioningManager; +import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; import java.util.ArrayList; -import java.util.List; -import java.util.Map; +import java.util.Collection; import java.util.Objects; import java.util.Optional; @@ -28,8 +23,8 @@ import java.util.Optional; * Created by TALIO on 7/3/2017. */ public class VlmVersionHealer implements Healer { - private static final VendorLicenseFacade vendorLicenseFacade = - VendorLicenseFacadeFactory.getInstance().createInterface(); + private VersioningManager versioningManager = + VersioningManagerFactory.getInstance().createInterface(); private static final VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); private static final LicenseAgreementDao licenseAgreementDao = @@ -38,51 +33,35 @@ public class VlmVersionHealer implements Healer { LoggerFactory.getLogger(VlmVersionHealer.class); @Override - public Object heal(Map<String, Object> healingParams) throws Exception { - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - String user = (String) healingParams.get(SdcCommon.USER); - + public Object heal(String vspId, Version version) throws Exception { VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); - VersionedVendorLicenseModel vendorLicenseModel; - - if(!Objects.isNull(vspDetails.getVlmVersion())) { + + if (!Objects.isNull(vspDetails.getVlmVersion())) { return Optional.empty(); } - - try{ - vendorLicenseModel = - vendorLicenseFacade.getVendorLicenseModel(vspDetails.getVendorId(), null, user); - } catch (Exception e){ - logger.debug("" + e); + // get the certified vlm version with the highest number in its name + Optional<Version> certifiedVlmVersion = + versioningManager.list(vspDetails.getVendorId()).stream() + .filter(ver -> VersionStatus.Certified == ver.getStatus()) + .max((o1, o2) -> ((Double) Double.parseDouble(o1.getName())) + .compareTo(Double.parseDouble(o2.getName()))); + if (!certifiedVlmVersion.isPresent()) { logger.debug("No Vlm was found for Vsp " + vspDetails.getName()); return Optional.empty(); } + vspDetails.setVlmVersion(certifiedVlmVersion.get()); - VendorLicenseModelEntity vlm = vendorLicenseModel.getVendorLicenseModel(); - String vlmId = vlm.getId(); - Version vlmVersion = getLatestFinalVlmVersion(vendorLicenseModel.getVersionInfo()); - - List<LicenseAgreementEntity> laList = - new ArrayList<>( - licenseAgreementDao.list(new LicenseAgreementEntity(vlmId, vlmVersion, null))); - - - vspDetails.setVlmVersion(vlmVersion); - - if(CollectionUtils.isNotEmpty(laList)) { - vspDetails.setLicenseAgreement(laList.get(0).getId()); - vspDetails.setFeatureGroups(new ArrayList<>(laList.get(0).getFeatureGroupIds())); + Collection<LicenseAgreementEntity> licenseAgreements = licenseAgreementDao.list( + new LicenseAgreementEntity(vspDetails.getVendorId(), certifiedVlmVersion.get(), null)); + if (!licenseAgreements.isEmpty()) { + LicenseAgreementEntity licenseAgreement = licenseAgreements.iterator().next(); + vspDetails.setLicenseAgreement(licenseAgreement.getId()); + vspDetails.setFeatureGroups(new ArrayList<>(licenseAgreement.getFeatureGroupIds())); } vspInfoDao.update(vspDetails); - return vspDetails; - } - - private Version getLatestFinalVlmVersion(VersionInfo versionInfo){ - return versionInfo.getActiveVersion().isFinal() ? versionInfo.getActiveVersion() - : versionInfo.getLatestFinalVersion(); + return vspDetails; } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealer.java index ddcd31453c..d5c082bdae 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealer.java @@ -2,55 +2,91 @@ package org.openecomp.sdc.healing.healers; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OnboardingMethod; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Map; import java.util.Objects; public class VspOnboardingMethodHealer implements Healer { - private static VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; + + private static final String DEFAULT_FILE_NAME = "Upload File"; private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; + private OrchestrationTemplateDao orchestrationTemplateDao; + private OrchestrationTemplateCandidateDao candidateDao; public VspOnboardingMethodHealer(){ - this(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface()); + this(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), + OrchestrationTemplateDaoFactory.getInstance().createInterface(), + OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface()); } - public VspOnboardingMethodHealer( VendorSoftwareProductInfoDao inVendorSoftwareProductInfoDao){ - vendorSoftwareProductInfoDao = inVendorSoftwareProductInfoDao; + public VspOnboardingMethodHealer(VendorSoftwareProductInfoDao vspInfoDao, + OrchestrationTemplateDao orchestrationTemplateDao, + OrchestrationTemplateCandidateDao candidateDao) { + this.vendorSoftwareProductInfoDao = vspInfoDao; + this.orchestrationTemplateDao = orchestrationTemplateDao; + this.candidateDao = candidateDao; } - @Override - public Object heal(Map<String, Object> healingParams) throws Exception { - mdcDataDebugMessage.debugEntryMessage(null, null); - - String onboardingMethod=null; - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - VspDetails vendorSoftwareProductInfo = - vendorSoftwareProductInfoDao.get(new VspDetails(vspId, version)); - String onboardingValue = vendorSoftwareProductInfo.getOnboardingMethod(); - - if(Objects.isNull(onboardingValue)) { - onboardingMethod="NetworkPackage"; - - updateVSPInfo(OnboardingTypesEnum.ZIP.toString(), onboardingMethod, vendorSoftwareProductInfo); - } else if (onboardingValue.equals("HEAT")){ - onboardingMethod="NetworkPackage"; - updateVSPInfo(OnboardingTypesEnum.ZIP.toString(),onboardingMethod, vendorSoftwareProductInfo); + public Object heal(String vspId, Version version) throws Exception { + mdcDataDebugMessage.debugEntryMessage(null); + + VspDetails vsp = vendorSoftwareProductInfoDao.get(new VspDetails(vspId, version)); + healOnboardingMethod(vsp); + + if (!OnboardingMethod.Manual.name().equals(vsp.getOnboardingMethod())) { + healOrchestrationTemplateFileName(vspId, version); + healOrchestrationTemplateCandidateFileName(vspId, version); + } + + mdcDataDebugMessage.debugExitMessage(null); + return null; + } + + private void healOnboardingMethod(VspDetails vsp) { + if (Objects.isNull(vsp.getOnboardingMethod()) || "HEAT".equals(vsp.getOnboardingMethod())) { + vsp.setOnboardingMethod(OnboardingMethod.NetworkPackage.name()); + vendorSoftwareProductInfoDao.update(vsp); } - return onboardingMethod; } - private void updateVSPInfo(String onboardingOrigin, String onboardingMethod, VspDetails vendorSoftwareProductInfo) { - vendorSoftwareProductInfo.setOnboardingMethod(onboardingMethod); - vendorSoftwareProductInfo.setOnboardingOrigin(onboardingOrigin); - vendorSoftwareProductInfoDao.update(vendorSoftwareProductInfo); + private void healOrchestrationTemplateFileName(String vspId, Version version) { + OrchestrationTemplateEntity orchestrationTemplate = + orchestrationTemplateDao.get(vspId, version); + + if (orchestrationTemplate == null || orchestrationTemplate.getContentData() == null || + orchestrationTemplate.getFileSuffix() != null) { + return; + } + orchestrationTemplate.setFileSuffix(OnboardingTypesEnum.ZIP.toString()); + orchestrationTemplate.setFileName(DEFAULT_FILE_NAME); + + orchestrationTemplateDao.update(vspId, version, orchestrationTemplate); + } + + private void healOrchestrationTemplateCandidateFileName(String vspId, Version version) { + OrchestrationTemplateCandidateData candidate = candidateDao.get(vspId, version); + + if (candidate == null || candidate.getContentData() == null || + candidate.getFileSuffix() != null) { + return; + } + candidate.setFileSuffix(OnboardingTypesEnum.ZIP.toString()); + candidate.setFileName(DEFAULT_FILE_NAME); + + candidateDao.update(vspId, version, candidate); } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspQuestionnaireHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspQuestionnaireHealer.java index 0952a4c88f..b45ce30a3e 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspQuestionnaireHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/VspQuestionnaireHealer.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.healing.healers; import org.openecomp.core.utilities.json.JsonSchemaDataGenerator; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; @@ -35,7 +34,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.SchemaTempl import org.openecomp.sdc.versioning.dao.types.Version; import java.io.IOException; -import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -50,15 +48,12 @@ public class VspQuestionnaireHealer implements Healer { } @Override - public Object heal(Map<String, Object> healingParams) throws IOException { + public Object heal(String vspId, Version version) throws IOException { mdcDataDebugMessage.debugEntryMessage(null, null); Optional<String> questionnaireData = null; - String vspId = (String) healingParams.get(SdcCommon.VSP_ID); - Version version = (Version) healingParams.get(SdcCommon.VERSION); - VspQuestionnaireEntity vspQuestionnaireEntity = vspInfoDao.getQuestionnaire(vspId, version); diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealerTest.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealerTest.java index 69f4287cd1..688d1d4236 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealerTest.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ComponentQuestionnaireHealerTest.java @@ -8,7 +8,6 @@ import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; @@ -20,10 +19,7 @@ import org.openecomp.sdc.versioning.dao.types.Version; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; -import java.util.HashMap; -import java.util.Map; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.doNothing; @@ -47,7 +43,6 @@ public class ComponentQuestionnaireHealerTest { private static final String DUMMY_COMPONENT_ID = "2495ef442f964cbfb00d82bd54292f89"; private static final String DUMMY_COMPUTE_ID = "3495ef442f964cbfb00d82bd54292f89"; private static final String DUMMY_IMAGE_ID = "4495ef442f964cbfb00d82bd54292f89"; - private static Map<String, Object> healingParams = new HashMap<>(); private static final String componentQuestionnaireData = "{\"compute\": {" + "\"guestOS\": {\"bitSize\": 64},\"vmSizing\": {\"IOOperationsPerSec\": \"0\"}," + "\"numOfVMs\": {\"CpuOverSubscriptionRatio\": \"1:1\",\"MemoryRAM\": \"2 GB\"}}," + @@ -131,16 +126,13 @@ public class ComponentQuestionnaireHealerTest { @Before public void init() throws Exception { MockitoAnnotations.initMocks(ComponentQuestionnaireHealerTest.this); - - healingParams.put(SdcCommon.VSP_ID, DUMMY_VSP_ID); - healingParams.put(SdcCommon.VERSION, VERSION); } @Test public void healQuestionnaireNullTest() throws Exception { prepareHealingData(); componentEntity.setQuestionnaireData(null); - Object returnObject = componentQuestionnaireHealer.heal(healingParams); + Object returnObject = componentQuestionnaireHealer.heal(DUMMY_VSP_ID, VERSION); Assert.assertTrue(returnObject instanceof Collection); Collection<ComponentEntity> componentEntities = (Collection<ComponentEntity>) returnObject; componentEntities.forEach(componentEntity -> { @@ -152,7 +144,7 @@ public class ComponentQuestionnaireHealerTest { public void healAllCasesTest() throws Exception { prepareHealingData(); - Object returnObject = componentQuestionnaireHealer.heal(healingParams); + Object returnObject = componentQuestionnaireHealer.heal(DUMMY_VSP_ID, VERSION); Assert.assertTrue(returnObject instanceof Collection); Collection<ComponentEntity> componentEntities = (Collection<ComponentEntity>) returnObject; componentEntities.forEach(componentEntity -> { @@ -177,7 +169,7 @@ public class ComponentQuestionnaireHealerTest { public void healDiskAttrMissingTest() throws Exception { prepareHealingData(); componentEntity.setQuestionnaireData(componentQuestionnaireMissingDiskAttrData); - Object returnObject = componentQuestionnaireHealer.heal(healingParams); + Object returnObject = componentQuestionnaireHealer.heal(DUMMY_VSP_ID, VERSION); Assert.assertTrue(returnObject instanceof Collection); Collection<ComponentEntity> componentEntities = (Collection<ComponentEntity>) returnObject; componentEntities.forEach(componentEntity -> { @@ -238,7 +230,7 @@ public class ComponentQuestionnaireHealerTest { .getDeclaredMethod(methodName, JsonObject.class, JsonObject.class); method.setAccessible(true); - method.invoke(componentQuestionnaireHealer,jsonObject.getAsJsonObject(COMPUTE), null); + method.invoke(componentQuestionnaireHealer, jsonObject.getAsJsonObject(COMPUTE), null); } private void prepareHealingData() { diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealerTest.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealerTest.java index 406d039178..a07ace683f 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealerTest.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/ForwarderCapabilityHealerTest.java @@ -13,7 +13,6 @@ import org.mockito.MockitoAnnotations; import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.sdc.common.togglz.ToggleableFeature; -import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.healing.healers.util.TestUtil; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; @@ -32,13 +31,14 @@ import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.eq; public class ForwarderCapabilityHealerTest { + private static final String vspId = "1"; + private static final Version version = new Version(1, 1); private static final String IN_SUFFIX = "/in"; private static final String OUT_SUFFIX = "/out"; private static final String BASE_DIRECTORY = "/mock/healers/forwarder"; private static final String ENTRY_DEFINITION_SERVICE_TEMPLATE = "MainServiceTemplate.yaml"; private static TestFeatureManager manager; - private Map<String,Object> params = new HashMap<>(); @Mock private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao; @@ -65,8 +65,6 @@ public class ForwarderCapabilityHealerTest { @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(ForwarderCapabilityHealerTest.this); - params.put(SdcCommon.VSP_ID,"1"); - params.put(SdcCommon.VERSION, new Version(1,1)); } @@ -127,7 +125,7 @@ public class ForwarderCapabilityHealerTest { private void validateServiceModelAfterHealing(String testDirectory) throws Exception { Optional<ToscaServiceModel> serviceModelObject = - (Optional<ToscaServiceModel>) forwarderCapabilityHealer.heal(params); + (Optional<ToscaServiceModel>) forwarderCapabilityHealer.heal(vspId, version); Assert.assertTrue(serviceModelObject.isPresent()); TestUtil diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealerTest.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealerTest.java index b732cb03b6..5584a5fe77 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealerTest.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/VspOnboardingMethodHealerTest.java @@ -2,69 +2,77 @@ package org.openecomp.sdc.healing.healers; import org.junit.Before; import org.junit.Test; +import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.common.utils.SdcCommon; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateCandidateData; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.HashMap; -import java.util.Map; - import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; -public class VspOnboardingMethodHealerTest{ +public class VspOnboardingMethodHealerTest { + private static final String vspId = "1"; + private static final Version version = new Version(1, 1); + + @Mock + private VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; + @Mock + private OrchestrationTemplateDao orchestrationTemplateDao; + @Mock + private OrchestrationTemplateCandidateDao candidateDao; + @InjectMocks + private VspOnboardingMethodHealer vspOnboardingMethodHealer; + + private OrchestrationTemplateEntity orchestrationTemplateEntity = new OrchestrationTemplateEntity(); + private OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); + private static final String NETWORK_PACKAGE = "NetworkPackage"; + private static final String HEAT = "HEAT"; + private static final String MANUAL = "Manual"; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(VspOnboardingMethodHealerTest.this); + } + + @Test + public void checkHealingWithNullOnboarding() throws Exception { + VspDetails vspDetails = initAndExecuteHealer(null); + assertEquals(vspDetails.getOnboardingMethod(), NETWORK_PACKAGE); + } - @Mock - private VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao; + @Test + public void checkHealingWithHEATOnboarding() throws Exception { + VspDetails vspDetails = initAndExecuteHealer(HEAT); + assertEquals(vspDetails.getOnboardingMethod(), NETWORK_PACKAGE); + } - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(VspOnboardingMethodHealerTest.this); - } + @Test + public void checkHealingWithManualOnboarding() throws Exception { + VspDetails vspDetails = initAndExecuteHealer(MANUAL); + assertEquals(vspDetails.getOnboardingMethod(), MANUAL); + } - @Test - public void checkHealingWithNullOnboarding() throws Exception{ - VspOnboardingMethodHealer vspOnboardingMethodHealer = new VspOnboardingMethodHealer(vendorSoftwareProductInfoDao); - Map<String,Object> params = new HashMap<>(); - params.put(SdcCommon.VSP_ID,"1"); - params.put(SdcCommon.VERSION, new Version(1,1)); - VspDetails vspDetails = new VspDetails(); - vspDetails.setOnboardingMethod(null); - Mockito.when(vendorSoftwareProductInfoDao.get(any())).thenReturn(vspDetails); - vspOnboardingMethodHealer.heal(params); - assertEquals(vspDetails.getOnboardingMethod(),"NetworkPackage"); - assertEquals(vspDetails.getOnboardingOrigin(),"zip"); - } + private VspDetails initAndExecuteHealer(String onboardingMethod) throws Exception { + VspDetails vspDetails = new VspDetails(); + vspDetails.setOnboardingMethod(onboardingMethod); - @Test - public void checkHealingWithHEATOnboarding() throws Exception{ - VspOnboardingMethodHealer vspOnboardingMethodHealer = new VspOnboardingMethodHealer(vendorSoftwareProductInfoDao); - Map<String,Object> params = new HashMap<>(); - params.put(SdcCommon.VSP_ID,"1"); - params.put(SdcCommon.VERSION, new Version(1,1)); - VspDetails vspDetails = new VspDetails(); - vspDetails.setOnboardingMethod("HEAT"); - Mockito.when(vendorSoftwareProductInfoDao.get(any())).thenReturn(vspDetails); - vspOnboardingMethodHealer.heal(params); - assertEquals(vspDetails.getOnboardingMethod(),"NetworkPackage"); - assertEquals(vspDetails.getOnboardingOrigin(),"zip"); - } + setMockActions(vspDetails); + vspOnboardingMethodHealer.heal(vspId, version); + return vspDetails; + } - @Test - public void checkHealingWithManualOnboarding() throws Exception{ - VspOnboardingMethodHealer vspOnboardingMethodHealer = new VspOnboardingMethodHealer(vendorSoftwareProductInfoDao); - Map<String,Object> params = new HashMap<>(); - params.put(SdcCommon.VSP_ID,"1"); - params.put(SdcCommon.VERSION, new Version(1,1)); - VspDetails vspDetails = new VspDetails(); - vspDetails.setOnboardingMethod("Manual"); - Mockito.when(vendorSoftwareProductInfoDao.get(any())).thenReturn(vspDetails); - vspOnboardingMethodHealer.heal(params); - assertEquals(vspDetails.getOnboardingMethod(),"Manual"); - assertEquals(vspDetails.getOnboardingOrigin(),null); - } + private void setMockActions(VspDetails vspDetails) { + Mockito.doReturn(vspDetails).when(vendorSoftwareProductInfoDao).get(any()); + Mockito.doReturn(orchestrationTemplateEntity).when(orchestrationTemplateDao).get(any(), any()); + Mockito.doNothing().when(orchestrationTemplateDao).update(any(), any(), any()); + Mockito.doReturn(candidateData).when(candidateDao).get(any(), any()); + Mockito.doNothing().when(candidateDao).update(any(), any(), any()); + } }
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/data/TestDescriptionHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/data/TestDescriptionHealer.java new file mode 100644 index 0000000000..aac1a502ef --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/data/TestDescriptionHealer.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.healing.healers.testHealers.data; + +import org.openecomp.sdc.healing.interfaces.Healer; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.versioning.dao.types.Version; + +public class TestDescriptionHealer implements Healer { + + @Override + public Object heal(String vspId, Version version) throws Exception { + VspDetails vspDetails = new VspDetails(vspId, version); + vspDetails.setDescription("This is a data healer"); + + return vspDetails; + } +} diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/structure/TestNewEntityInVspHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/structure/TestNewEntityInVspHealer.java new file mode 100644 index 0000000000..7d71c0319b --- /dev/null +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/test/java/org/openecomp/sdc/healing/healers/testHealers/structure/TestNewEntityInVspHealer.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.healing.healers.testHealers.structure; + +import org.openecomp.sdc.healing.interfaces.Healer; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.versioning.dao.types.Version; + +public class TestNewEntityInVspHealer implements Healer { + + @Override + public Object heal(String vspId, Version version) throws Exception { + VspDetails vspDetails = new VspDetails(vspId, version); + vspDetails.setDescription("This is a structure healer"); + + return vspDetails; + } +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/pom.xml b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/pom.xml new file mode 100644 index 0000000000..f69f3041a7 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/pom.xml @@ -0,0 +1,32 @@ +<?xml version="1.0" encoding="UTF-8"?> + <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"> + <modelVersion>4.0.0</modelVersion> + + + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>..</relativePath> + </parent> + + <artifactId>openecomp-item-permissions-api</artifactId> + + <dependencies> + + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-nosqldb-core</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-facade-api</artifactId> + <version>${project.version}</version> + </dependency> + + + </dependencies> + +</project>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRules.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRules.java new file mode 100644 index 0000000000..b5a119e8ed --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRules.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.itempermissions; + +import java.util.Set; + +/** + * Created by ayalaben on 6/22/2017. + */ +public interface PermissionsRules { + + boolean isAllowed(String userId,String action); + + void executeAction(String itemId, String userId, String action); + + void updatePermission(String itemId,String currentUserId, String permission,Set<String> + addedUsersIds, Set<String> removedUsersIds); + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRulesFactory.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRulesFactory.java new file mode 100644 index 0000000000..c3e0672939 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsRulesFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.itempermissions; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +/** + * Created by ayalaben on 6/26/2017 + */ +public abstract class PermissionsRulesFactory extends + AbstractComponentFactory<PermissionsRules> { + + public static PermissionsRulesFactory getInstance() { + return AbstractFactory.getInstance(PermissionsRulesFactory.class); + } + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServices.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServices.java new file mode 100644 index 0000000000..09c8102ef0 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServices.java @@ -0,0 +1,26 @@ +package org.openecomp.sdc.itempermissions; + +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; + +import java.util.Collection; +import java.util.Set; + +/** + * Created by ayalaben on 6/22/2017 + */ +public interface PermissionsServices { + + Collection<ItemPermissionsEntity> listItemPermissions(String itemId); + + void updateItemPermissions(String itemId, String permission, Set<String> addedUsersIds, + Set<String> removedUsersIds); + + boolean isAllowed(String itemId,String userId,String action); + + void execute(String itemId,String userId,String action); + + String getUserItemPermiission(String itemId, String userId); + + + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServicesFactory.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServicesFactory.java new file mode 100644 index 0000000000..97769bcc82 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/PermissionsServicesFactory.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.itempermissions; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +/** + * Created by ayalaben on 6/22/2017. + */ +public abstract class PermissionsServicesFactory extends + AbstractComponentFactory<PermissionsServices> { + + public static PermissionsServicesFactory getInstance() { + return AbstractFactory.getInstance(PermissionsServicesFactory.class); + } + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDao.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDao.java new file mode 100644 index 0000000000..a0f51f90bb --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDao.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.itempermissions.dao; + +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; + +import java.util.Collection; +import java.util.Set; + +/** + * Created by ayalaben on 6/18/2017. + */ +public interface ItemPermissionsDao { + + Collection<ItemPermissionsEntity> listItemPermissions(String itemId); + + void updateItemPermissions(String itemId, String permission, Set<String> addedUsersIds, + Set<String> removedUsersIds); + + void addUserPermission(String itemId, String userId, String permission); + + String getUserItemPermiission(String itemId, String userId); +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDaoFactory.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDaoFactory.java new file mode 100644 index 0000000000..95d541e028 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/dao/ItemPermissionsDaoFactory.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.itempermissions.dao; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +/** + * Created by ayalaben on 6/18/2017. + */ +public abstract class ItemPermissionsDaoFactory extends AbstractComponentFactory<ItemPermissionsDao> { + + public static ItemPermissionsDaoFactory getInstance() { + return AbstractFactory.getInstance(ItemPermissionsDaoFactory.class); + } + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessages.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessages.java new file mode 100644 index 0000000000..a3fb9a14a8 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessages.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.itempermissions.errors; + +/** + * Created by ayalaben on 6/28/2017 + */ +public enum PermissionsErrorMessages { + + NO_PERMISSION_FOR_USER("The user is not permitted to edit this item"), + USER_NOT_OWNER_SUBMIT("The user must be the owner to submit the item"), + INVALID_PERMISSION_TYPE("Invalid permission type"), + INVALID_ACTION_TYPE("Invalid action type"); + + private String errorMessage; + + PermissionsErrorMessages(String errorMessage) { + this.errorMessage = errorMessage; + } + + public String getErrorMessage() { + return errorMessage; + } + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessagesBuilder.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessagesBuilder.java new file mode 100644 index 0000000000..f0c13d9cda --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/errors/PermissionsErrorMessagesBuilder.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.itempermissions.errors; + +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; + +/** + * Created by ayalaben on 6/28/2017 + */ +public class PermissionsErrorMessagesBuilder { + public static final String PERMISSIONS_ERROR= "PERMISSIONS_ERROR"; + private final ErrorCode.ErrorCodeBuilder builder = new ErrorCode.ErrorCodeBuilder(); + + /** + * Instantiates a new Submit uncompleted license model error builder. + * + * @param error + */ + public PermissionsErrorMessagesBuilder(PermissionsErrorMessages error) { + builder.withId(PERMISSIONS_ERROR); + builder.withCategory(ErrorCategory.APPLICATION); + builder.withMessage(error.getErrorMessage()); + } + + public ErrorCode build() { + return builder.build(); + } + + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/notifications/NotificationConstants.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/notifications/NotificationConstants.java new file mode 100644 index 0000000000..d4235cd6c6 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/notifications/NotificationConstants.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.itempermissions.notifications; + +/** + * @author avrahamg + * @since July 10, 2017 + */ +public class NotificationConstants { + public static final String PERMISSION_CHANGED= "PermissionChanged"; + public static final String PERMISSION_ITEM = "permission"; + public static final String ITEM_ID_PROP = "itemId"; + public static final String ITEM_NAME_PROP = "itemName"; + public static final String PERMISSION_GRANTED = "granted"; + public static final String PERMISSION_USER = "userId"; +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/type/ItemPermissionsEntity.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/type/ItemPermissionsEntity.java new file mode 100644 index 0000000000..22ff43778c --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-api/src/main/java/org/openecomp/sdc/itempermissions/type/ItemPermissionsEntity.java @@ -0,0 +1,50 @@ +package org.openecomp.sdc.itempermissions.type; + +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; + +/** + * Created by ayalaben on 6/18/2017. + */ + +@Table(keyspace = "dox", name = "item_permissions") +public class ItemPermissionsEntity { + + @PartitionKey + @Column(name = "item_id") + private String itemId; + + @ClusteringColumn + @Column(name = "user_id") + private String userId; + + @Column(name = "permission") + private String permission; + + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getPermission() { + return permission; + } + + public void setPermission(String permission) { + this.permission = permission; + } +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/pom.xml b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/pom.xml new file mode 100644 index 0000000000..a420b23f6e --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/pom.xml @@ -0,0 +1,63 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>..</relativePath> + </parent> + + <artifactId>openecomp-item-permissions-core</artifactId> + + <dependencies> + + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-session-lib</artifactId> + <version>${project.version}</version> + </dependency> + + + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-api</artifactId> + <version>${project.version}</version> + </dependency> + + + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-facade-core</artifactId> + <version>${project.version}</version> + </dependency> + + + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-nosqldb-core</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-notification-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <version>RELEASE</version> + </dependency> + <dependency> + <groupId>org.testng</groupId> + <artifactId>testng</artifactId> + <version>RELEASE</version> + </dependency> + + </dependencies> + +</project>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoFactoryImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoFactoryImpl.java new file mode 100644 index 0000000000..87c0338c25 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoFactoryImpl.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.itempermissions.dao.impl; + + +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDaoFactory; + + +/** + * Created by ayalaben on 6/18/2017. + */ +public class ItemPermissionsDaoFactoryImpl extends ItemPermissionsDaoFactory { + + private static ItemPermissionsDao INSTANCE =new ItemPermissionsDaoImpl(); + + @Override + public ItemPermissionsDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoImpl.java new file mode 100644 index 0000000000..e1a9d1c874 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/ItemPermissionsDaoImpl.java @@ -0,0 +1,66 @@ +package org.openecomp.sdc.itempermissions.dao.impl; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.mapping.Result; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; + +import java.util.Collection; +import java.util.Set; + +/** + * Created by ayalaben on 6/20/2017. + */ +public class ItemPermissionsDaoImpl implements ItemPermissionsDao { + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static ItemPermissionsAccessor accessor = + noSqlDb.getMappingManager().createAccessor(ItemPermissionsAccessor.class); + + @Override + public Collection<ItemPermissionsEntity> listItemPermissions(String itemId) { + return accessor.getItemPermissions(itemId).all(); + } + + @Override + public void updateItemPermissions(String itemId, String permission, Set<String> addedUsersIds, + Set<String> removedUsersIds) { + addedUsersIds.forEach(userId -> accessor.addPermission(itemId,userId,permission)); + removedUsersIds.forEach(userId -> accessor.deletePermission(itemId,userId)); + } + + @Override + public void addUserPermission(String itemId, String userId, String permission){ + accessor.addPermission(itemId,userId,permission); + } + + @Override + public String getUserItemPermiission(String itemId, String userId) { + + ResultSet result = accessor.getUserItemPermission(itemId,userId); + if (result.getAvailableWithoutFetching() < 1) { + return null; + } + return result.one().getString(0); + } + + + @Accessor + interface ItemPermissionsAccessor { + @Query("select * from dox.item_permissions WHERE item_id = ?") + Result<ItemPermissionsEntity> getItemPermissions(String itemId); + + @Query("select permission from dox.item_permissions WHERE item_id = ? AND user_id=?") + ResultSet getUserItemPermission(String itemId,String userId); + + @Query("delete from dox.item_permissions where item_id = ? and user_id = ?") + void deletePermission(String itemId, String userId); + + @Query("insert into dox.item_permissions (item_id,user_id,permission) values (?,?,?)") + void addPermission(String itemId,String userId, String permission); + + } +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImpl.java new file mode 100644 index 0000000000..ae40ea8d97 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImpl.java @@ -0,0 +1,70 @@ +package org.openecomp.sdc.itempermissions.dao.impl; + +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.itempermissions.PermissionsRules; +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; + +import java.util.Collection; +import java.util.Set; + + +/** + * Created by ayalaben on 6/22/2017. + */ +public class PermissionsServicesImpl implements PermissionsServices { + + private ItemPermissionsDao permissionsDao; + + private PermissionsRules permissionsRules; + + private static final String CHANGE_PERMISSIONS = "Change_Item_Permissions"; + + public PermissionsServicesImpl(PermissionsRules permissionsRules, + ItemPermissionsDao permissionsDao) { + this.permissionsDao = permissionsDao; + this.permissionsRules = permissionsRules; + } + + + @Override + public Collection<ItemPermissionsEntity> listItemPermissions(String itemId) { + return permissionsDao.listItemPermissions(itemId); + } + + @Override + public void updateItemPermissions(String itemId, String permission, Set<String> addedUsersIds, + Set<String> removedUsersIds) { + + String currentUserId = SessionContextProviderFactory.getInstance() + .createInterface().get().getUser().getUserId(); + + permissionsRules.executeAction(itemId,currentUserId,CHANGE_PERMISSIONS); + + permissionsRules.updatePermission(itemId,currentUserId,permission,addedUsersIds, + removedUsersIds); + + permissionsDao.updateItemPermissions(itemId, permission, + addedUsersIds, removedUsersIds); + + } + + @Override + public boolean isAllowed(String itemId,String userId,String action) { + + String userPermission = permissionsDao.getUserItemPermiission(itemId,userId); + return permissionsRules.isAllowed(userPermission,action); + } + + @Override + public void execute(String itemId,String userId,String action) { + permissionsRules.executeAction(itemId, userId, action); + } + + @Override + public String getUserItemPermiission(String itemId, String userId) { + return permissionsDao.getUserItemPermiission(itemId,userId); + } + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PrmissionsServicesFactoryImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PrmissionsServicesFactoryImpl.java new file mode 100644 index 0000000000..34532cb384 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/dao/impl/PrmissionsServicesFactoryImpl.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.itempermissions.dao.impl; + +import org.openecomp.sdc.itempermissions.PermissionsRulesFactory; +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.itempermissions.PermissionsServicesFactory; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDaoFactory; + +/** + * Created by ayalaben on 6/22/2017 + */ +public class PrmissionsServicesFactoryImpl extends PermissionsServicesFactory { + + private static final PermissionsServices INSTANCE = + new org.openecomp.sdc.itempermissions.dao.impl.PermissionsServicesImpl(PermissionsRulesFactory.getInstance().createInterface(), + ItemPermissionsDaoFactory.getInstance().createInterface()); + + @Override + public PermissionsServices createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/servlet/PermissionsFilter.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/servlet/PermissionsFilter.java new file mode 100644 index 0000000000..21acc07733 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/java/org/openecomp/sdc/itempermissions/servlet/PermissionsFilter.java @@ -0,0 +1,72 @@ +package org.openecomp.sdc.itempermissions.servlet; + +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.itempermissions.PermissionsServicesFactory; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +/** + * Created by ayalaben on 6/27/2017. + */ +public class PermissionsFilter implements Filter { + + private final PermissionsServices permissionsServices; + public static final String IRRELEVANT_REQUEST = "Irrelevant_Request"; + public static final String EDIT_ITEM = "Edit_Item"; + + public PermissionsFilter() { + this.permissionsServices = PermissionsServicesFactory.getInstance().createInterface(); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, + FilterChain filterChain) throws IOException, ServletException { + + if (servletRequest instanceof HttpServletRequest) { + if (((HttpServletRequest) servletRequest).getMethod().equals("POST") + || ((HttpServletRequest) servletRequest).getMethod().equals("PUT")) { + + String userId = ((HttpServletRequest) servletRequest).getHeader("USER_ID"); + String itemId = parseItemIdFromPath(((HttpServletRequest) servletRequest).getPathInfo()); + if ( ! itemId.equals(IRRELEVANT_REQUEST)) { + if ( ! permissionsServices.isAllowed(itemId,userId,EDIT_ITEM)) { + ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_FORBIDDEN); + servletResponse.getWriter().print("Permissions Error. The user does not have " + + "permission to perform" + + " this action."); + return; + } + } + } + } + + filterChain.doFilter(servletRequest, servletResponse); + } + + private String parseItemIdFromPath(String pathInfo) { + String[] tokens = pathInfo.split("/"); + if (tokens.length < 4) { + return IRRELEVANT_REQUEST; + } else { + return tokens[3]; + } + } + + @Override + public void destroy() { + + } +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..d23948437f --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,4 @@ +{ + "org.openecomp.sdc.itempermissions.dao.ItemPermissionsDaoFactory": "org.openecomp.sdc.itempermissions.dao.impl.ItemPermissionsDaoFactoryImpl", +"org.openecomp.sdc.itempermissions.PermissionsServicesFactory" : "org.openecomp.sdc.itempermissions.dao.impl.PrmissionsServicesFactoryImpl" +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/test/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImplTest.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/test/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImplTest.java new file mode 100644 index 0000000000..0a87c29f50 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-core/src/main/test/java/org/openecomp/sdc/itempermissions/dao/impl/PermissionsServicesImplTest.java @@ -0,0 +1,111 @@ +package org.openecomp.sdc.itempermissions.dao.impl; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.itempermissions.PermissionsRules; +import org.openecomp.sdc.itempermissions.dao.ItemPermissionsDao; +import org.openecomp.sdc.itempermissions.type.ItemPermissionsEntity; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Created by ayalaben on 7/9/2017 + */ +public class PermissionsServicesImplTest { + + private static final String ITEM1_ID = "1"; + private static final String PERMISSION = "Owner"; + private static final String USER2_ID = "testUser2"; + private static final String USER1_ID = "testUser1"; + private static final String ACTION_SUBMIT = "Submit_Item"; + private static final String CHANGE_PERMISSIONS = "Change_Item_Permissions"; + + static { + SessionContextProviderFactory.getInstance().createInterface().create("testUser1"); + } + + @Mock + private ItemPermissionsDao permissionsDaoMock; + @Mock + private PermissionsRules permissionsRules; + @InjectMocks + @Spy + private PermissionsServicesImpl permissionsServices; + + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testListItemPermissionsWhenNone() { + Collection<ItemPermissionsEntity> permissions = + permissionsServices.listItemPermissions(ITEM1_ID); + Assert.assertEquals(permissions.size(), 0); + } + + + @Test + public void testListItemPermissions(){ + doReturn(Arrays.asList( + createPermissionEntity(ITEM1_ID, USER1_ID, PERMISSION), + createPermissionEntity(ITEM1_ID, USER2_ID, PERMISSION))) + .when(permissionsDaoMock).listItemPermissions(anyObject()); + + Collection<ItemPermissionsEntity> actual = + permissionsServices.listItemPermissions(ITEM1_ID); + Assert.assertEquals(actual.size(), 2); + } + + + @Test + public void testIsAllowed(){ + when(permissionsDaoMock.getUserItemPermiission(ITEM1_ID,USER1_ID)).thenReturn(PERMISSION); + when(permissionsRules.isAllowed(PERMISSION,ACTION_SUBMIT)).thenReturn(true); + + Boolean result = permissionsServices.isAllowed(ITEM1_ID,USER1_ID,ACTION_SUBMIT); + + Assert.assertTrue(result); + + } + @Test + public void testUpdatePermissions(){ + + Set<String> addedUsers = new HashSet<String>(); + addedUsers.add(USER2_ID); + + permissionsServices.updateItemPermissions(ITEM1_ID,PERMISSION,addedUsers, + new HashSet<String>()); + + verify(permissionsRules).executeAction(ITEM1_ID,USER1_ID,CHANGE_PERMISSIONS); + verify(permissionsRules).updatePermission(ITEM1_ID,USER1_ID,PERMISSION,addedUsers,new HashSet<String>()); + verify(permissionsDaoMock).updateItemPermissions(ITEM1_ID,PERMISSION,addedUsers,new + HashSet<String>()); + } + + + public static ItemPermissionsEntity createPermissionEntity(String itemId, String + userId, String permission) { + ItemPermissionsEntity permissionsEntity = new ItemPermissionsEntity(); + permissionsEntity.setItemId(itemId); + permissionsEntity.setUserId(userId); + permissionsEntity.setPermission(permission); + return permissionsEntity; + } + +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/pom.xml b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/pom.xml new file mode 100644 index 0000000000..0a3bf6eb9d --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/pom.xml @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>..</relativePath> + </parent> + <artifactId>openecomp-item-permissions-impl</artifactId> + <dependencies> + + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-core</artifactId> + <version>${project.version}</version> + <scope>runtime</scope> + </dependency> + </dependencies> +</project>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesFactoryImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesFactoryImpl.java new file mode 100644 index 0000000000..c74907ce03 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesFactoryImpl.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.itempermissions.impl; + +import org.openecomp.sdc.itempermissions.PermissionsRules; +import org.openecomp.sdc.itempermissions.PermissionsRulesFactory; + +/** + * Created by ayalaben on 6/26/2017. + */ +public class PermissionsRulesFactoryImpl extends PermissionsRulesFactory { + + @Override + public PermissionsRules createInterface() { + return new PermissionsRulesImpl(); + } + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImpl.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImpl.java new file mode 100644 index 0000000000..22d81a73dc --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImpl.java @@ -0,0 +1,126 @@ +package org.openecomp.sdc.itempermissions.impl; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.itempermissions.PermissionsRules; +import org.openecomp.sdc.itempermissions.PermissionsServicesFactory; +import org.openecomp.sdc.itempermissions.errors.PermissionsErrorMessagesBuilder; +import org.openecomp.sdc.itempermissions.impl.types.PermissionActionTypes; +import org.openecomp.sdc.itempermissions.impl.types.PermissionTypes; + +import java.util.HashSet; +import java.util.Set; + +import static org.openecomp.sdc.itempermissions.errors.PermissionsErrorMessages.INVALID_ACTION_TYPE; +import static org.openecomp.sdc.itempermissions.errors.PermissionsErrorMessages.INVALID_PERMISSION_TYPE; + +/** + * Created by ayalaben on 6/26/2017. + */ +public class PermissionsRulesImpl implements PermissionsRules { + + + @Override + public boolean isAllowed(String permission, String action) { + + if (permission == null) { + return false; + } + try { + PermissionTypes.valueOf(permission); + } catch (IllegalArgumentException ex) { + throw new CoreException(new PermissionsErrorMessagesBuilder(INVALID_PERMISSION_TYPE).build()); + } + + try { + switch (PermissionActionTypes.valueOf(action)) { + case Create_Item: + return true; + + case Edit_Item: + if (permission.equals(PermissionTypes.Contributor.name()) || permission.equals + (PermissionTypes.Owner.name())) { + return true; + } + break; + case Commit_Item: + if (permission.equals(PermissionTypes.Contributor.name()) || permission.equals + (PermissionTypes.Owner.name())) { + return true; + } + break; + + case Change_Item_Permissions: + if (permission.equals(PermissionTypes.Owner.name())) { + return true; + } + break; + + case Submit_Item: + if (permission.equals(PermissionTypes.Owner.name())) { + return true; + } + break; + + default: + return false; + } + } catch (IllegalArgumentException ex) { + throw new CoreException(new PermissionsErrorMessagesBuilder(INVALID_ACTION_TYPE).build()); + } + + return false; + } + + @Override + public void executeAction(String itemId, String userId, String action) { + try { + switch (PermissionActionTypes.valueOf(action)) { + case Create_Item: + caseCreateItem(userId,itemId); + break; + + case Change_Item_Permissions: + break; + + case Edit_Item: + break; + + case Submit_Item: + break; + + default: + } + } catch (IllegalArgumentException ex) { + throw new CoreException(new PermissionsErrorMessagesBuilder(INVALID_ACTION_TYPE).build()); + } + } + + @Override + public void updatePermission(String itemId,String currentUserId, String permission, Set<String> + addedUsersIds,Set<String> removedUsersIds) { + try { + PermissionTypes.valueOf(permission); + } catch (IllegalArgumentException ex) { + throw new CoreException(new PermissionsErrorMessagesBuilder(INVALID_PERMISSION_TYPE).build()); + } + + if (permission.equals(PermissionTypes.Owner.name())) { + + HashSet<String> currentOwner = new HashSet<String>(); + currentOwner.add(currentUserId); + + PermissionsServicesFactory.getInstance().createInterface() + .updateItemPermissions(itemId,PermissionTypes.Contributor.name(), + currentOwner,new HashSet<String>()); + } + } + + protected void caseCreateItem(String userId,String itemId) { + HashSet<String> ownerId = new HashSet<String>(); + ownerId.add(userId); + PermissionsServicesFactory.getInstance().createInterface() + .updateItemPermissions(itemId, PermissionTypes.Owner.name(), ownerId, + new HashSet<String>()); + } + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionActionTypes.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionActionTypes.java new file mode 100644 index 0000000000..3d1b8a82d7 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionActionTypes.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.itempermissions.impl.types; + +/** + * Created by ayalaben on 6/26/2017 + */ +public enum PermissionActionTypes { + + Create_Item, + Change_Item_Permissions, + Edit_Item, + Commit_Item, + Submit_Item; + +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionTypes.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionTypes.java new file mode 100644 index 0000000000..e3c93c5e6e --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/java/org/openecomp/sdc/itempermissions/impl/types/PermissionTypes.java @@ -0,0 +1,9 @@ +package org.openecomp.sdc.itempermissions.impl.types; + +/** + * Created by ayalaben on 6/26/2017. + */ +public enum PermissionTypes { + Owner, + Contributor +} diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..a3d3dae5c5 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.sdc.itempermissions.PermissionsRulesFactory": "org.openecomp.sdc.itempermissions.impl.PermissionsRulesFactoryImpl" +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImplTest.java b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImplTest.java new file mode 100644 index 0000000000..635a0b2a25 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/java/org/openecomp/sdc/itempermissions/impl/PermissionsRulesImplTest.java @@ -0,0 +1,101 @@ +package org.openecomp.sdc.itempermissions.impl; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.itempermissions.dao.impl.PermissionsServicesImpl; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.HashSet; + + +/** + * Created by ayalaben on 7/10/2017 + */ +public class PermissionsRulesImplTest { + + private static final String ITEM1_ID = "1"; + private static final String USER1_ID = "testUser1"; + private static final String PERMISSION_OWNER = "Owner"; + private static final String PERMISSION_CONTRIBUTOR = "Contributor"; + private static final String INVALID_PERMISSION = "Invalid_Permission"; + private static final String SUBMIT_ACTION = "Submit_Item"; + private static final String EDIT_ACTION = "Edit_Item"; + private static final String CHANGE_PERMISSIONS_ACTION = "Change_Item_Permissions"; + private static final String INVALID_ACTION = "Invalid_Action"; + + @Mock + private PermissionsServicesImpl permissionsServices; + + @InjectMocks + @Spy + private PermissionsRulesImpl permissionsRules; + + + @BeforeMethod + public void setUp() throws Exception { + + MockitoAnnotations.initMocks(this); + } + + @Test(expectedExceptions = CoreException.class,expectedExceptionsMessageRegExp = + "Invalid permission type") + public void testIsAllowedWhenInvalidPermission() { + permissionsRules.isAllowed(INVALID_PERMISSION, EDIT_ACTION); + } + + @Test(expectedExceptions = CoreException.class,expectedExceptionsMessageRegExp = + "Invalid action type") + public void testIsAllowedWhenInvalidAction() { + permissionsRules.isAllowed(PERMISSION_CONTRIBUTOR, INVALID_ACTION); + } + + @Test + public void testIsAllowedCaseSubmitOwner(){ + Assert.assertTrue(permissionsRules.isAllowed(PERMISSION_OWNER,SUBMIT_ACTION)); + } + + @Test + public void testIsAllowedCaseSubmitNotOwner(){ + Assert.assertFalse(permissionsRules.isAllowed(PERMISSION_CONTRIBUTOR,SUBMIT_ACTION)); + } + + @Test + public void testIsAllowedCaseEditOwner(){ + Assert.assertTrue(permissionsRules.isAllowed(PERMISSION_OWNER,EDIT_ACTION)); + } + + @Test + public void testIsAllowedCaseEditContributer(){ + Assert.assertTrue(permissionsRules.isAllowed(PERMISSION_CONTRIBUTOR,EDIT_ACTION)); + } + + @Test + public void testIsAllowedCaseChangePermissionsContributer(){ + Assert.assertFalse(permissionsRules.isAllowed(PERMISSION_CONTRIBUTOR,CHANGE_PERMISSIONS_ACTION)); + } + + @Test + public void testIsAllowedCaseChangePermissionsOwner(){ + Assert.assertTrue(permissionsRules.isAllowed(PERMISSION_OWNER,CHANGE_PERMISSIONS_ACTION)); + } + + @Test(expectedExceptions = CoreException.class,expectedExceptionsMessageRegExp = + "Invalid permission type") + public void testUpdatePermissionWhenInvalidPermission() { + permissionsRules.updatePermission(ITEM1_ID,USER1_ID,INVALID_PERMISSION,new HashSet<String>(), + new HashSet<String>()); + } + + @Test(expectedExceptions = CoreException.class,expectedExceptionsMessageRegExp = + "Invalid action type") + public void testExecuteActionInvalidAction(){ + permissionsRules.executeAction(ITEM1_ID,USER1_ID,INVALID_ACTION); + } + + +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/resources/logback.xml b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/resources/logback.xml new file mode 100644 index 0000000000..c1932e31e8 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/openecomp-item-permissions-impl/src/test/resources/logback.xml @@ -0,0 +1,15 @@ +<configuration> + + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <!-- encoders are assigned the type + ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> + <encoder> + <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> + </encoder> + </appender> + + <root level="warn"> + <appender-ref ref="STDOUT" /> + </root> + +</configuration>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-item-permissions-lib/pom.xml b/openecomp-be/lib/openecomp-item-permissions-lib/pom.xml new file mode 100644 index 0000000000..fbf8ca5ab4 --- /dev/null +++ b/openecomp-be/lib/openecomp-item-permissions-lib/pom.xml @@ -0,0 +1,24 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <artifactId>openecomp-sdc-lib</artifactId> + <groupId>org.openecomp.sdc</groupId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>..</relativePath> + </parent> + + <artifactId>openecomp-item-permissions-lib</artifactId> + <packaging>pom</packaging> + + + <modules> + <module>openecomp-item-permissions-api</module> + <module>openecomp-item-permissions-impl</module> + <module>openecomp-item-permissions-core</module> + </modules> + +</project>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionMapper.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionMapper.java index 98e1c6938a..9ca574a3da 100644 --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionMapper.java +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/errors/ActionExceptionMapper.java @@ -20,6 +20,10 @@ package org.openecomp.sdc.action.errors; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + import static org.openecomp.sdc.action.ActionConstants.WWW_AUTHENTICATE_HEADER_PARAM; import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_ALREADY_EXISTS_CODE; import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_CHECKSUM_ERROR_CODE; @@ -60,10 +64,6 @@ import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_NOT_ALLOWED_FOR_NAME; import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_UPDATE_ON_UNLOCKED_ENTITY; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.ext.ExceptionMapper; - /** * Mapper class to map Action Library exceptions to corresponding HTTP Response objects. */ diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/util/ActionUtil.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/util/ActionUtil.java index 0315a31a70..820fb86e79 100644 --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/util/ActionUtil.java +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-api/src/main/java/org/openecomp/sdc/action/util/ActionUtil.java @@ -20,6 +20,18 @@ package org.openecomp.sdc.action.util; +import org.openecomp.sdc.action.logging.CategoryLogLevel; +import org.openecomp.sdc.action.logging.StatusCode; +import org.openecomp.sdc.action.types.ActionLogResponseCode; +import org.openecomp.sdc.action.types.ActionSubOperation; +import org.slf4j.MDC; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.ZoneOffset; +import java.util.Date; +import java.util.TimeZone; + import static org.openecomp.sdc.action.ActionConstants.BEGIN_TIMESTAMP; import static org.openecomp.sdc.action.ActionConstants.ELAPSED_TIME; import static org.openecomp.sdc.action.ActionConstants.END_TIMESTAMP; @@ -104,18 +116,6 @@ import static org.openecomp.sdc.action.types.ActionLogResponseCode.UPDATE_NOT_AL import static org.openecomp.sdc.action.types.ActionLogResponseCode.UPDATE_ON_LOCKED_ENTITY; import static org.openecomp.sdc.action.types.ActionLogResponseCode.UPDATE_ON_UNLOCKED_ENTITY; -import org.openecomp.sdc.action.logging.CategoryLogLevel; -import org.openecomp.sdc.action.logging.StatusCode; -import org.openecomp.sdc.action.types.ActionLogResponseCode; -import org.openecomp.sdc.action.types.ActionSubOperation; -import org.slf4j.MDC; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.time.ZoneOffset; -import java.util.Date; -import java.util.TimeZone; - public class ActionUtil { private static final String UTC_DATE_FORMAT = "dd MMM yyyy kk:mm:ss z"; diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoImpl.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoImpl.java index bfa5830b8d..27f0438f4e 100644 --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionArtifactDaoImpl.java @@ -20,20 +20,12 @@ package org.openecomp.sdc.action.dao.impl; -import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY_DB; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_MSG; - import com.datastax.driver.core.exceptions.NoHostAvailableException; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; import org.openecomp.core.dao.impl.CassandraBaseDao; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.action.dao.ActionArtifactDao; @@ -44,10 +36,18 @@ import org.openecomp.sdc.action.logging.StatusCode; import org.openecomp.sdc.action.types.ActionArtifact; import org.openecomp.sdc.action.types.ActionSubOperation; import org.openecomp.sdc.action.util.ActionUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import java.util.Collection; import java.util.List; +import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY_DB; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_MSG; + public class ActionArtifactDaoImpl extends CassandraBaseDao<ActionArtifactEntity> implements ActionArtifactDao { diff --git a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoImpl.java b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoImpl.java index b7f4b5c926..a79687f9a4 100644 --- a/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-action-lib/openecomp-sdc-action-core/src/main/java/org/openecomp/sdc/action/dao/impl/ActionDaoImpl.java @@ -20,30 +20,6 @@ package org.openecomp.sdc.action.dao.impl; -import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; -import static com.datastax.driver.core.querybuilder.QueryBuilder.in; -import static com.datastax.driver.core.querybuilder.QueryBuilder.set; -import static org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory.getSession; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_CATEGORY; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_OPEN_ECOMP_COMPONENT; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_MODEL; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NAME; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NONE; -import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_VENDOR; -import static org.openecomp.sdc.action.ActionConstants.STATUS; -import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY; -import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY_DB; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_MSG; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_CODE; -import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_MSG; - import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.Statement; @@ -56,8 +32,6 @@ import com.datastax.driver.mapping.UDTMapper; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; import org.openecomp.core.dao.impl.CassandraBaseDao; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.core.utilities.json.JsonUtil; @@ -73,6 +47,8 @@ import org.openecomp.sdc.action.types.ActionStatus; import org.openecomp.sdc.action.types.ActionSubOperation; import org.openecomp.sdc.action.types.OpenEcompComponent; import org.openecomp.sdc.action.util.ActionUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.dao.VersionInfoDao; import org.openecomp.sdc.versioning.dao.VersionInfoDaoFactory; @@ -93,6 +69,30 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import static com.datastax.driver.core.querybuilder.QueryBuilder.eq; +import static com.datastax.driver.core.querybuilder.QueryBuilder.in; +import static com.datastax.driver.core.querybuilder.QueryBuilder.set; +import static org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory.getSession; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_CATEGORY; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_MODEL; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NAME; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_NONE; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_OPEN_ECOMP_COMPONENT; +import static org.openecomp.sdc.action.ActionConstants.FILTER_TYPE_VENDOR; +import static org.openecomp.sdc.action.ActionConstants.STATUS; +import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY; +import static org.openecomp.sdc.action.ActionConstants.TARGET_ENTITY_DB; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ARTIFACT_DEL_LOCKED_OTHER_USER_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_INTERNAL_SERVER_ERROR_MSG; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_ENTITY_NOT_EXIST_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_INTERNAL_SERVER_ERR_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_NOT_LOCKED_MSG; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_CODE; +import static org.openecomp.sdc.action.errors.ActionErrorConstants.ACTION_QUERY_FAILURE_MSG; + public class ActionDaoImpl extends CassandraBaseDao<ActionEntity> implements ActionDao { private static NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDao.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDao.java index 9804bfc3c5..6ca1010a2d 100644 --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDao.java +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDao.java @@ -18,10 +18,6 @@ package org.openecomp.sdc.activitylog.dao; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.util.Collection; public interface ActivityLogDao extends BaseDao<ActivityLogEntity> { - Collection<ActivityLogEntity> getActivityLogListForItem(String itemId, String versionId); } diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDaoFactory.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDaoFactory.java index d3ac277d58..1fc7de7cbc 100644 --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDaoFactory.java +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/ActivityLogDaoFactory.java @@ -15,8 +15,8 @@ */ package org.openecomp.sdc.activitylog.dao; -import org.openecomp.core.factory.api.AbstractFactory; import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; public abstract class ActivityLogDaoFactory extends AbstractComponentFactory<ActivityLogDao> { diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityLogEntity.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityLogEntity.java index e84a2be40a..36a4bbcbfd 100644 --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityLogEntity.java +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityLogEntity.java @@ -16,107 +16,130 @@ package org.openecomp.sdc.activitylog.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Enumerated; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Calendar; import java.util.Date; @Table(keyspace = "dox", name = "activity_log") public class ActivityLogEntity { - @PartitionKey - @Column(name = "item_id") - private String itemId; - @ClusteringColumn(value = 1) - @Column(name = "version_id") - private String versionId; - @ClusteringColumn - @Column(name = "activity_id") - private String id; - private String type; - private String user; - private Date timestamp; - private boolean success; - private String message; - private String comment; - - public ActivityLogEntity() {} - - public ActivityLogEntity(String itemId, String versionId, String type, String user, boolean success, String message, String comment) { - this.itemId = itemId; - this.versionId = versionId; - this.type = type; - this.user = user; - this.success = success; - this.message = message; - this.comment = comment; - Calendar now = Calendar.getInstance(); - this.timestamp = now.getTime(); - } - - public String getItemId() { return itemId; } - - public void setItemId(String itemId) { - this.itemId = itemId; - } - - public String getVersionId() { - return versionId; - } - - public void setVersionId(String versionId) { - this.versionId = versionId; - } - - public String getId() { return id; } - - public void setId(String id) { this.id = id; } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public Date getTimestamp() { - return timestamp; - } - - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } + @PartitionKey + @Column(name = "item_id") + private String itemId; + @ClusteringColumn(value = 1) + @Column(name = "version_id") + private String versionId; + @ClusteringColumn + @Column(name = "activity_id") + private String id; + @Enumerated + private ActivityType type; + private String user; + private Date timestamp; + private boolean success; + private String message; + private String comment; + + public ActivityLogEntity() { + } + + public ActivityLogEntity(String itemId, Version version) { + this.itemId = itemId; + setVersion(version); + } + + public ActivityLogEntity(String itemId, Version version, ActivityType type, String user, + boolean success, String message, String comment) { + this(itemId, version); + this.type = type; + this.user = user; + this.success = success; + this.message = message; + this.comment = comment; + this.timestamp = new Date(); + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public Version getVersion() { + return versionId == null ? null : new Version(versionId); + } + + public void setVersion(Version version) { + this.versionId = version == null ? null : version.getId(); + } + + public String getVersionId() { + return versionId; + } + + public void setVersionId(String versionId) { + this.versionId = versionId; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public ActivityType getType() { + return type; + } + + public void setType(ActivityType type) { + this.type = type; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public Date getTimestamp() { + return timestamp; + } + + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public String getComment() { + return comment; + } + + public void setComment(String comment) { + this.comment = comment; + } } diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityType.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityType.java new file mode 100644 index 0000000000..620113e2b5 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-api/src/main/java/org/openecomp/sdc/activitylog/dao/type/ActivityType.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.activitylog.dao.type; + +public enum ActivityType { + Create, + Create_Version, + Commit, + Submit, + Upload_Artifact, + Upload_Network_Package, + Revert, + Reset + +} diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoCassandraImpl.java index 5772cc16b7..85e0afa90f 100644 --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoCassandraImpl.java +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoCassandraImpl.java @@ -26,58 +26,34 @@ import org.openecomp.sdc.activitylog.dao.ActivityLogDao; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import java.util.Collection; -import java.util.Date; -public class ActivityLogDaoCassandraImpl extends CassandraBaseDao<ActivityLogEntity> implements ActivityLogDao{ - private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); - private static final Mapper<ActivityLogEntity> mapper = - noSqlDb.getMappingManager().mapper(ActivityLogEntity.class); - private static final ActivityLogAccessor accessor = - noSqlDb.getMappingManager().createAccessor(ActivityLogAccessor.class); - - @Override - protected Mapper<ActivityLogEntity> getMapper() { - return mapper; - } - - @Override - protected Object[] getKeys(ActivityLogEntity entity) { - return new Object[0]; - } - - @Override - public Collection<ActivityLogEntity> list(ActivityLogEntity entity) { - return accessor.list().all(); - } - - @Override - public void create(ActivityLogEntity activityLogEntity) { - accessor.create(activityLogEntity.getItemId(), activityLogEntity.getVersionId(),activityLogEntity.getId(), - activityLogEntity.getType(),activityLogEntity.getUser(), activityLogEntity.getTimestamp(), activityLogEntity.isSuccess(), - activityLogEntity.getMessage(), activityLogEntity.getComment()); - } - - @Override - public Collection<ActivityLogEntity> getActivityLogListForItem(String itemId, String versionId) { - return accessor.getForItem(itemId, versionId).all(); - } - - - @Accessor - interface ActivityLogAccessor { - @Query("select item_id, version_id, activity_id, type, user, timestamp, success, message, comment" - + " from activity_log") - Result<ActivityLogEntity> list(); - - @Query("select item_id, version_id, activity_id, type, user, timestamp, success, message, comment" - + " from activity_log where item_id=? and version_id=?") - Result<ActivityLogEntity> getForItem(String itemId, String versionId); - - @Query("insert into activity_log " + - " (item_id, version_id, activity_id, type, user, timestamp, success, message, comment)" + - " values (?,?,?,?,?,?,?,?,?)") - Result<ActivityLogEntity> create(String itemId, String versionId, String id, String type, - String user, Date timestamp, boolean success, - String message, String comment); - } +public class ActivityLogDaoCassandraImpl extends CassandraBaseDao<ActivityLogEntity> + implements ActivityLogDao { + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper<ActivityLogEntity> mapper = + noSqlDb.getMappingManager().mapper(ActivityLogEntity.class); + private static final ActivityLogAccessor accessor = + noSqlDb.getMappingManager().createAccessor(ActivityLogAccessor.class); + + @Override + protected Mapper<ActivityLogEntity> getMapper() { + return mapper; + } + + @Override + protected Object[] getKeys(ActivityLogEntity entity) { + return new Object[]{entity.getItemId(), entity.getVersionId(), entity.getId()}; + } + + @Override + public Collection<ActivityLogEntity> list(ActivityLogEntity entity) { + return accessor.listByItemVersion(entity.getItemId(), entity.getVersionId()).all(); + } + + @Accessor + interface ActivityLogAccessor { + + @Query("select * from activity_log where item_id=? and version_id=?") + Result<ActivityLogEntity> listByItemVersion(String itemId, String versionId); + } } diff --git a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoFactoryImpl.java index 98e4cc2ed2..02c8a71b0e 100644 --- a/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-activity-log-lib/openecomp-sdc-activity-log-core/src/main/java/org/openecomp/sdc/activitylog/dao/impl/ActivityLogDaoFactoryImpl.java @@ -19,10 +19,10 @@ import org.openecomp.sdc.activitylog.dao.ActivityLogDao; import org.openecomp.sdc.activitylog.dao.ActivityLogDaoFactory; public class ActivityLogDaoFactoryImpl extends ActivityLogDaoFactory { - private static final ActivityLogDao INSTANCE = new ActivityLogDaoCassandraImpl(); + private static final ActivityLogDao INSTANCE = new ActivityLogDaoCassandraImpl(); - @Override - public ActivityLogDao createInterface() { - return INSTANCE; - } + @Override + public ActivityLogDao createInterface() { + return INSTANCE; + } } diff --git a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ElementType.java b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ElementType.java new file mode 100644 index 0000000000..19d5656036 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ElementType.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.datatypes.model; + +public enum ElementType { + itemVersion, + + VendorLicenseModel, + LicenseAgreements, LicenseAgreement, + FeatureGroups, FeatureGroup, + LicenseKeyGroups, LicenseKeyGroup, + EntitlementPools, EntitlementPool, + Limits, Limit, + + VendorSoftwareProduct, + VSPQuestionnaire, + + VspModel, NetworkPackage, + OrchestrationTemplateCandidate, OrchestrationTemplateCandidateContent, + // todo - remove OrchestrationTemplateContent + OrchestrationTemplate, OrchestrationTemplateValidationData, OrchestrationTemplateContent, + Networks, Network, + Components, Component, ComponentQuestionnaire, ComponentDependencies, ComponentDependency, + Nics, Nic, NicQuestionnaire, + Mibs, SNMP_POLL, SNMP_TRAP, VES_EVENTS, + Processes, Process, + DeploymentFlavors, DeploymentFlavor, + Computes, Compute, ComputeQuestionnaire, + Images, Image, ImageQuestionnaire, + ServiceModel, EnrichedServiceModel, ServiceTemplate, Templates, Artifact, Artifacts, + + test +} diff --git a/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ItemType.java b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ItemType.java new file mode 100644 index 0000000000..892351ac4d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-datatypes-lib/src/main/java/org/openecomp/sdc/datatypes/model/ItemType.java @@ -0,0 +1,6 @@ +package org.openecomp.sdc.datatypes.model; + +public enum ItemType { + vlm, + vsp +} diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImpl.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImpl.java index 06b157b92c..6610ec5f86 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/main/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImpl.java @@ -22,12 +22,12 @@ package org.openecomp.sdc.enrichment.impl; import org.openecomp.core.enrichment.api.EnrichmentManager; import org.openecomp.core.enrichment.types.EntityInfo; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.enrichment.EnrichmentInfo; import org.openecomp.sdc.enrichment.factory.EnricherHandlerFactory; import org.openecomp.sdc.enrichment.inter.Enricher; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.versioning.dao.types.Version; diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/test/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImplTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/test/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImplTest.java index 1b9e119fbf..acd25dd7bc 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/test/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-core/src/test/java/org/openecomp/sdc/enrichment/impl/EnrichmentManagerImplTest.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.enrichment.impl; -import static org.junit.Assert.assertEquals; - import org.openecomp.core.enrichment.factory.EnrichmentManagerFactory; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.logging.api.Logger; @@ -50,6 +48,8 @@ import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import static org.junit.Assert.assertEquals; + public class EnrichmentManagerImplTest { diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerImpl.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerImpl.java index a5eeece2b3..c9d89ee38f 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/EnricherHandlerImpl.java @@ -20,12 +20,12 @@ package org.openecomp.sdc.enrichment.impl; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.enrichment.impl.external.artifact.ExternalArtifactEnricher; import org.openecomp.sdc.enrichment.impl.tosca.ToscaEnricher; import org.openecomp.sdc.enrichment.inter.Enricher; import org.openecomp.sdc.enrichment.inter.EnricherHandler; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import java.util.ArrayList; import java.util.List; diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java index a5f6529bbb..828de7244c 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricher.java @@ -10,10 +10,10 @@ import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.enrichment.EnrichmentInfo; import org.openecomp.sdc.enrichment.inter.ExternalArtifactEnricherInterface; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessType; @@ -28,7 +28,7 @@ import java.util.Map; public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterface { - private VendorSoftwareProductDao vendorSoftwareProductDao; + private ComponentDao componentDao; //private ProcessArtifactDao processArtifactDao; private ProcessDao processDao; private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @@ -41,10 +41,9 @@ public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterfac Version version = enrichmentInfo.getVersion(); Collection<ComponentEntity> components = - getVendorSoftwareProductDao().listComponents(vspId, version); - components.stream() - .forEach(componentEntry -> errors.putAll(enrichComponent(componentEntry, - vspId, version))); + getComponentDao().list(new ComponentEntity(vspId, version, null)); + components.forEach(componentEntry -> errors.putAll(enrichComponent(componentEntry, + vspId, version))); return errors; } @@ -79,10 +78,9 @@ public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterfac ProcessArtifactEntity artifactEntity = new ProcessArtifactEntity(vspId, version, componentId, entity.getId());*/ - processes.stream() - .forEach(entity -> { - ProcessEntity artifactEntity = new ProcessEntity(vspId, version, - componentId, entity.getId()); + processes.forEach(entity -> { + ProcessEntity artifactEntity = new ProcessEntity(vspId, version, + componentId, entity.getId()); ProcessEntity artifactProcessEntity = getProcessDao().get(artifactEntity); //ProcessArtifactEntity artifact = getProcessArtifactDao().get(artifactEntity); @@ -105,7 +103,7 @@ public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterfac } }); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } void enrichServiceArtifact(ComponentProcessInfo componentProcessInfo, @@ -113,19 +111,19 @@ public class ProcessArtifactEnricher implements ExternalArtifactEnricherInterfac Map<String, List<ErrorMessage>> errors) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); processServiceArtifact.setName(componentProcessInfo.getName()); processServiceArtifact.setContentData(FileUtils.toByteArray(componentProcessInfo.getContent())); getEnrichedServiceModelDao().storeExternalArtifact(processServiceArtifact); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } - private VendorSoftwareProductDao getVendorSoftwareProductDao() { - if (vendorSoftwareProductDao == null) { - vendorSoftwareProductDao = VendorSoftwareProductDaoFactory.getInstance().createInterface(); + private ComponentDao getComponentDao() { + if (componentDao == null) { + componentDao = ComponentDaoFactory.getInstance().createInterface(); } - return vendorSoftwareProductDao; + return componentDao; } private ProcessDao getProcessDao() { diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/VspInformationArtifactEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/VspInformationArtifactEnricher.java index b7da22bdfb..9e46a5c33d 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/VspInformationArtifactEnricher.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/external/artifact/VspInformationArtifactEnricher.java @@ -32,8 +32,6 @@ import org.openecomp.sdc.enrichment.EnrichmentInfo; import org.openecomp.sdc.enrichment.inter.ExternalArtifactEnricherInterface; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; @@ -61,8 +59,6 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI EnrichedServiceModelDaoFactory.getInstance().createInterface(); private VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory .getInstance().createInterface(); - private OrchestrationTemplateDao orchestrationTemplateDataDao = - OrchestrationTemplateDaoFactory.getInstance().createInterface(); public VspInformationArtifactEnricher() { } @@ -81,7 +77,7 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI throws IOException { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Map<String, List<ErrorMessage>> errors = new HashMap<>(); ByteBuffer infoArtifactByteBuffer = ByteBuffer.wrap(informationArtifactGenerator.generate( @@ -94,13 +90,13 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI vspId, version.toString()))); //TODO: add error to map (what is the key?) - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return errors; } enrichInformationArtifact(vspId, version, infoArtifactByteBuffer); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return errors; } @@ -108,10 +104,7 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI ByteBuffer infoArtifactByteBuffer) { ServiceArtifact infoArtifactServiceArtifact = new ServiceArtifact(); - VspDetails vspDetails = getVspDetails(vspId, version); - - String vspName = vspDetails.getName(); - + String vspName = vspInfoDao.get(new VspDetails(vspId, version)).getName(); infoArtifactServiceArtifact.setVspId(vspId); infoArtifactServiceArtifact.setVersion(version); @@ -126,9 +119,5 @@ public class VspInformationArtifactEnricher implements ExternalArtifactEnricherI enrichedServiceModelDao.storeExternalArtifact(infoArtifactServiceArtifact); } - public VspDetails getVspDetails(String vspId,Version version){ - VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId,version)); - vspDetails.setValidationData(orchestrationTemplateDataDao.getValidationData(vspId,version)); - return vspDetails; - } + } diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireData.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireData.java index f49c53d79b..9ebe9e5e67 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireData.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireData.java @@ -26,36 +26,35 @@ import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MIN_INS import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VFC_NAMING_CODE; - public class ComponentQuestionnaireData { ComponentDao componentDao = ComponentDaoFactory.getInstance().createInterface(); - ComponentDependencyModelDao componentDependencyModelDao = ComponentDependencyModelDaoFactory.getInstance() - .createInterface(); + ComponentDependencyModelDao componentDependencyModelDao = + ComponentDependencyModelDaoFactory.getInstance().createInterface(); - private Map<String,String> sourceToTargetComponent; + private Map<String, String> sourceToTargetComponent; - public Map<String,String> getSourceToTargetComponent() { + public Map<String, String> getSourceToTargetComponent() { return sourceToTargetComponent; } - public void setSourceToTargetComponent(Map<String,String> sourceToTargetComponent) { + public void setSourceToTargetComponent(Map<String, String> sourceToTargetComponent) { this.sourceToTargetComponent = sourceToTargetComponent; } public Map<String, Map<String, Object>> getPropertiesfromCompQuestionnaire(String key, Version version) { - Map<String, Map<String,Object>> componentProperties = - new HashMap<String, Map<String,Object>>(); + Map<String, Map<String, Object>> componentProperties = + new HashMap<String, Map<String, Object>>(); ComponentEntity entity = new ComponentEntity(key, version, null); final Collection<ComponentEntity> componentEntities = componentDao.listCompositionAndQuestionnaire(key, version); - Map<String,String> sourceToTarget = new HashMap<String, String>(); + Map<String, String> sourceToTarget = new HashMap<>(); for (ComponentEntity component : componentEntities) { - Map<String, Object> questionnaireParams = new HashMap<String, Object>(); + Map<String, Object> questionnaireParams = new HashMap<>(); final ComponentQuestionnaire componentQuestionnaire = JsonUtil.json2Object(component.getQuestionnaireData(), ComponentQuestionnaire.class); @@ -77,7 +76,7 @@ public class ComponentQuestionnaireData { questionnaireParams.put(EnrichmentConstants.VFC_FUNCTION, vfcDescription); - if (componentQuestionnaire.getHighAvailabilityAndLoadBalancing() != null ) { + if (componentQuestionnaire.getHighAvailabilityAndLoadBalancing() != null) { String mandatory = componentQuestionnaire.getHighAvailabilityAndLoadBalancing() .getIsComponentMandatory(); questionnaireParams.put(MANDATORY, mandatory); @@ -91,19 +90,20 @@ public class ComponentQuestionnaireData { final Integer maxVms = componentQuestionnaire.getCompute() != null ? (componentQuestionnaire.getCompute() .getNumOfVMs() != null ? componentQuestionnaire.getCompute().getNumOfVMs() - .getMaximum(): null) : null; + .getMaximum() : null) : null; final Integer minVms = componentQuestionnaire.getCompute() != null ? (componentQuestionnaire.getCompute() .getNumOfVMs() != null ? componentQuestionnaire.getCompute().getNumOfVMs() - .getMinimum(): null) : null; + .getMinimum() : null) : null; - questionnaireParams.put(MIN_INSTANCES,minVms != null && minVms == 0 ? null : minVms); - questionnaireParams.put(MAX_INSTANCES,maxVms != null && maxVms == 0 ? null : maxVms); + questionnaireParams.put(MIN_INSTANCES, minVms != null && minVms == 0 ? null : minVms); + questionnaireParams.put(MAX_INSTANCES, maxVms != null && maxVms == 0 ? null : maxVms); - if (! questionnaireParams.isEmpty()) + if (!questionnaireParams.isEmpty()) { componentProperties.put(JsonUtil.json2Object(component.getCompositionData(), ComponentData.class).getDisplayName(), questionnaireParams); + } } setSourceToTargetComponent(sourceToTarget); @@ -111,12 +111,12 @@ public class ComponentQuestionnaireData { return componentProperties; } - public Map<String,List<String>> populateDependencies(String vspId, Version version, Map<String, - String> componentNameData) { + public Map<String, List<String>> populateDependencies(String vspId, Version version, Map<String, + String> componentNameData) { Collection<ComponentDependencyModelEntity> componentDependencies = componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, version, null)); - Map<String,List<String>> sourceToTargetComponent = new HashMap<String, List<String>>(); + Map<String, List<String>> sourceToTargetComponent = new HashMap<String, List<String>>(); List<String> targetComponents = null; for (ComponentDependencyModelEntity dependency : componentDependencies) { String sourceComponentName = componentNameData.get(dependency.getSourceComponentId()); diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricher.java index 705773d1fc..a855a7477f 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricher.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricher.java @@ -1,9 +1,5 @@ package org.openecomp.sdc.enrichment.impl.tosca; -import static org.openecomp.sdc.tosca.services.DataModelUtil.getClonedObject; -import static org.openecomp.sdc.tosca.services.ToscaConstants.PORT_MIRRORING_CAPABILITY_CP_PROPERTY_NAME; -import static org.openecomp.sdc.tosca.services.ToscaConstants.PORT_MIRRORING_CAPABILITY_ID; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.datatypes.error.ErrorMessage; @@ -39,6 +35,10 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import static org.openecomp.sdc.tosca.services.DataModelUtil.getClonedObject; +import static org.openecomp.sdc.tosca.services.ToscaConstants.PORT_MIRRORING_CAPABILITY_CP_PROPERTY_NAME; +import static org.openecomp.sdc.tosca.services.ToscaConstants.PORT_MIRRORING_CAPABILITY_ID; + public class PortMirroringEnricher { //Map of service template file name and map of all port node template ids, node template private Map<String, Map<String, NodeTemplate>> portNodeTemplates = new HashMap<>(); diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ToscaEnricher.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ToscaEnricher.java index 090c3ae101..5ea1176e48 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ToscaEnricher.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/impl/tosca/ToscaEnricher.java @@ -20,11 +20,13 @@ package org.openecomp.sdc.enrichment.impl.tosca; +import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.enrichment.inter.Enricher; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -45,13 +47,19 @@ public class ToscaEnricher extends Enricher { private Map<String, List<ErrorMessage>> enrichAbstractSubstitute() { mdcDataDebugMessage.debugEntryMessage(null, null); - Map<String, List<ErrorMessage>> enrichErrors; + Map<String, List<ErrorMessage>> enrichErrors = new HashMap<>(); ToscaServiceModel toscaModel = (ToscaServiceModel) model; AbstractSubstituteToscaEnricher abstractSubstituteToscaEnricher = new AbstractSubstituteToscaEnricher(); - enrichErrors = abstractSubstituteToscaEnricher.enrich(toscaModel, data.getKey(), - data.getVersion()); + + try { + enrichErrors = abstractSubstituteToscaEnricher.enrich(toscaModel, data.getKey(), + data.getVersion()); + }catch (Exception e){ + enrichErrors.put("Tosca Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, e + .getMessage()))); + } mdcDataDebugMessage.debugExitMessage(null, null); return enrichErrors; @@ -59,10 +67,16 @@ public class ToscaEnricher extends Enricher { private Map<String, List<ErrorMessage>> enrichPortMirroring() { mdcDataDebugMessage.debugEntryMessage(null, null); - Map<String, List<ErrorMessage>> enrichErrors; + Map<String, List<ErrorMessage>> enrichErrors = new HashMap<>(); ToscaServiceModel toscaModel = (ToscaServiceModel) model; PortMirroringEnricher portMirroringEnricher = new PortMirroringEnricher(); - enrichErrors = portMirroringEnricher.enrich(toscaModel); + + try { + enrichErrors = portMirroringEnricher.enrich(toscaModel); + }catch (Exception e){ + enrichErrors.put("Tosca Enrich", Arrays.asList(new ErrorMessage(ErrorLevel.ERROR, e + .getMessage()))); + } mdcDataDebugMessage.debugExitMessage(null, null); return enrichErrors; } diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/ExternalArtifactEnricherInterface.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/ExternalArtifactEnricherInterface.java index 49b424ef05..bd250bb8f4 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/ExternalArtifactEnricherInterface.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/main/java/org/openecomp/sdc/enrichment/inter/ExternalArtifactEnricherInterface.java @@ -32,5 +32,5 @@ import java.util.Map; * Created by Talio on 11/24/2016. */ public interface ExternalArtifactEnricherInterface { - public Map<String, List<ErrorMessage>> enrich(EnrichmentInfo enrichmentInfo) throws IOException; + Map<String, List<ErrorMessage>> enrich(EnrichmentInfo enrichmentInfo) throws IOException; } diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricherTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricherTest.java index 3730a15465..c01f986ab1 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricherTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/MonitoringMibEnricherTest.java @@ -35,7 +35,6 @@ import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; import org.openecomp.sdc.versioning.dao.types.Version; @@ -60,8 +59,6 @@ public class MonitoringMibEnricherTest { @Mock private EnrichedServiceModelDao enrichedServiceModelDaoMock; @Mock - private VendorSoftwareProductDao vendorSoftwareProductDaoMock; - @Mock private ComponentDao componentDaoMock; @InjectMocks @@ -157,7 +154,7 @@ public class MonitoringMibEnricherTest { private ByteBuffer getMibByteBuffer(String fileName) { byte[] mibBytes = FileUtils.readViaInputStream(this.getClass().getResource(fileName), - stream -> FileUtils.toByteArray(stream)); + stream -> FileUtils.toByteArray(stream)); return ByteBuffer.wrap(mibBytes); } diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java index 0bd84a4e30..59931a1a11 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/external/artifact/ProcessArtifactEnricherTest.java @@ -1,46 +1,15 @@ package org.openecomp.sdc.enrichment.impl.external.artifact; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.openecomp.core.enrichment.types.ArtifactCategory; -import org.openecomp.core.model.dao.EnrichedServiceModelDao; -import org.openecomp.core.model.types.ServiceArtifact; -import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.enrichment.EnrichmentInfo; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessType; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.File; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; - -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.when; - public class ProcessArtifactEnricherTest { /*@Mock ProcessDao processDaoMock; @Mock EnrichedServiceModelDao enrichedServiceModelDaoMock; @Mock - VendorSoftwareProductDao vendorSoftwareProductDaoMock; - + ComponentDao componentDaoMock; @InjectMocks ProcessArtifactEnricher processArtifactEnricher; - @BeforeMethod(alwaysRun = true) public void injectDoubles() { MockitoAnnotations.initMocks(this); @@ -65,11 +34,11 @@ public class ProcessArtifactEnricherTest { processEntity.setArtifactName("artifact_1kb.txt"); processEntity.setArtifact(getMibByteBuffer("/mock/enrichProcess/artifact_1kb.txt")); - Collection<ComponentEntity> componentList = new ArrayList<ComponentEntity>(); + Collection<ComponentEntity> componentList = new ArrayList<>(); componentList.add(componentEntity); - when(vendorSoftwareProductDaoMock.listComponents(vspId, version)).thenReturn(componentList); + when(componentDaoMock.list(anyObject())).thenReturn(componentList); - Collection<ProcessEntity> list = new ArrayList<ProcessEntity>(); + Collection<ProcessEntity> list = new ArrayList<>(); list.add(processEntity); when(processDaoMock.list(entity)).thenReturn(list); @@ -111,7 +80,7 @@ public class ProcessArtifactEnricherTest { private ByteBuffer getMibByteBuffer(String fileName) { byte[] mibBytes = FileUtils.readViaInputStream(this.getClass().getResource(fileName), - stream -> FileUtils.toByteArray(stream)); + stream -> FileUtils.toByteArray(stream)); return ByteBuffer.wrap(mibBytes); }*/ } diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/BaseToscaEnrichmentTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/BaseToscaEnrichmentTest.java index 0001cdf404..363e171c6c 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/BaseToscaEnrichmentTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/BaseToscaEnrichmentTest.java @@ -25,12 +25,18 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.tosca.services.ToscaFileOutputService; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; -import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; import java.net.URL; import java.nio.file.NotDirectoryException; import java.util.Collection; diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireDataTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireDataTest.java index 73732575f3..d6810d92b0 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireDataTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/ComponentQuestionnaireDataTest.java @@ -1,31 +1,5 @@ package org.openecomp.sdc.enrichment.impl.tosca; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.testng.Assert; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.mockito.Mockito.doReturn; -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.HIGH_AVAIL_MODE; -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MANDATORY; -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MAX_INSTANCES; -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.MIN_INSTANCES; -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VFC_CODE; -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VFC_FUNCTION; -import static org.openecomp.sdc.enrichment.impl.util.EnrichmentConstants.VFC_NAMING_CODE; - public class ComponentQuestionnaireDataTest { /*private static String VSP_ID = "vspId"; public static final Version VERSION01 = new Version(0, 1); diff --git a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricherTest.java b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricherTest.java index 0a8fe432b0..b48fd8d8d7 100644 --- a/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricherTest.java +++ b/openecomp-be/lib/openecomp-sdc-enrichment-lib/openecomp-sdc-enrichment-impl/src/test/java/org/openecomp/sdc/enrichment/impl/tosca/PortMirroringEnricherTest.java @@ -2,8 +2,6 @@ package org.openecomp.sdc.enrichment.impl.tosca; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerServiceName.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerServiceName.java index 08c957a58e..1a9d327414 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerServiceName.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerServiceName.java @@ -161,8 +161,14 @@ public enum LoggerServiceName { CREATE_COMPONENT_DEPENDENCY_MODEL, GET_COMPONENT_DEPENDENCY_MODEL, - - Health_check + GET_LIST_COMPONENT_DEPENDENCY, + CREATE_COMPONENT_DEPENDENCY, + UPDATE_COMPONENT_DEPENDENCY, + DELETE_COMPONENT_DEPENDENCY, + GET_COMPONENT_DEPENDENCY, + + Health_check, + notifications ; public static String getServiceName(LoggerServiceName serviceName) { diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerTragetServiceName.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerTragetServiceName.java index 33573a5572..ab7292a485 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerTragetServiceName.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/main/java/org/openecomp/sdc/logging/types/LoggerTragetServiceName.java @@ -128,6 +128,8 @@ public class LoggerTragetServiceName { public static final String CREATE_TRANSLATED_FILE = "Create Translated File"; public static final String CREATE_PACKAGE = "Create Package"; + public static final String CREATE_VERSION = "Create Version"; + public static final String SELF_HEALING = "Self Healing"; public static final String WRITE_ARTIFACT_XML = "Write Artifact To XML File"; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/LoggerFactoryTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/LoggerFactoryTest.java index aa04c50210..4b3a1ba7c7 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/LoggerFactoryTest.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/LoggerFactoryTest.java @@ -21,7 +21,9 @@ import org.testng.annotations.Test; import java.lang.reflect.Field; import java.util.ServiceLoader; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; /** * @author evitaliy diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/context/TaskFactoryTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/context/TaskFactoryTest.java index 61e1819b3b..f5c2187024 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/context/TaskFactoryTest.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-api/src/test/java/org/openecomp/sdc/logging/api/context/TaskFactoryTest.java @@ -4,7 +4,9 @@ import org.testng.annotations.Test; import java.util.ServiceLoader; -import static org.testng.Assert.*; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; /** * @author evitaliy diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/servlet/LoggingFilter.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/servlet/LoggingFilter.java index f34d09e882..0ca550a20a 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/servlet/LoggingFilter.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/main/java/org/openecomp/sdc/logging/servlet/LoggingFilter.java @@ -20,7 +20,12 @@ import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.slf4j.MDC; -import javax.servlet.*; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.net.InetAddress; @@ -58,7 +63,7 @@ public class LoggingFilter implements Filter { private static final HostAddressCache HOST_ADDRESS = new HostAddressCache(); private static final String UNKNOWN = "UNKNOWN"; - private final static Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class); public void destroy() { } @@ -80,7 +85,8 @@ public class LoggingFilter implements Filter { InetAddress host = HOST_ADDRESS.get(); - String ipAddress, hostName; + String ipAddress; + String hostName; if (host == null) { ipAddress = UNKNOWN; hostName = UNKNOWN; diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/context/MDCPropagationFactoryTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/context/MDCPropagationFactoryTest.java index 8502d95023..1fda9e85b3 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/context/MDCPropagationFactoryTest.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/context/MDCPropagationFactoryTest.java @@ -22,7 +22,9 @@ import org.testng.annotations.Test; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; -import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; /** * @author evitaliy diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java index 57911a368f..95a5421be0 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/src/test/java/org/openecomp/sdc/logging/servlet/LoggingFilterTest.java @@ -20,7 +20,13 @@ import org.slf4j.MDC; import org.testng.Assert; import org.testng.annotations.Test; -import javax.servlet.*; +import javax.servlet.FilterChain; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDao.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDao.java index aa8cbee7d4..3e5975dd13 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDao.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/dao/EnrichedServiceModelDao.java @@ -22,9 +22,6 @@ package org.openecomp.core.model.dao; import org.openecomp.core.model.types.ServiceArtifact; import org.openecomp.sdc.versioning.dao.VersionableDao; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.util.List; public interface EnrichedServiceModelDao<M, E> extends VersionableDao,ServiceModelDao<M, E>{ diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceArtifactEntity.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceArtifactEntity.java index d3d125b849..8736f369c7 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceArtifactEntity.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceArtifactEntity.java @@ -16,14 +16,12 @@ package org.openecomp.core.model.types; -import com.google.common.io.ByteStreams; - import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - +import com.google.common.io.ByteStreams; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceTemplateEntity.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceTemplateEntity.java index c837a70c36..f60c8922cd 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceTemplateEntity.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/EnrichedServiceTemplateEntity.java @@ -16,14 +16,12 @@ package org.openecomp.core.model.types; -import com.google.common.io.ByteStreams; - import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - +import com.google.common.io.ByteStreams; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifactEntity.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifactEntity.java index 8385a5da48..ddff54b436 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifactEntity.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceArtifactEntity.java @@ -16,13 +16,12 @@ package org.openecomp.core.model.types; -import com.google.common.io.ByteStreams; - import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import com.google.common.io.ByteStreams; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplateEntity.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplateEntity.java index 4897c2f076..8f886c2e74 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplateEntity.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-api/src/main/java/org/openecomp/core/model/types/ServiceTemplateEntity.java @@ -20,14 +20,12 @@ package org.openecomp.core.model.types; -import com.google.common.io.ByteStreams; - import com.datastax.driver.mapping.annotations.ClusteringColumn; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; - +import com.google.common.io.ByteStreams; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoImpl.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoImpl.java index 14eda9ee4d..348a8addbd 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/EnrichedServiceModelDaoImpl.java @@ -23,13 +23,10 @@ package org.openecomp.sdc.model.impl; import org.openecomp.core.model.dao.EnrichedServiceArtifactDaoFactory; import org.openecomp.core.model.dao.EnrichedServiceModelDao; import org.openecomp.core.model.dao.EnrichedServiceTemplateDaoFactory; -import org.openecomp.core.model.types.ServiceArtifact; import org.openecomp.core.model.types.ServiceElement; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.List; - public class EnrichedServiceModelDaoImpl extends AbstractServiceModelDao implements EnrichedServiceModelDao<ToscaServiceModel, ServiceElement> { public EnrichedServiceModelDaoImpl() { diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/EnrichedServiceModelDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/EnrichedServiceModelDaoZusammenImpl.java index d018c9a87c..3bd2881117 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/EnrichedServiceModelDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/EnrichedServiceModelDaoZusammenImpl.java @@ -1,7 +1,6 @@ package org.openecomp.sdc.model.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; -import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; @@ -11,10 +10,13 @@ import org.openecomp.core.model.types.ServiceElement; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; + public class EnrichedServiceModelDaoZusammenImpl extends ServiceModelDaoZusammenImpl implements EnrichedServiceModelDao<ToscaServiceModel, ServiceElement> { @@ -23,28 +25,31 @@ public class EnrichedServiceModelDaoZusammenImpl extends ServiceModelDaoZusammen public EnrichedServiceModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { super(zusammenAdaptor); - this.name = StructureElement.EnrichedServiceModel.name(); + this.elementType = ElementType.EnrichedServiceModel; } @Override public void storeExternalArtifact(ServiceArtifact serviceArtifact) { - ZusammenElement artifactElement = buildArtifactElement(serviceArtifact.getName(), + ZusammenElement artifact = buildArtifactElement(serviceArtifact.getName(), FileUtils.toByteArray(serviceArtifact.getContent()), Action.CREATE); - ZusammenElement artifactsElement = - buildStructuralElement(StructureElement.Artifacts.name(), null); - artifactsElement.addSubElement(artifactElement); + ZusammenElement artifacts = buildStructuralElement(ElementType.Artifacts, Action.IGNORE); + artifacts.addSubElement(artifact); + + ZusammenElement enrichedServiceModel = buildStructuralElement(elementType, Action.IGNORE); + enrichedServiceModel.addSubElement(artifacts); - ZusammenElement enrichedServiceModelElement = buildStructuralElement(name, null); - enrichedServiceModelElement.addSubElement(artifactsElement); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(enrichedServiceModel); SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(serviceArtifact.getVspId()); - ElementContext elementContext = new ElementContext(itemId, getFirstVersionId(context, itemId)); + ElementContext elementContext = + new ElementContext(serviceArtifact.getVspId(), serviceArtifact.getVersion().getId()); zusammenAdaptor - .saveElement(context, elementContext, enrichedServiceModelElement, "add service artifact."); + .saveElement(context, elementContext, vspModel, "add service external artifact."); - logger.info("Finished adding artifact to service model for vsp id -> " + + logger.info( + "Finished adding artifact to enriched service model for VendorSoftwareProduct id -> {}", elementContext.getItemId().getValue()); } } diff --git a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ServiceModelDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ServiceModelDaoZusammenImpl.java index b5e3627e61..4ae9353f42 100644 --- a/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ServiceModelDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-model-lib/openecomp-sdc-model-impl/src/main/java/org/openecomp/sdc/model/impl/zusammen/ServiceModelDaoZusammenImpl.java @@ -8,7 +8,6 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersion; import org.apache.commons.io.IOUtils; import org.openecomp.core.model.dao.ServiceModelDao; import org.openecomp.core.model.errors.RetrieveServiceTemplateFromDbErrorBuilder; @@ -17,14 +16,14 @@ import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.core.converter.datatypes.Constants; +import org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; import java.util.Collection; @@ -33,16 +32,20 @@ import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; + public class ServiceModelDaoZusammenImpl implements ServiceModelDao<ToscaServiceModel, ServiceElement> { + private static final String BASE_PROPERTY = "base"; private static final Logger logger = LoggerFactory.getLogger(ServiceModelDaoZusammenImpl.class); protected ZusammenAdaptor zusammenAdaptor; - protected String name; + protected ElementType elementType; public ServiceModelDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { this.zusammenAdaptor = zusammenAdaptor; - this.name = StructureElement.ServiceModel.name(); + this.elementType = ElementType.ServiceModel; } @Override @@ -53,98 +56,59 @@ public class ServiceModelDaoZusammenImpl @Override public ToscaServiceModel getServiceModel(String vspId, Version version) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, getFirstVersionId(context, itemId), - version.getStatus() == VersionStatus.Locked ? null : version.toString()); - - Optional<ElementInfo> serviceModelElement = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, name); - - if (serviceModelElement.isPresent()) { - String entryDefinitionServiceTemplate = - serviceModelElement.get().getInfo().getProperty("base"); - Id serviceModelElementId = serviceModelElement.get().getId(); - Map<String, ServiceTemplate> serviceTemplates = - getTemplates(context, elementContext, serviceModelElementId); - if (serviceTemplates == null) { - return null; - } - FileContentHandler artifacts = getArtifacts(context, elementContext, serviceModelElementId); - + ElementContext elementContext = new ElementContext(vspId, version.getId()); - return new ToscaServiceModel( - artifacts, serviceTemplates, entryDefinitionServiceTemplate); - } else { + Optional<ElementInfo> serviceModel = getServiceModelElementInfo(context, elementContext); + if (!serviceModel.isPresent()) { return null; } - } - - protected Map<String, ServiceTemplate> getTemplates(SessionContext context, - ElementContext elementContext, - Id serviceModelElementId) { - Optional<ElementInfo> templatesElementInfo = zusammenAdaptor.getElementInfoByName( - context, elementContext, serviceModelElementId, StructureElement.Templates.name()); - if (templatesElementInfo.isPresent()) { - Collection<Element> elements = zusammenAdaptor.listElementData(context, elementContext, - templatesElementInfo.get().getId()); - - return elements.stream().collect(Collectors.toMap( - element -> element.getInfo().getName(), - this::elementToServiceTemplate)); + Id serviceModelElementId = serviceModel.get().getId(); + Map<String, ServiceTemplate> serviceTemplates = + getTemplates(context, elementContext, serviceModelElementId); + if (serviceTemplates == null) { + return null; } - return null; - } - - protected FileContentHandler getArtifacts(SessionContext context, ElementContext elementContext, - Id serviceModelElementId) { - Optional<ElementInfo> artifactsElement = zusammenAdaptor.getElementInfoByName( - context, elementContext, serviceModelElementId, StructureElement.Artifacts.name()); - if (artifactsElement.isPresent()) { - - Collection<Element> elements = zusammenAdaptor.listElementData(context, elementContext, - artifactsElement.get().getId()); - FileContentHandler fileContentHandler = new FileContentHandler(); - elements.forEach(element -> fileContentHandler.addFile(element.getInfo().getName(), - element.getData())); - return fileContentHandler; - } + FileContentHandler artifacts = getArtifacts(context, elementContext, serviceModelElementId); + String entryDefinitionServiceTemplate = + serviceModel.get().getInfo().getProperty(BASE_PROPERTY); - return null; + return new ToscaServiceModel(artifacts, serviceTemplates, entryDefinitionServiceTemplate); } @Override public void storeServiceModel(String vspId, Version version, ToscaServiceModel serviceModel) { - logger.info("Storing service model for vsp id -> " + vspId); + logger.info("Storing service model for VendorSoftwareProduct id -> {}", vspId); - ZusammenElement templatesElement = - buildStructuralElement(StructureElement.Templates.name(), null); + ZusammenElement templatesElement = buildStructuralElement(ElementType.Templates, Action.UPDATE); serviceModel.getServiceTemplates().entrySet().forEach(entry -> templatesElement.addSubElement( buildServiceTemplateElement(entry.getKey(), entry.getValue(), serviceModel.getEntryDefinitionServiceTemplate(), Action.CREATE))); - ZusammenElement artifactsElement = - buildStructuralElement(StructureElement.Artifacts.name(), Action.UPDATE); + ZusammenElement artifactsElement = buildStructuralElement(ElementType.Artifacts, Action.UPDATE); if (Objects.nonNull(serviceModel.getArtifactFiles())) { - serviceModel.getArtifactFiles().getFiles().entrySet().forEach(entry -> artifactsElement - .addSubElement(buildArtifactElement(entry.getKey(), entry.getValue(), Action.CREATE))); + serviceModel.getArtifactFiles().getFiles().entrySet() + .forEach(entry -> artifactsElement.addSubElement( + buildArtifactElement(entry.getKey(), entry.getValue(), Action.CREATE))); } - ZusammenElement serviceModelElement = buildStructuralElement(name, Action.UPDATE); + ZusammenElement serviceModelElement = buildStructuralElement(elementType, Action.UPDATE); serviceModelElement.getInfo() - .addProperty("base", serviceModel.getEntryDefinitionServiceTemplate()); + .addProperty(BASE_PROPERTY, serviceModel.getEntryDefinitionServiceTemplate()); serviceModelElement.addSubElement(templatesElement); serviceModelElement.addSubElement(artifactsElement); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(serviceModelElement); + SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, getFirstVersionId(context, itemId)); - zusammenAdaptor - .saveElement(context, elementContext, serviceModelElement, "Store service model"); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + zusammenAdaptor.saveElement(context, elementContext, vspModel, "Store service model"); - logger.info("Finished storing service model for vsp id -> " + vspId); + logger + .info("Finished storing {} for VendorSoftwareProduct id -> {}", elementType.name(), vspId); } @Override @@ -154,65 +118,132 @@ public class ServiceModelDaoZusammenImpl @Override public void deleteAll(String vspId, Version version) { - logger.info("started deleting service model for vsp id -> " + vspId); + logger.info("Started deleting content of Templates and Artifacts of {} of vsp {} version {}", + elementType.name(), vspId, version.getId()); + SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, getFirstVersionId(context, itemId)); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + Optional<ElementInfo> serviceModel = getServiceModelElementInfo(context, elementContext); + if (!serviceModel.isPresent()) { + logger.info("{} of vsp {} version {} does not exist - nothing to delete", elementType.name(), + vspId, version.getId()); + return; + } + + ZusammenElement serviceModelElement = buildElement(serviceModel.get().getId(), Action.IGNORE); + for (Id serviceModelSubElementId : + serviceModel.get().getSubElements().stream() + .map(ElementInfo::getId) + .collect(Collectors.toSet())) { + ElementInfo serviceModelSubElementInfo = + zusammenAdaptor.getElementInfo(context, elementContext, serviceModelSubElementId) + .orElseThrow(() -> new IllegalStateException(String.format( + "Element %s declared as sub element of element %s (%s) does not exist", + serviceModelSubElementId.getValue(), + serviceModel.get().getId().getValue(), + elementType.name()))); + + if (ElementType.Templates.name().equals(serviceModelSubElementInfo.getInfo().getName()) + || ElementType.Artifacts.name().equals(serviceModelSubElementInfo.getInfo().getName())) { + ZusammenElement serviceModelSubElement = + buildElement(serviceModelSubElementId, Action.IGNORE); + serviceModelSubElement.setSubElements(serviceModelSubElementInfo.getSubElements().stream() + .map(elementInfo -> buildElement(elementInfo.getId(), Action.DELETE)) + .collect(Collectors.toSet())); + serviceModelElement.addSubElement(serviceModelSubElement); + } + } - ZusammenElement zusammenElement = ZusammenUtil.buildStructuralElement(name, Action.DELETE); - zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete:" + name + "."); - logger.info("Finished deleting service model for vsp id -> " + vspId); + zusammenAdaptor.saveElement(context, elementContext, serviceModelElement, + String.format("Delete content of Templates and Artifacts of %s", elementType.name())); + + logger.info("Finished deleting content of Templates and Artifacts of {} of vsp {} version {}", + elementType.name(), vspId, version.getId()); } - protected ZusammenElement buildArtifactElement(String name, byte[] artifact, Action action) { - ZusammenElement artifactElement = new ZusammenElement(); - artifactElement.setAction(action); - Info info = new Info(); - info.setName(name); - info.addProperty("type", ElementType.Artifact.name()); - artifactElement.setInfo(info); - artifactElement.setData(new ByteArrayInputStream(artifact)); + private Optional<ElementInfo> getServiceModelElementInfo(SessionContext context, + ElementContext elementContext) { + Collection<ElementInfo> vspModelSubs = zusammenAdaptor + .listElementsByName(context, elementContext, null, ElementType.VspModel.name()); - return artifactElement; + return vspModelSubs.stream() + .filter(elementInfo -> elementInfo.getInfo() != null + && elementType.name().equals(elementInfo.getInfo().getName())) + .findFirst(); } - private ServiceTemplate elementToServiceTemplate(Element element){ + private Map<String, ServiceTemplate> getTemplates(SessionContext context, + ElementContext elementContext, + Id serviceModelElementId) { + Optional<ElementInfo> templatesElementInfo = zusammenAdaptor.getElementInfoByName( + context, elementContext, serviceModelElementId, ElementType.Templates.name()); - try { - String yamlContent = IOUtils.toString(element.getData()); - return new ToscaExtensionYamlUtil(). - yamlToObject(yamlContent, ServiceTemplate.class); - }catch (Exception e){ - throw new CoreException( - new RetrieveServiceTemplateFromDbErrorBuilder( - element.getInfo().getName(), e.getMessage()).build()); + if (templatesElementInfo.isPresent()) { + Collection<Element> elements = zusammenAdaptor.listElementData(context, elementContext, + templatesElementInfo.get().getId()); + + return elements.stream().collect(Collectors.toMap( + element -> element.getInfo().getName(), + this::elementToServiceTemplate)); } + return null; + } + + private FileContentHandler getArtifacts(SessionContext context, ElementContext elementContext, + Id serviceModelElementId) { + Optional<ElementInfo> artifactsElement = zusammenAdaptor.getElementInfoByName( + context, elementContext, serviceModelElementId, ElementType.Artifacts.name()); + + if (artifactsElement.isPresent()) { + + Collection<Element> elements = zusammenAdaptor.listElementData(context, elementContext, + artifactsElement.get().getId()); + FileContentHandler fileContentHandler = new FileContentHandler(); + elements.forEach(element -> fileContentHandler.addFile(element.getInfo().getName(), + element.getData())); + return fileContentHandler; + } + + return null; } private Element buildServiceTemplateElement(String name, ServiceTemplate serviceTemplate, String entryDefinitionServiceTemplate, Action action) { - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(action); + ZusammenElement zusammenElement = buildElement(null, action); Info info = new Info(); info.setName(name); info.setDescription(serviceTemplate.getDescription()); - info.addProperty("type", ElementType.Servicetemplate.name()); - info.addProperty("base", entryDefinitionServiceTemplate); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.ServiceTemplate.name()); + info.addProperty(BASE_PROPERTY, entryDefinitionServiceTemplate); String yaml = new ToscaExtensionYamlUtil().objectToYaml(serviceTemplate); zusammenElement.setData(new ByteArrayInputStream(yaml.getBytes())); zusammenElement.setInfo(info); return zusammenElement; } - protected Id getFirstVersionId(SessionContext context, Id vspId) { - Optional<ItemVersion> itemVersionOptional = zusammenAdaptor.getFirstVersion(context, vspId); - ItemVersion itemVersion = itemVersionOptional.orElseThrow(() -> - new RuntimeException(String.format("Vsp %s does not contain any version.", vspId))); //todo - return itemVersion.getId(); + protected ZusammenElement buildArtifactElement(String name, byte[] artifact, Action action) { + ZusammenElement artifactElement = buildElement(null, action); + Info info = new Info(); + info.setName(name); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Artifact.name()); + artifactElement.setInfo(info); + artifactElement.setData(new ByteArrayInputStream(artifact)); + + return artifactElement; } - protected ZusammenElement buildStructuralElement(String structureElement, Action action) { - return ZusammenUtil.buildStructuralElement(structureElement, action); + + private ServiceTemplate elementToServiceTemplate(Element element) { + try { + String yamlContent = IOUtils.toString(element.getData()); + return new ToscaExtensionYamlUtil(). + yamlToObject(yamlContent, ServiceTemplate.class); + }catch (Exception e){ + throw new CoreException( + new RetrieveServiceTemplateFromDbErrorBuilder( + element.getInfo().getName(), e.getMessage()).build()); + } } } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/pom.xml new file mode 100644 index 0000000000..8e1c293e16 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/pom.xml @@ -0,0 +1,20 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <name>openecomp-sdc-notification-api</name> + <artifactId>openecomp-sdc-notification-api</artifactId> + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>../..</relativePath> + </parent> + <dependencies> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-nosqldb-core</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> +</project> diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/destinationprovider/DestinationProvider.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/destinationprovider/DestinationProvider.java new file mode 100644 index 0000000000..0c6dfc8580 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/destinationprovider/DestinationProvider.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.destinationprovider; + +import java.util.List; + +/** + * @author avrahamg + * @since July 09, 2017 + */ +public interface DestinationProvider { + List<String> getSubscribers(); +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/UploadDataDao.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/LastNotificationDao.java index cdc3a770db..f0bf7e8874 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/UploadDataDao.java +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/LastNotificationDao.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,17 +18,17 @@ * ============LICENSE_END========================================================= */ -package org.openecomp.sdc.vendorsoftwareproduct.dao; +package org.openecomp.sdc.notification.dao; import org.openecomp.core.dao.BaseDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; -import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; -import java.nio.ByteBuffer; +import java.util.UUID; -public interface UploadDataDao extends BaseDao<UploadDataEntity> { +public interface LastNotificationDao extends BaseDao<LastSeenNotificationEntity> { - void deleteContentDataAndValidationData(String vspId, Version version); + UUID getOwnerLastEventId(String ownerId); + + void persistOwnerLastEventId(String ownerId, UUID eventId); - ByteBuffer getContentData(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/NotificationsDao.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/NotificationsDao.java new file mode 100644 index 0000000000..6542d70158 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/NotificationsDao.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao; + +import org.openecomp.core.dao.BaseDao; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.dtos.NotificationsStatus; + +import java.util.Collection; +import java.util.List; +import java.util.UUID; + + +public interface NotificationsDao extends BaseDao<NotificationEntity> { + + int DEFAULT_LIMIT_OF_RESULTS_FOR_OWNER_NOTIFICATIONS = 1000; + + List<NotificationEntity> getNotificationsByOwnerId(String ownerId, int limit); + + List<NotificationEntity> getNewNotificationsByOwnerId(String ownerId, UUID eventId); + + List<NotificationEntity> getNewNotificationsByOwnerId(String ownerId, UUID eventId, int limit); + + NotificationsStatus getNotificationsStatus(String ownerId, UUID lastSeenNotification, int numOfRecordsToReturn); + + NotificationsStatus getNotificationsStatus(String ownerId, UUID lastSeenNotification, int numOfRecordsToReturn, UUID prevLastNotification); + + void markNotificationAsRead(String ownerId, Collection<UUID> eventIds); + + void createBatch(List<NotificationEntity> notificationEntities); +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/SubscribersDao.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/SubscribersDao.java new file mode 100644 index 0000000000..3daf165efc --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/SubscribersDao.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao; + +import org.openecomp.core.dao.BaseDao; +import org.openecomp.sdc.notification.dao.types.SubscribersEntity; + +import java.util.Set; + + +public interface SubscribersDao extends BaseDao<SubscribersEntity> { + + void subscribe(String ownerId, String entityId); + + void unsubscribe(String ownerId, String entityId); + + Set<String> getSubscribers(String entityId); + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/LastSeenNotificationEntity.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/LastSeenNotificationEntity.java new file mode 100644 index 0000000000..d6e717d1b3 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/LastSeenNotificationEntity.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao.types; + +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; + +import java.util.Objects; +import java.util.UUID; + +@Table(keyspace = "dox", name = "last_notification") +public class LastSeenNotificationEntity { + public static final String ENTITY_TYPE = "Event Notification"; + + @PartitionKey + @Column(name = "owner_id") + private String ownerId; + + @Column(name = "event_id") + private UUID lastEventId; + + public LastSeenNotificationEntity() { + } + + /** + * Instantiates a new Notification entity. + * + * @param ownerId the owner id + * @param lastEventId the last event id + */ + public LastSeenNotificationEntity(String ownerId, UUID lastEventId) { + this.ownerId = ownerId; + this.lastEventId = lastEventId; + } + + public String getOwnerId() { + return ownerId; + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + public UUID getLastEventId() { + return lastEventId; + } + + public void setLastEventId(UUID lastEventId) { + this.lastEventId = lastEventId; + } + + @Override + public boolean equals(Object other) { + if (Objects.equals(this, other)) { + return true; + } + + if (Objects.equals(getClass(), other.getClass())) { + return false; + } + + LastSeenNotificationEntity that = (LastSeenNotificationEntity) other; + + if (Objects.equals(ownerId, that.ownerId)) { + return false; + } + + return !Objects.equals(lastEventId, that.lastEventId); + } + + @Override + public int hashCode() { + int result = ownerId != null ? ownerId.hashCode() : 0; + result = 31 * result + (lastEventId != null ? lastEventId.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "LastSeenNotificationEntity {" + + "ownerId='" + ownerId + '\'' + + '}'; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/NotificationEntity.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/NotificationEntity.java new file mode 100644 index 0000000000..52377077cf --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/NotificationEntity.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao.types; + +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; + +import java.util.Objects; +import java.util.UUID; + +@Table(keyspace = "dox", name = "notifications") +public class NotificationEntity { + + public static final String ENTITY_TYPE = "Event Notification"; + + @PartitionKey + @Column(name = "owner_id") + private String ownerId; + + @Column(name = "read") + private boolean read; + + @ClusteringColumn + @Column(name = "event_id") + private UUID eventId; + + @Column(name = "event_type") + private String eventType; + + @Column(name = "event_attributes") + private String eventAttributes; + + @Column(name = "originator_id") + private String originatorId; + + public NotificationEntity() { + } + + public NotificationEntity(String ownerId) { + this.ownerId = ownerId; + } + + /** + * Instantiates a new Notification entity. + * + * @param ownerId the owner id + * @param eventId the event id + * @param eventType the event type + * @param originatorId the originator id + */ + public NotificationEntity(String ownerId, UUID eventId, String eventType, String originatorId, boolean read, String eventAttributes) { + this.ownerId = ownerId; + this.read = read; + this.eventId = eventId; + this.eventType = eventType; + this.originatorId = originatorId; + this.eventAttributes = eventAttributes; + } + + public NotificationEntity(String ownerId, UUID eventId, String eventType, String originatorId) { + this(ownerId, eventId, eventType, originatorId, false, null); + } + + public NotificationEntity(String ownerId, UUID eventId) { + this(ownerId, eventId, null, null); + } + + public String getOwnerId() { + return ownerId; + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + public boolean isRead() { + return read; + } + + public void setRead(boolean read) { + this.read = read; + } + + public UUID getEventId() { + return eventId; + } + + public void setEventId(UUID eventId) { + this.eventId = eventId; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public String getEventAttributes() { + return eventAttributes; + } + + public void setEventAttributes(String eventAttributes) { + this.eventAttributes = eventAttributes; + } + + public String getOriginatorId() { + return originatorId; + } + + public void setOriginatorId(String originatorId) { + this.originatorId = originatorId; + } + + @Override + public boolean equals(Object other) { + if (Objects.equals(this, other)) { + return true; + } + + if (Objects.equals(getClass(), other.getClass())) { + return false; + } + + NotificationEntity that = (NotificationEntity) other; + + if (Objects.equals(ownerId, that.ownerId)) { + return false; + } + if (read != that.read) { + return false; + } + if (Objects.equals(eventId, that.eventId)) { + return false; + } + if (Objects.equals(eventType, that.eventType)) { + return false; + } + if (Objects.equals(eventAttributes, that.eventAttributes)) { + return false; + } + if (Objects.equals(originatorId, that.originatorId)) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = ownerId != null ? ownerId.hashCode() : 0; + result = 31 * result + (eventId != null ? eventId.hashCode() : 0); + return result; + } + + @Override + public String toString() { + return "NotificationEntity {" + + "ownerId='" + ownerId + '\'' + + ", state='" + (read ? "Read" : "Noread") + '\'' + + ", originatorId='" + originatorId + '\'' + + ", eventId='" + eventId + '\'' + + ", eventType='" + eventType + '\'' + + ", eventAttributes='" + eventAttributes + '\'' + + '}'; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/SubscribersEntity.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/SubscribersEntity.java new file mode 100644 index 0000000000..d858cbd9eb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dao/types/SubscribersEntity.java @@ -0,0 +1,68 @@ +package org.openecomp.sdc.notification.dao.types; + +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; + +import java.util.Objects; +import java.util.Set; + +import static java.util.Objects.hash; + +@Table(keyspace = "dox", name = "notification_subscribers") +public class SubscribersEntity { + + @PartitionKey + @Column(name = "entity_id") + private String entityId; + + @Column(name = "subscribers") + private Set<String> subscribers; + + + public SubscribersEntity() { + } + + public SubscribersEntity(String entityId, Set<String> subscribers) { + this.entityId = entityId; + this.subscribers = subscribers; + } + + public String getEntityId() { + return entityId; + } + + public void setEntityId(String entityId) { + this.entityId = entityId; + } + + public Set<String> getSubscribers() { + return subscribers; + } + + public void setSubscribers(Set<String> subscribers) { + this.subscribers = subscribers; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + SubscribersEntity that = (SubscribersEntity) o; + return Objects.equals(entityId, that.entityId) && + Objects.equals(subscribers, that.subscribers); + } + + @Override + public int hashCode() { + return hash(entityId, subscribers); + } + + @Override + public String toString() { + return "SubscribersEntity{" + + "entityId='" + entityId + '\'' + + ", subscribers=" + subscribers + + '}'; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/Event.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/Event.java new file mode 100644 index 0000000000..f7a181e5e6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/Event.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.notification.dtos; + +import java.util.Map; + +public interface Event { + + String getEventType(); + + String getOriginatorId(); + + Map<String, Object> getAttributes(); + + String getEntityId(); +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/NotificationsStatus.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/NotificationsStatus.java new file mode 100644 index 0000000000..1620569ec5 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/dtos/NotificationsStatus.java @@ -0,0 +1,24 @@ +package org.openecomp.sdc.notification.dtos; + +import org.openecomp.sdc.notification.dao.types.NotificationEntity; + +import java.util.List; +import java.util.UUID; + +/** + * @author Avrahamg + * @since June 26, 2017 + */ +public interface NotificationsStatus { + + List<NotificationEntity> getNotifications(); + + List<UUID> getNewEntries(); + + UUID getLastScanned(); + + UUID getEndOfPage(); + + long getNumOfNotSeenNotifications(); + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/exceptons/NotificationNotExistException.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/exceptons/NotificationNotExistException.java new file mode 100644 index 0000000000..90e53ea69a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/exceptons/NotificationNotExistException.java @@ -0,0 +1,18 @@ +package org.openecomp.sdc.notification.exceptons; + +/** + * @author avrahamg + * @since July 02, 2017 + */ +public class NotificationNotExistException extends Exception { + private String message; + + + public NotificationNotExistException(String Message){ + this(Message, null); + } + public NotificationNotExistException(String message, Throwable cause) { + super(cause); + this.message = message; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/LastNotificationDaoFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/LastNotificationDaoFactory.java new file mode 100644 index 0000000000..6e6f9f063a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/LastNotificationDaoFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.factories; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.sdc.notification.dao.LastNotificationDao; + + +public abstract class LastNotificationDaoFactory extends AbstractComponentFactory<LastNotificationDao> { + + public static LastNotificationDaoFactory getInstance() { + return AbstractFactory.getInstance(LastNotificationDaoFactory.class); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationPropagationManagerFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationPropagationManagerFactory.java new file mode 100644 index 0000000000..356055e26c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationPropagationManagerFactory.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.notification.factories; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.sdc.notification.services.NotificationPropagationManager; + +public abstract class NotificationPropagationManagerFactory extends AbstractComponentFactory<NotificationPropagationManager> { + + + public static NotificationPropagationManagerFactory getInstance() { + return AbstractFactory.getInstance(NotificationPropagationManagerFactory.class); + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsDaoFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsDaoFactory.java new file mode 100644 index 0000000000..341af7e296 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsDaoFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.factories; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.sdc.notification.dao.NotificationsDao; + + +public abstract class NotificationsDaoFactory extends AbstractComponentFactory<NotificationsDao> { + + public static NotificationsDaoFactory getInstance() { + return AbstractFactory.getInstance(NotificationsDaoFactory.class); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsServiceFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsServiceFactory.java new file mode 100644 index 0000000000..eab26188c1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/NotificationsServiceFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.factories; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.sdc.notification.services.NotificationsService; + + +public abstract class NotificationsServiceFactory extends AbstractComponentFactory<NotificationsService> { + + public static NotificationsServiceFactory getInstance() { + return AbstractFactory.getInstance(NotificationsServiceFactory.class); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/PropagationServiceFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/PropagationServiceFactory.java new file mode 100644 index 0000000000..e82783c40c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/PropagationServiceFactory.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.notification.factories; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.sdc.notification.services.PropagationService; + +public abstract class PropagationServiceFactory extends AbstractComponentFactory<PropagationService> { + + + public static PropagationServiceFactory getInstance() { + return AbstractFactory.getInstance(PropagationServiceFactory.class); + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscribersDaoFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscribersDaoFactory.java new file mode 100644 index 0000000000..33b62e2f5d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscribersDaoFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.factories; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.sdc.notification.dao.SubscribersDao; + + +public abstract class SubscribersDaoFactory extends AbstractComponentFactory<SubscribersDao> { + + public static SubscribersDaoFactory getInstance() { + return AbstractFactory.getInstance(SubscribersDaoFactory.class); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscriptionServiceFactory.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscriptionServiceFactory.java new file mode 100644 index 0000000000..3e789c22a7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/factories/SubscriptionServiceFactory.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.factories; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; +import org.openecomp.sdc.notification.services.SubscriptionService; + + +public abstract class SubscriptionServiceFactory extends AbstractComponentFactory<SubscriptionService> { + + public static SubscriptionServiceFactory getInstance() { + return AbstractFactory.getInstance(SubscriptionServiceFactory.class); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationPropagationManager.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationPropagationManager.java new file mode 100644 index 0000000000..7a1596eb95 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationPropagationManager.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.notification.services; + +import org.openecomp.sdc.notification.dtos.Event; + +/** + * @author avrahamg + * @since July 09, 2017 + */ +public interface NotificationPropagationManager { + void notifySubscribers(Event event, String ... excludedSubscribers); + void directNotification(Event event, String destinationId); +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationsService.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationsService.java new file mode 100644 index 0000000000..17cfac1e5d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/NotificationsService.java @@ -0,0 +1,31 @@ +package org.openecomp.sdc.notification.services; + +import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.dtos.NotificationsStatus; +import org.openecomp.sdc.notification.exceptons.NotificationNotExistException; + +import java.util.List; +import java.util.UUID; + +/** + * @author Avrahamg + * @since June 22, 2017 + */ +public interface NotificationsService { + + LastSeenNotificationEntity getLastNotification(String ownerId); + + NotificationsStatus getNotificationsStatus(String ownerId, UUID lastDelivered, int numOfRecordsToReturn, UUID endOfPage); + + void updateLastSeenNotification(String ownerId, UUID eventId); + + void markAsRead(String ownerId, String notificationId) throws NotificationNotExistException; + + List<NotificationEntity> getNotificationsByOwnerId(String ownerId, int limit); + + List<NotificationEntity> getNewNotificationsByOwnerId(String ownerId, UUID eventId); + + List<NotificationEntity> getNewNotificationsByOwnerId(String ownerId, UUID eventId, int limit); + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/PropagationService.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/PropagationService.java new file mode 100644 index 0000000000..c084aa8015 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/PropagationService.java @@ -0,0 +1,9 @@ +package org.openecomp.sdc.notification.services; + +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.notification.dtos.Event; + +public interface PropagationService { + + void notify(Event event, DestinationProvider destinationProvider); +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/SubscriptionService.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/SubscriptionService.java new file mode 100644 index 0000000000..98cd458ca2 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-api/src/main/java/org/openecomp/sdc/notification/services/SubscriptionService.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.notification.services; + +import java.util.Set; + +/** + * @author avrahamg + * @since July 09, 2017 + */ +public interface SubscriptionService { + void subscribe(String ownerId, String entityId); + + void unsubscribe(String ownerId, String entityId); + + Set<String> getSubscribers(String entityId); +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/pom.xml new file mode 100644 index 0000000000..4fe33ea1c3 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/pom.xml @@ -0,0 +1,42 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <name>openecomp-sdc-notification-core</name> + <artifactId>openecomp-sdc-notification-core</artifactId> + + + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>../..</relativePath> + </parent> + <dependencies> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-notification-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <scope>test</scope> + <version>1.10.19</version> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + <version>${junit.version}</version> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-module-junit4</artifactId> + <version>1.6.5</version> + <scope>test</scope> + </dependency> + </dependencies> + +</project> diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestination.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestination.java new file mode 100644 index 0000000000..431f9c18d6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestination.java @@ -0,0 +1,44 @@ +package org.openecomp.sdc.destinationprovider.impl; + +import org.apache.commons.lang3.ArrayUtils; +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.notification.services.SubscriptionService; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +/** + * @author avrahamg + * @since July 09, 2017 + */ +public class MulticastDestination implements DestinationProvider { + + private String entityId; + private SubscriptionService subscriptionService; + private String[] excludedSubscribers; + + public MulticastDestination(String entityId, SubscriptionService subscriptionService, + String... excludedSubscribers) { + this.entityId = entityId; + this.excludedSubscribers = excludedSubscribers; + this.subscriptionService = subscriptionService; + } + + public List<String> getSubscribers() { + ArrayList<String> subscribers = new ArrayList<>(subscriptionService.getSubscribers(entityId)); + if (ArrayUtils.isNotEmpty(excludedSubscribers)) { + subscribers.removeAll(Arrays.asList(excludedSubscribers)); + } + return Collections.unmodifiableList(subscribers); + } + + public String getEntityId() { + return entityId; + } + + public void setEntityId(String entityId) { + this.entityId = entityId; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/UnicastDestination.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/UnicastDestination.java new file mode 100644 index 0000000000..693c816d01 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/destinationprovider/impl/UnicastDestination.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.destinationprovider.impl; + +import org.openecomp.sdc.destinationprovider.DestinationProvider; + +import java.util.Collections; +import java.util.List; + +/** + * @author avrahamg + * @since July 09, 2017 + */ +public class UnicastDestination implements DestinationProvider { + + private String originatorId; + + public UnicastDestination(String originatorId) { + this.originatorId = originatorId; + } + + public List<String> getSubscribers() { + return Collections.unmodifiableList(Collections.singletonList(originatorId)); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/LastNotificationDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/LastNotificationDaoCassandraImpl.java new file mode 100644 index 0000000000..0bfd6a314d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/LastNotificationDaoCassandraImpl.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao.impl; + +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.Mapper; +import com.datastax.driver.mapping.Result; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.dao.impl.CassandraBaseDao; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; +import org.openecomp.sdc.notification.dao.LastNotificationDao; +import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; + +import java.util.Collection; +import java.util.UUID; + + +public class LastNotificationDaoCassandraImpl extends CassandraBaseDao<LastSeenNotificationEntity> implements LastNotificationDao { + + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper<LastSeenNotificationEntity> mapper = + noSqlDb.getMappingManager().mapper(LastSeenNotificationEntity.class); + private static final LastNotificationAccessor accessor = + noSqlDb.getMappingManager().createAccessor(LastNotificationAccessor.class); + + @Override + protected Mapper<LastSeenNotificationEntity> getMapper() { + return mapper; + } + + @Override + protected Object[] getKeys(LastSeenNotificationEntity entity) { + return new Object[]{entity.getOwnerId()}; + } + + @Override + public Collection<LastSeenNotificationEntity> list(LastSeenNotificationEntity entity) { + return accessor.list(entity.getOwnerId()).all(); + } + + @Override + public UUID getOwnerLastEventId(String ownerId) { + ResultSet ownerLastEventId = accessor.getOwnerLastEventId(ownerId); + Row one = ownerLastEventId.one(); + return one != null ? one.getUUID("event_id") : null; + } + + @Override + public void persistOwnerLastEventId(String ownerId, UUID eventId) { + accessor.updateOwnerLastEventId(eventId, ownerId); + } + + @Accessor + interface LastNotificationAccessor { + + @Query("select * from last_notification where owner_id=?") + Result<LastSeenNotificationEntity> list(String ownerId); + + @Query("select event_id from last_notification where owner_id=?") + ResultSet getOwnerLastEventId(String ownerId); + + @Query("update last_notification set event_id=? where owner_id=?") + ResultSet updateOwnerLastEventId(UUID eventId, String ownerId); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/NotificationsDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/NotificationsDaoCassandraImpl.java new file mode 100644 index 0000000000..151c2c81d9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/NotificationsDaoCassandraImpl.java @@ -0,0 +1,287 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao.impl; + +import com.datastax.driver.core.BatchStatement; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Statement; +import com.datastax.driver.core.utils.UUIDs; +import com.datastax.driver.mapping.Mapper; +import com.datastax.driver.mapping.Result; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.core.dao.impl.CassandraBaseDao; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; +import org.openecomp.sdc.notification.dao.NotificationsDao; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.dtos.NotificationsStatus; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.openecomp.core.nosqldb.impl.cassandra.CassandraSessionFactory.getSession; + +//import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; +//import java.util.Optional; + +public class NotificationsDaoCassandraImpl extends CassandraBaseDao<NotificationEntity> + implements NotificationsDao { + + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper<NotificationEntity> mapper = + noSqlDb.getMappingManager().mapper(NotificationEntity.class); + private static final NotificationsAccessor accessor = + noSqlDb.getMappingManager().createAccessor(NotificationsAccessor.class); + + @Override + protected Mapper<NotificationEntity> getMapper() { + return mapper; + } + + @Override + protected Object[] getKeys(NotificationEntity entity) { + return new Object[]{entity.getOwnerId(), entity.getEventId()}; + } + + @Override + public List<NotificationEntity> list(NotificationEntity entity) { + return accessor.list(entity.getOwnerId()).all(); + } + + @Override + public List<NotificationEntity> getNotificationsByOwnerId(String ownerId, int limit) { + return accessor.getNotifications(ownerId, limit).all(); + } + + @Override + public List<NotificationEntity> getNewNotificationsByOwnerId(String ownerId, UUID eventId) { + return getNewNotificationsByOwnerId(ownerId, eventId, + DEFAULT_LIMIT_OF_RESULTS_FOR_OWNER_NOTIFICATIONS); + } + + @Override + public List<NotificationEntity> getNewNotificationsByOwnerId(String ownerId, UUID eventId, int limit) { + if (Objects.isNull(eventId)) { + return getNotificationsByOwnerId(ownerId, limit); + } + return accessor.getNewNotifications(ownerId, eventId, limit).all(); + } + + @Override + public void markNotificationAsRead(String ownerId, Collection<UUID> eventIds) { + eventIds.forEach(eventId -> accessor.markAsRead(ownerId, eventId)); + } + + @Override + public NotificationsStatus getNotificationsStatus(String ownerId, UUID lastScannedEventId, int numOfRecordsToReturn) { + NotificationsStatusImpl notificationsStatus = new NotificationsStatusImpl(); + List<NotificationEntity> entities = accessor.getNotifications(ownerId, numOfRecordsToReturn).all(); + if (CollectionUtils.isNotEmpty(entities)) { + long lastSeen = UUIDs.unixTimestamp(lastScannedEventId); + populateNewNotifications(notificationsStatus, entities, lastSeen); + UUID firstScannedEventId = entities.get(0).getEventId(); + notificationsStatus.setLastScanned(firstScannedEventId); + notificationsStatus.setNumOfNotSeenNotifications(accessor.getNewNotificationsCount(ownerId, lastScannedEventId, firstScannedEventId).one().getLong(0)); + } + return notificationsStatus; + } + + private void populateNewNotifications(NotificationsStatusImpl notificationsStatus, List<NotificationEntity> entities, long lastSeen) { + for (NotificationEntity entity : entities) { + UUID eventId = entity.getEventId(); + notificationsStatus.addNotification(entity); + if (UUIDs.unixTimestamp(eventId) > lastSeen) { + notificationsStatus.addNewNotificationUUID(eventId); + } + } + } + + @Override + public NotificationsStatus getNotificationsStatus(String ownerId, UUID lastSeenNotification, int numOfRecordsToReturn, UUID prevLastScannedEventId) { + NotificationsStatusImpl notificationsStatus = new NotificationsStatusImpl(); + List<NotificationEntity> entities = accessor.getPrevNotifications(ownerId, prevLastScannedEventId, numOfRecordsToReturn).all(); + if (CollectionUtils.isNotEmpty(entities)) { + long lastSeen = UUIDs.unixTimestamp(lastSeenNotification); + populateNewNotifications(notificationsStatus, entities, lastSeen); + } + return notificationsStatus; + } + +/* + @Override + public NotificationsStatus getNotificationsStatus(String ownerId, + LastSeenNotificationEntity lastSeenNotification, + int numOfRecordsToReturn) { + + List<NotificationEntity> notificationEntities = + fetchNewNotifications(lastSeenNotification, numOfRecordsToReturn); + NotificationsStatusImpl notificationsStatus = new NotificationsStatusImpl(); + if (CollectionUtils.isEmpty(notificationEntities)) { + return notificationsStatus; + } + + notificationEntities.forEach(notification -> { + if (isNewNotification(lastSeenNotification, notification)) { + notificationsStatus.addNewNotificationUUID(notification.getEventId()); + } + notificationsStatus.addNotification(notification); + }); + + Optional<NotificationEntity> latestNotification = notificationEntities.stream().findFirst(); + latestNotification.ifPresent(e -> notificationsStatus.setLastScanned(e.getEventId())); + return notificationsStatus; + } + + private List<NotificationEntity> fetchNewNotifications( + LastSeenNotificationEntity lastSeenNotification, int numOfRecordsToReturn) { + String ownerId = lastSeenNotification.getOwnerId(); + UUID lastEventId = lastSeenNotification.getLastEventId(); + List<NotificationEntity> newNotificationsByOwnerId = + getNewNotificationsByOwnerId(ownerId, lastEventId); + newNotificationsByOwnerId = fetchMoreIfNeeded(ownerId, newNotificationsByOwnerId, + numOfRecordsToReturn, lastEventId); + return newNotificationsByOwnerId; + } + + private boolean isNewNotification(LastSeenNotificationEntity lastSeenNotification, + NotificationEntity notification) { + return Objects.isNull(lastSeenNotification.getLastEventId()) || + UUIDs.unixTimestamp(notification.getEventId()) > + UUIDs.unixTimestamp(lastSeenNotification.getLastEventId()); + } +*/ + + @Override + public void createBatch(List<NotificationEntity> notificationEntities) { + BatchStatement batch = new BatchStatement(); + List<Statement> statements = notificationEntities.stream() + .map(mapper::saveQuery) + .collect(Collectors.toList()); + batch.addAll(statements); + getSession().execute(batch); + } + + @Accessor + interface NotificationsAccessor { + + @Query("select * from notifications where owner_id=?") + Result<NotificationEntity> list(String ownerId); + + @Query("select * from notifications where owner_id=? limit ?") + Result<NotificationEntity> getNotifications(String ownerId, int limit); + + @Query("select * from notifications where owner_id=? and event_id > ? limit ?") + Result<NotificationEntity> getNewNotifications(String ownerId, UUID lastScannedEventId, int limit); + + @Query("select * from notifications where owner_id=? and event_id < ? limit ?") + Result<NotificationEntity> getPrevNotifications(String ownerId, UUID prevLastScannedEventId, int limit); + + @Query("select count(*) from notifications where owner_id=? and event_id > ? and event_id <= ?") + ResultSet getNewNotificationsCount(String ownerId, UUID lastScannedEventId, UUID firstScannedEventId); + + @Query("update notifications set read=true where owner_id=? and event_id=?") + ResultSet markAsRead(String ownerId, UUID eventId); + } + + private class NotificationsStatusImpl implements NotificationsStatus { + + private List<NotificationEntity> notifications = new ArrayList<>(); + private List<UUID> newEntries = new ArrayList<>(); + private UUID lastScanned; + private UUID endOfPage; + private long numOfNotSeenNotifications = 0; + + void addNotification(NotificationEntity notification) { + notifications.add(notification); + endOfPage = notification.getEventId(); + } + + void addNewNotificationUUID(UUID notificationUuid) { + newEntries.add(notificationUuid); + } + + @Override + public List<NotificationEntity> getNotifications() { + return Collections.unmodifiableList(notifications); + } + + @Override + public List<UUID> getNewEntries() { + return Collections.unmodifiableList(newEntries); + } + + @Override + public UUID getLastScanned() { + return lastScanned; + } + + void setLastScanned(UUID lastScanned) { + this.lastScanned = lastScanned; + } + + @Override + public UUID getEndOfPage() { + return endOfPage; + } + + @Override + public long getNumOfNotSeenNotifications() { + return numOfNotSeenNotifications; + } + + void setNumOfNotSeenNotifications(long numOfNotSeenNotifications) { + this.numOfNotSeenNotifications = numOfNotSeenNotifications; + } + } + +/* + private List<NotificationEntity> fetchMoreIfNeeded(String ownerId, + List<NotificationEntity> notificationEntities, + int numOfRecordsToReturn, UUID lastEventId) { + + if (numOfRecordsToReturn <= notificationEntities.size() || Objects.isNull(lastEventId)) { + return notificationEntities; + } + + int multiplier = 2; + while (numOfRecordsToReturn > notificationEntities.size()) { + + int bring = notificationEntities.size() + + (numOfRecordsToReturn - notificationEntities.size()) * multiplier; + notificationEntities = getNotificationsByOwnerId(ownerId, bring); + + if (notificationEntities.size() < bring) { + return notificationEntities; + } + multiplier++; + } + return notificationEntities; + } +*/ + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/SubscribersDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/SubscribersDaoCassandraImpl.java new file mode 100644 index 0000000000..8e8cf9b181 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/dao/impl/SubscribersDaoCassandraImpl.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.dao.impl; + +import com.datastax.driver.mapping.Mapper; +import com.datastax.driver.mapping.Result; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import com.google.common.collect.Sets; +import org.openecomp.core.dao.impl.CassandraBaseDao; +import org.openecomp.core.nosqldb.api.NoSqlDb; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; +import org.openecomp.sdc.notification.dao.SubscribersDao; +import org.openecomp.sdc.notification.dao.types.SubscribersEntity; + +import java.util.Collection; +import java.util.Collections; +import java.util.Objects; +import java.util.Set; + +import static java.util.Objects.isNull; + +public class SubscribersDaoCassandraImpl extends CassandraBaseDao<SubscribersEntity> implements + SubscribersDao { + + private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + private static final Mapper<SubscribersEntity> mapper = + noSqlDb.getMappingManager().mapper(SubscribersEntity.class); + private static final SubscribersAccessor accessor = + noSqlDb.getMappingManager().createAccessor(SubscribersAccessor.class); + + + @Override + protected Object[] getKeys(SubscribersEntity entity) { + return new Object[]{entity.getEntityId()}; + } + + @Override + protected Mapper<SubscribersEntity> getMapper() { + return mapper; + } + + @Override + public void subscribe(String ownerId, String entityId) { + Objects.requireNonNull(ownerId); + Objects.requireNonNull(entityId); + accessor.subscribe(Sets.newHashSet(ownerId), entityId); + } + + @Override + @Deprecated + public Collection<SubscribersEntity> list(SubscribersEntity entity) { + throw new UnsupportedOperationException(); + } + + @Override + public void unsubscribe(String ownerId, String entityId) { + Objects.requireNonNull(ownerId); + Objects.requireNonNull(entityId); + accessor.unsubscribe(Sets.newHashSet(ownerId), entityId); + } + + @Override + public Set<String> getSubscribers(String entityId) { + Objects.requireNonNull(entityId); + SubscribersEntity subscribersEntity = accessor.getSubscribers(entityId).one(); + if (isNull(subscribersEntity)) { + return Collections.emptySet(); + } + return subscribersEntity.getSubscribers(); + } + + @Accessor + interface SubscribersAccessor { + + @Query("select * from notification_subscribers where entity_id=?") + Result<SubscribersEntity> getSubscribers(String entityId); + + @Query("update notification_subscribers set subscribers=subscribers+? WHERE entity_id=?") + void subscribe(Set<String> ownerId, String entityId); + + @Query("update notification_subscribers set subscribers=subscribers-? WHERE entity_id=?") + void unsubscribe(Set<String> ownerId, String entityId); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/LastNotificationDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/LastNotificationDaoFactoryImpl.java new file mode 100644 index 0000000000..7ac9e00967 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/LastNotificationDaoFactoryImpl.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.dao.LastNotificationDao; +import org.openecomp.sdc.notification.dao.impl.LastNotificationDaoCassandraImpl; +import org.openecomp.sdc.notification.factories.LastNotificationDaoFactory; + +/** + * @author itzikpa + * @since June 23, 2017 + */ + +public class LastNotificationDaoFactoryImpl extends LastNotificationDaoFactory { + private static final LastNotificationDao INSTANCE = new LastNotificationDaoCassandraImpl(); + + @Override + public LastNotificationDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationPropagationManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationPropagationManagerFactoryImpl.java new file mode 100644 index 0000000000..7b9e51e8c9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationPropagationManagerFactoryImpl.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory; +import org.openecomp.sdc.notification.factories.PropagationServiceFactory; +import org.openecomp.sdc.notification.factories.SubscriptionServiceFactory; +import org.openecomp.sdc.notification.services.NotificationPropagationManager; +import org.openecomp.sdc.notification.services.impl.NotificationPropagationManagerImpl; + +public class NotificationPropagationManagerFactoryImpl extends + NotificationPropagationManagerFactory { + private static final NotificationPropagationManager INSTANCE = new NotificationPropagationManagerImpl( + PropagationServiceFactory.getInstance().createInterface(), SubscriptionServiceFactory + .getInstance().createInterface()); + + @Override + public NotificationPropagationManager createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsDaoFactoryImpl.java new file mode 100644 index 0000000000..edb020637b --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsDaoFactoryImpl.java @@ -0,0 +1,18 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.dao.NotificationsDao; +import org.openecomp.sdc.notification.dao.impl.NotificationsDaoCassandraImpl; +import org.openecomp.sdc.notification.factories.NotificationsDaoFactory; + +/** + * @author Avrahamg + * @since June 20, 2017 + */ +public class NotificationsDaoFactoryImpl extends NotificationsDaoFactory { + private static final NotificationsDao INSTANCE = new NotificationsDaoCassandraImpl(); + + @Override + public NotificationsDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsServiceFactoryImpl.java new file mode 100644 index 0000000000..ac265e3c8c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/NotificationsServiceFactoryImpl.java @@ -0,0 +1,22 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.factories.LastNotificationDaoFactory; +import org.openecomp.sdc.notification.factories.NotificationsDaoFactory; +import org.openecomp.sdc.notification.factories.NotificationsServiceFactory; +import org.openecomp.sdc.notification.services.NotificationsService; +import org.openecomp.sdc.notification.services.impl.NotificationsServiceImpl; + +/** + * @author Avrahamg + * @since June 20, 2017 + */ +public class NotificationsServiceFactoryImpl extends NotificationsServiceFactory { + private static final NotificationsService INSTANCE = new NotificationsServiceImpl( + LastNotificationDaoFactory.getInstance().createInterface(), NotificationsDaoFactory + .getInstance().createInterface()); + + @Override + public NotificationsService createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/PropagationServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/PropagationServiceFactoryImpl.java new file mode 100644 index 0000000000..e5987fe266 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/PropagationServiceFactoryImpl.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.factories.NotificationsDaoFactory; +import org.openecomp.sdc.notification.factories.PropagationServiceFactory; +import org.openecomp.sdc.notification.services.PropagationService; +import org.openecomp.sdc.notification.services.impl.PropagationServiceImpl; + +public class PropagationServiceFactoryImpl extends PropagationServiceFactory { + private static final PropagationService INSTANCE = new PropagationServiceImpl( + NotificationsDaoFactory.getInstance().createInterface()); + + @Override + public PropagationService createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscribersDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscribersDaoFactoryImpl.java new file mode 100644 index 0000000000..fb87b944f9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscribersDaoFactoryImpl.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.dao.SubscribersDao; +import org.openecomp.sdc.notification.dao.impl.SubscribersDaoCassandraImpl; +import org.openecomp.sdc.notification.factories.SubscribersDaoFactory; + + +public class SubscribersDaoFactoryImpl extends SubscribersDaoFactory { + private static final SubscribersDao INSTANCE = new SubscribersDaoCassandraImpl(); + + @Override + public SubscribersDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscriptionServiceFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscriptionServiceFactoryImpl.java new file mode 100644 index 0000000000..604cff0b5e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/factories/impl/SubscriptionServiceFactoryImpl.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.notification.factories.impl; + +import org.openecomp.sdc.notification.factories.SubscribersDaoFactory; +import org.openecomp.sdc.notification.factories.SubscriptionServiceFactory; +import org.openecomp.sdc.notification.services.SubscriptionService; +import org.openecomp.sdc.notification.services.impl.SubscriptionServiceImpl; + + +public class SubscriptionServiceFactoryImpl extends SubscriptionServiceFactory { + private static final SubscriptionService INSTANCE = new SubscriptionServiceImpl + (SubscribersDaoFactory.getInstance().createInterface()); + + @Override + public SubscriptionService createInterface() { + return INSTANCE; + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImpl.java new file mode 100644 index 0000000000..d381268b3f --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImpl.java @@ -0,0 +1,35 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.openecomp.sdc.destinationprovider.impl.MulticastDestination; +import org.openecomp.sdc.destinationprovider.impl.UnicastDestination; +import org.openecomp.sdc.notification.dtos.Event; +import org.openecomp.sdc.notification.services.NotificationPropagationManager; +import org.openecomp.sdc.notification.services.PropagationService; +import org.openecomp.sdc.notification.services.SubscriptionService; + +/** + * @author avrahamg + * @since July 10, 2017 + */ +public class NotificationPropagationManagerImpl implements NotificationPropagationManager { + + private PropagationService propagationService; + private SubscriptionService subscriptionService; + + public NotificationPropagationManagerImpl(PropagationService propagationService, + SubscriptionService subscriptionService) { + this.propagationService = propagationService; + this.subscriptionService = subscriptionService; + } + + @Override + public void notifySubscribers(Event event, String ... excludedSubscribers) { + propagationService.notify(event, new MulticastDestination(event.getEntityId(), + subscriptionService, excludedSubscribers)); + } + + @Override + public void directNotification(Event event, String destinationId) { + propagationService.notify(event, new UnicastDestination(destinationId)); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImpl.java new file mode 100644 index 0000000000..8a7ab8bdae --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImpl.java @@ -0,0 +1,92 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.openecomp.sdc.notification.dao.LastNotificationDao; +import org.openecomp.sdc.notification.dao.NotificationsDao; +import org.openecomp.sdc.notification.dao.types.LastSeenNotificationEntity; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.dtos.NotificationsStatus; +import org.openecomp.sdc.notification.exceptons.NotificationNotExistException; +import org.openecomp.sdc.notification.services.NotificationsService; + +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +/** + * @author Avrahamg + * @since June 26, 2017 + */ +public class NotificationsServiceImpl implements NotificationsService { + + private LastNotificationDao lastNotificationDao; + private NotificationsDao notificationsDao; + + public NotificationsServiceImpl(LastNotificationDao lastNotificationDao, + NotificationsDao notificationsDao) { + this.lastNotificationDao = lastNotificationDao; + this.notificationsDao = notificationsDao; + } + + @Override + public LastSeenNotificationEntity getLastNotification(String ownerId) { + return new LastSeenNotificationEntity(ownerId, + lastNotificationDao.getOwnerLastEventId(ownerId)); + } + + @Override + public void updateLastSeenNotification(String ownerId, UUID eventId) + { + lastNotificationDao.persistOwnerLastEventId(ownerId, eventId); + } + + @Override + public NotificationsStatus getNotificationsStatus(String ownerId, UUID lastDelivered, int numOfRecordsToReturn, UUID endOfPage) { + if (Objects.isNull(lastDelivered)) { + LastSeenNotificationEntity entity = getLastNotification(ownerId); + if (Objects.nonNull(entity)) { + lastDelivered = entity.getLastEventId(); + } + if (Objects.isNull(lastDelivered)) { + lastDelivered = UUID.fromString("00000000-0000-1000-8080-808080808080"); // Lowest time UUID value + } + } + if (Objects.isNull(endOfPage)) { + // First page + return notificationsDao.getNotificationsStatus(ownerId, lastDelivered, numOfRecordsToReturn); + } + else { + // Next page + return notificationsDao.getNotificationsStatus(ownerId, lastDelivered, numOfRecordsToReturn, endOfPage); + } + } + + @Override + public void markAsRead(String ownerId, String notificationId) throws + NotificationNotExistException { + NotificationEntity notificationEntity = + notificationsDao.get(new NotificationEntity(ownerId, UUID.fromString(notificationId))); + if (Objects.isNull(notificationEntity)) { + throw new NotificationNotExistException( + "Notification '" + notificationId + "' is not related to ownerId" + + " '" + ownerId + "'"); + } + notificationEntity.setRead(true); + notificationsDao.update(notificationEntity); + } + + @Override + public List<NotificationEntity> getNotificationsByOwnerId(String ownerId, int limit) { + return notificationsDao.getNotificationsByOwnerId(ownerId, limit); + } + + @Override + public List<NotificationEntity> getNewNotificationsByOwnerId(String ownerId, UUID eventId) { + return notificationsDao.getNewNotificationsByOwnerId(ownerId, eventId); + } + + @Override + public List<NotificationEntity> getNewNotificationsByOwnerId(String ownerId, UUID eventId, int limit) { + return notificationsDao.getNewNotificationsByOwnerId(ownerId, eventId, limit); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImpl.java new file mode 100644 index 0000000000..99d35b3726 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImpl.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.services.impl; + +import com.datastax.driver.core.utils.UUIDs; +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.notification.dao.NotificationsDao; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.dtos.Event; +import org.openecomp.sdc.notification.services.PropagationService; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +import static java.util.Objects.requireNonNull; + +public class PropagationServiceImpl implements PropagationService { + + private NotificationsDao notificationsDao; + + public PropagationServiceImpl(NotificationsDao notificationsDao) { + this.notificationsDao = notificationsDao; + } + + + @Override + public void notify(Event event, DestinationProvider destinationProvider) { + requireNonNull(event.getEventType()); + requireNonNull(event.getOriginatorId()); + List<String> subscribers = destinationProvider.getSubscribers(); + if (CollectionUtils.isEmpty(subscribers)) { + return; + } + List<NotificationEntity> notificationEntities = subscribers.stream().map( + subscriber -> { + UUID eventId = UUIDs.timeBased(); + return createNotificationEntity(event.getEventType(), subscriber, + event.getOriginatorId(), event.getAttributes(), eventId); + }).collect(Collectors.toList()); + if(CollectionUtils.isNotEmpty(notificationEntities)) { + notificationsDao.createBatch(notificationEntities); + } + } + + private NotificationEntity createNotificationEntity(String eventType, String subscriber, + String originatorId, + Map<String, Object> attributes, + UUID eventId) { + NotificationEntity notificationEntity = + new NotificationEntity(subscriber, eventId, eventType, originatorId); + if (attributes != null && !attributes.isEmpty()) { + notificationEntity.setEventAttributes(JsonUtil.object2Json(attributes)); + } + return notificationEntity; + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/SubscriptionServiceImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/SubscriptionServiceImpl.java new file mode 100644 index 0000000000..2a12463fae --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/java/org/openecomp/sdc/notification/services/impl/SubscriptionServiceImpl.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.services.impl; + +import org.openecomp.sdc.notification.dao.SubscribersDao; +import org.openecomp.sdc.notification.services.SubscriptionService; + +import java.util.Set; + +public class SubscriptionServiceImpl implements SubscriptionService { + + private SubscribersDao subscribersDao; + + public SubscriptionServiceImpl(SubscribersDao subscribersDao) { + this.subscribersDao = subscribersDao; + } + + @Override + public void subscribe(String ownerId, String entityId) { + subscribersDao.subscribe(ownerId, entityId); + } + + @Override + public void unsubscribe(String ownerId, String entityId) { + subscribersDao.unsubscribe(ownerId, entityId); + } + + @Override + public Set<String> getSubscribers(String entityId) { + return subscribersDao.getSubscribers(entityId); + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..3f1bdf3656 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,9 @@ +{ + "org.openecomp.sdc.notification.factories.LastNotificationDaoFactory": "org.openecomp.sdc.notification.factories.impl.LastNotificationDaoFactoryImpl", + "org.openecomp.sdc.notification.factories.NotificationsDaoFactory": "org.openecomp.sdc.notification.factories.impl.NotificationsDaoFactoryImpl", + "org.openecomp.sdc.notification.factories.NotificationsServiceFactory": "org.openecomp.sdc.notification.factories.impl.NotificationsServiceFactoryImpl", + "org.openecomp.sdc.notification.factories.SubscribersDaoFactory": "org.openecomp.sdc.notification.factories.impl.SubscribersDaoFactoryImpl", + "org.openecomp.sdc.notification.factories.PropagationServiceFactory": "org.openecomp.sdc.notification.factories.impl.PropagationServiceFactoryImpl", + "org.openecomp.sdc.notification.factories.SubscriptionServiceFactory": "org.openecomp.sdc.notification.factories.impl.SubscriptionServiceFactoryImpl", + "org.openecomp.sdc.notification.factories.NotificationPropagationManagerFactory": "org.openecomp.sdc.notification.factories.impl.NotificationPropagationManagerFactoryImpl" +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestinationTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestinationTest.java new file mode 100644 index 0000000000..a0dd00632e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/destinationprovider/impl/MulticastDestinationTest.java @@ -0,0 +1,67 @@ +package org.openecomp.sdc.destinationprovider.impl; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.notification.services.SubscriptionService; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; + +/** + * @author avrahamg + * @since July 13, 2017 + */ +public class MulticastDestinationTest { + @Mock + private SubscriptionService subscriptionServiceMock; + + private final String excludedSubscriber = "excluded"; + private Set<String> subscribers = new HashSet<>(Arrays.asList("a", "b", excludedSubscriber)); + private MulticastDestination multicastDestination; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void shouldReturnAllSubscribersIfNoExcludedProvided() throws Exception { + doReturn(subscribers).when(subscriptionServiceMock).getSubscribers(any()); + multicastDestination = new MulticastDestination("aa", subscriptionServiceMock); + assertEquals(subscribers.size(), multicastDestination.getSubscribers().size()); + List<String> actualSubscribers = multicastDestination.getSubscribers(); + assertTrue(actualSubscribers.containsAll(subscribers)); + } + + @Test + public void shouldReturnAllSubscribersExceptExcluded() throws Exception { + doReturn(subscribers).when(subscriptionServiceMock).getSubscribers(any()); + multicastDestination = + new MulticastDestination("aa", subscriptionServiceMock, excludedSubscriber); + List<String> actualSubscribers = multicastDestination.getSubscribers(); + assertNotEquals(this.subscribers.size(), actualSubscribers.size()); + assertFalse(actualSubscribers.containsAll(subscribers)); + assertFalse(actualSubscribers.contains(excludedSubscriber)); + } + + @Test(expected = UnsupportedOperationException.class) + public void shouldThrowUnsupportedOperationExceptionWhenTryingToChangeSubscribersList() throws + Exception { + doReturn(subscribers).when(subscriptionServiceMock).getSubscribers(any()); + multicastDestination = + new MulticastDestination("aa", subscriptionServiceMock, excludedSubscriber); + List<String> actualSubscribers = multicastDestination.getSubscribers(); + actualSubscribers.add("sss"); + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImplTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImplTest.java new file mode 100644 index 0000000000..0eb2b6235c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationPropagationManagerImplTest.java @@ -0,0 +1,64 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.destinationprovider.impl.MulticastDestination; +import org.openecomp.sdc.destinationprovider.impl.UnicastDestination; +import org.openecomp.sdc.notification.dtos.Event; +import org.openecomp.sdc.notification.services.PropagationService; +import org.openecomp.sdc.notification.services.SubscriptionService; + +import static org.mockito.Mockito.verify; + + +/** + * @author avrahamg + * @since July 13, 2017 + */ +public class NotificationPropagationManagerImplTest { + @Mock + private PropagationService propagationServiceMock; + @Mock + private SubscriptionService subscriptionServiceMock; + @Mock + private Event eventMock; + @Captor + private ArgumentCaptor<DestinationProvider> destinationProviderCaptor; + + @Spy + @InjectMocks + private NotificationPropagationManagerImpl notificationPropagationManager; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void shouldCallPropagationServiceNotifyWithMulticastDestinationWhenNotifySubscribers() + throws Exception { + notificationPropagationManager.notifySubscribers(eventMock); + verify(propagationServiceMock).notify(Matchers.eq(eventMock), destinationProviderCaptor + .capture()); + Assert.assertTrue(destinationProviderCaptor.getValue() instanceof MulticastDestination); + + } + + @Test + public void shouldCallPropagationServiceNotifyWithUnicastDestinationWhenDirectNotification() + throws Exception { + notificationPropagationManager.directNotification(eventMock, "aaa"); + verify(propagationServiceMock).notify(Matchers.eq(eventMock), destinationProviderCaptor + .capture()); + Assert.assertTrue(destinationProviderCaptor.getValue() instanceof UnicastDestination); + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImplTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImplTest.java new file mode 100644 index 0000000000..a20d0cce45 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/NotificationsServiceImplTest.java @@ -0,0 +1,50 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.notification.dao.LastNotificationDao; +import org.openecomp.sdc.notification.dao.NotificationsDao; +import org.openecomp.sdc.notification.dao.types.NotificationEntity; +import org.openecomp.sdc.notification.exceptons.NotificationNotExistException; + +import java.util.UUID; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +/** + * @author avrahamg + * @since July 13, 2017 + */ +public class NotificationsServiceImplTest { + @Mock + private LastNotificationDao lastNotificationDao; + @Mock + private NotificationsDao notificationsDao; + @Spy + @InjectMocks + private NotificationsServiceImpl notificationsService; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + public void shouldCallNotificationsDaoIfNotificationEntityExist() throws Exception { + doReturn(new NotificationEntity()).when(notificationsDao).get(any()); + notificationsService.markAsRead("ownerId", UUID.randomUUID().toString()); + verify(notificationsDao, times(1)).update(any()); + } + + @Test(expected = NotificationNotExistException.class) + public void shouldThrowExceptionIfOwnerIdAndNotificationIdDontRelate() throws Exception { + doReturn(null).when(notificationsDao).get(any()); + notificationsService.markAsRead("ownerId", UUID.randomUUID().toString()); + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImplTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImplTest.java new file mode 100644 index 0000000000..866dec0d6d --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-core/src/test/java/org/openecomp/sdc/notification/services/impl/PropagationServiceImplTest.java @@ -0,0 +1,96 @@ +package org.openecomp.sdc.notification.services.impl; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.openecomp.sdc.destinationprovider.DestinationProvider; +import org.openecomp.sdc.notification.dao.NotificationsDao; +import org.openecomp.sdc.notification.dtos.Event; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + +import static org.mockito.Matchers.anyList; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +/** + * @author avrahamg + * @since July 13, 2017 + */ +public class PropagationServiceImplTest { + @Mock + private NotificationsDao notificationsDaoMock; + @Mock + private Event eventMock; + @Mock + private DestinationProvider destinationProviderMock; + @Captor + private ArgumentCaptor<List> createBatchCaptor; + + @Rule + public ExpectedException thrown= ExpectedException.none(); + + @InjectMocks + @Spy + private PropagationServiceImpl propagationService; + private List<String> subscribersList = Arrays.asList("A1, A2, A3");; + + @Before + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + initEventMock(); + } + + @Test + public void shouldCallToNotificationsDaoWithCreateBatchWithNotificationEntitiesAsNumberOfSubscribers() + throws Exception { + doReturn(subscribersList).when(destinationProviderMock).getSubscribers(); + propagationService.notify(eventMock, destinationProviderMock); + verify(notificationsDaoMock).createBatch(createBatchCaptor.capture()); + Assert.assertEquals(createBatchCaptor.getValue().size(), subscribersList.size()); + } + + @Test + public void shouldNotCallNotificationDaoIfSubscriberIsNull() throws Exception { + doReturn(Collections.EMPTY_LIST).when(destinationProviderMock).getSubscribers(); + verify(notificationsDaoMock,never()).createBatch(anyList()); + } + + @Test + public void shouldThrowExceptionIfEventTypeIsNull() throws Exception { + doReturn(null).when(eventMock).getEventType(); + callToNotify(); + } + + @Test + public void shouldThrowExceptionIfOriginatorIdIsNull() throws Exception { + doReturn(null).when(eventMock).getOriginatorId(); + callToNotify(); + } + + private void callToNotify() { + thrown.expect(NullPointerException.class); + propagationService.notify(eventMock, destinationProviderMock); + } + + private void initEventMock() { + doReturn("eventType").when(eventMock).getEventType(); + doReturn("originator").when(eventMock).getOriginatorId(); + doReturn("entity").when(eventMock).getEntityId(); + doReturn(new HashMap<>()).when(eventMock).getAttributes(); + } + + +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/pom.xml new file mode 100644 index 0000000000..abff87f1ad --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/pom.xml @@ -0,0 +1,34 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <name>openecomp-sdc-notification-websocket</name> + <artifactId>openecomp-sdc-notification-websocket</artifactId> + + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>../..</relativePath> + </parent> + + <dependencies> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-notification-worker</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-websocket</artifactId> + <version>4.3.4.RELEASE</version> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.3.1</version> + </dependency> + </dependencies> + +</project> diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/src/main/java/org/openecomp/sdc/notification/websocket/NotificationWebsocketHandler.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/src/main/java/org/openecomp/sdc/notification/websocket/NotificationWebsocketHandler.java new file mode 100644 index 0000000000..1e424631f7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-websocket/src/main/java/org/openecomp/sdc/notification/websocket/NotificationWebsocketHandler.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.websocket; + +import com.google.gson.Gson; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.notification.types.NotificationsStatusDto; +import org.openecomp.sdc.notification.workers.NotificationWorker; +import org.springframework.http.HttpHeaders; +import org.springframework.web.socket.CloseStatus; +import org.springframework.web.socket.TextMessage; +import org.springframework.web.socket.WebSocketSession; +import org.springframework.web.socket.handler.TextWebSocketHandler; + +import java.io.IOException; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Consumer; + +public class NotificationWebsocketHandler extends TextWebSocketHandler { + + private static final String USER_ID_HEADER_PARAM = "USER_ID"; + private static final String LAST_DELIVERED_QUERY_PARAM = "LAST_DELIVERED_EVENT_ID"; + private static final String COOKIE = "Cookie"; + private static Logger LOGGER = LoggerFactory.getLogger(NotificationWebsocketHandler.class); + private NotificationWorker worker; + + public NotificationWebsocketHandler(NotificationWorker worker) { + super(); + this.worker = Objects.requireNonNull(worker, "NotificationWorker object is not initialized."); + } + + @Override + public void afterConnectionEstablished(WebSocketSession session) throws Exception { + super.afterConnectionEstablished(session); + + String ownerId = getOwnerId(session); + if (ownerId == null) { + return; + } + UUID lastDelivered = getLastEventId(session); + + Consumer<NotificationsStatusDto> notesProcessor = (notes) -> notifyReceiver(session, notes); + + worker.register(ownerId, lastDelivered, notesProcessor); + } + + @Override + public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { + String ownerId = getOwnerId(session); + if (ownerId != null) { + worker.unregister(ownerId); + } + super.afterConnectionClosed(session, status); + } + + private void notifyReceiver(WebSocketSession session, NotificationsStatusDto notificationsStatusDto) { + + try { + session.sendMessage(new TextMessage(new Gson().toJson(notificationsStatusDto))); + } catch (IOException e) { + LOGGER.error("IO Exception during Receiver notification.", e); + } + } + + private String getOwnerId(WebSocketSession session) { + + HttpHeaders handshakeHeaders = session.getHandshakeHeaders(); + if (handshakeHeaders.containsKey(COOKIE)) { + String[] cookies = handshakeHeaders.get(COOKIE).get(0).split("; "); + Optional<String> cookie = extractValue(cookies, USER_ID_HEADER_PARAM); + if (cookie.isPresent()) { + return cookie.get(); + } + } + + LOGGER.error("No " + USER_ID_HEADER_PARAM + " specified in the session cookies."); + return null; + } + + private UUID getLastEventId(WebSocketSession session) { + + String uriQuery = session.getUri().getQuery(); + if (uriQuery != null) { + + String[] queries = uriQuery.split("; "); + Optional<String> paramValue = extractValue(queries, LAST_DELIVERED_QUERY_PARAM); + if (paramValue.isPresent()) { + return UUID.fromString(paramValue.get()); + } + } + + LOGGER.warn("No " + LAST_DELIVERED_QUERY_PARAM + " specified in the request URI."); + return null; + } + + private Optional<String> extractValue(String[] pairs, String name) { + + for (String nameValuePair : pairs) { + + String[] value = nameValuePair.split("="); + if (value[0].equals(name)) { + return Optional.of(value[1]); + } + } + + return Optional.empty(); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/pom.xml new file mode 100644 index 0000000000..fb55d28017 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/pom.xml @@ -0,0 +1,73 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <name>openecomp-sdc-notification-worker</name> + <artifactId>openecomp-sdc-notification-worker</artifactId> + + <parent> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-sdc-lib</artifactId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>../..</relativePath> + </parent> + + <dependencies> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-utilities-lib</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.codehaus.jackson</groupId> + <artifactId>jackson-jaxrs</artifactId> + <version>${org.codehaus.jackson.version}</version> + </dependency> + <dependency> + <groupId>org.codehaus.jackson</groupId> + <artifactId>jackson-core-asl</artifactId> + <version>${org.codehaus.jackson.version}</version> + </dependency> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-websocket</artifactId> + <version>4.3.4.RELEASE</version> + </dependency> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.3.1</version> + </dependency> + <dependency> + <groupId>com.googlecode.json-simple</groupId> + <artifactId>json-simple</artifactId> + <version>1.1</version> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.4.1</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpcore</artifactId> + <version>4.4.1</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>com.datastax.cassandra</groupId> + <artifactId>cassandra-driver-core</artifactId> + <version>2.0.1</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + <version>${junit.version}</version> + </dependency> + </dependencies> + +</project> diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/config/ConfigurationManager.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/config/ConfigurationManager.java new file mode 100644 index 0000000000..d960b8b9dc --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/config/ConfigurationManager.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.config; + +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.tosca.services.YamlUtil; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.BiConsumer; + +public class ConfigurationManager { + + private static final String CONFIGURATION_YAML_FILE = "onboarding_configuration.yaml"; + private static final String NOTIFICATIONS_CONFIG = "notifications"; + + private LinkedHashMap<String, Object> notificationsConfiguration; + private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationManager.class); + private static final ConfigurationManager SINGLETON = new ConfigurationManager(); + + public static ConfigurationManager getInstance() { + return SINGLETON; + } + + private ConfigurationManager() { + initConfiguration(); + } + + private void initConfiguration() { + + YamlUtil yamlUtil = new YamlUtil(); + readConfigurationFromStream(yamlUtil, (filename, stream) -> { + + if (stream == null) { + LOGGER.warn("Configuration not found: " + filename + ". Using defaults"); + return; + } + + Map<String, LinkedHashMap<String, Object>> configurationMap = yamlUtil.yamlToMap(stream); + if (configurationMap == null) { + LOGGER.warn("Configuration cannot be parsed: " + filename + ". Using defaults"); + return; + } + + notificationsConfiguration = configurationMap.get(NOTIFICATIONS_CONFIG); + if (notificationsConfiguration == null) { + LOGGER.error(NOTIFICATIONS_CONFIG + + " is missing in configuration file '" + filename + "'. Using defaults"); + } + }); + } + + private void readConfigurationFromStream(YamlUtil yamlUtil, + BiConsumer<String, InputStream> reader) { + + String configurationYamlFile = System.getProperty(CONFIGURATION_YAML_FILE); + + try { + + if (configurationYamlFile == null) { + + try (InputStream inputStream = + yamlUtil.loadYamlFileIs("/" + CONFIGURATION_YAML_FILE)) { + reader.accept(CONFIGURATION_YAML_FILE, inputStream); + } + + } else { + + try (InputStream inputStream = new FileInputStream(configurationYamlFile)) { + reader.accept(configurationYamlFile, inputStream); + } + } + + } catch (IOException e) { + LOGGER.error("Failed to read configuration", e); + } + } + + public <T> T getConfigValue(String name, T defaultValue) { + + Object value = notificationsConfiguration.get(name); + + try { + return value == null ? defaultValue : (T) value; + } catch (ClassCastException e) { + LOGGER.warn(String.format("Failed to read configuration property '%s' as requested type. Using default '%s'", + name, defaultValue), e); + return defaultValue; + } + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationEntityDto.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationEntityDto.java new file mode 100644 index 0000000000..a415d9e081 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationEntityDto.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.types; + +import java.util.Map; +import java.util.UUID; + +public class NotificationEntityDto { + private boolean read; + private UUID eventId; + private String dateTime; + private String eventType; + private Map<String, Object> eventAttributes; + + public NotificationEntityDto() { + } + public NotificationEntityDto(boolean read, UUID eventId, String eventType, + Map<String, Object> eventAttributes) { + this.read = read; + this.eventId = eventId; + this.eventType = eventType; + this.eventAttributes = eventAttributes; + } + + public NotificationEntityDto(boolean read, UUID eventId,String eventType, + Map<String, Object> eventAttributes, String dateTime) { + this.read = read; + this.eventId = eventId; + this.dateTime = dateTime; + this.eventType = eventType; + this.eventAttributes = eventAttributes; + } + + public boolean isRead() { + return read; + } + + public void setRead(boolean read) { + this.read = read; + } + + public UUID getEventId() { + return eventId; + } + + public void setEventId(UUID eventId) { + this.eventId = eventId; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public Map<String, Object> getEventAttributes() { + return eventAttributes; + } + + public void setEventAttributes(Map<String, Object> eventAttributes) { + this.eventAttributes = eventAttributes; + } + + public String getDateTime() { + return dateTime; + } + + public void setDateTime(String dateTime) { + this.dateTime = dateTime; + } + + @Override + public String toString() { + return "NotificationEntityDto {" + + ", state='" + (read ? "Read" : "Noread") + '\'' + + ", dateTime='" + dateTime + '\'' + + ", eventId='" + eventId + '\'' + + ", eventType='" + eventType + '\'' + + ", eventAttributes='" + eventAttributes + '\'' + + '}'; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationsStatusDto.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationsStatusDto.java new file mode 100644 index 0000000000..fd8d32090e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/types/NotificationsStatusDto.java @@ -0,0 +1,72 @@ +package org.openecomp.sdc.notification.types; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * @author avrahamg + * @since June 29, 2017 + */ +public class NotificationsStatusDto { + private List<NotificationEntityDto> notifications; + private List<UUID> newEntries = new ArrayList<>(); + private UUID lastScanned; + private UUID endOfPage; + private long numOfNotSeenNotifications; + + public NotificationsStatusDto() { + } + + public List<NotificationEntityDto> getNotifications() { + return notifications; + } + + public void setNotifications( + List<NotificationEntityDto> notifications) { + this.notifications = notifications; + } + + public List<UUID> getNewEntries() { + return newEntries; + } + + public void setNewEntries(List<UUID> newEntries) { + this.newEntries = newEntries; + } + + public UUID getLastScanned() { + return lastScanned; + } + + public void setLastScanned(UUID lastScanned) { + this.lastScanned = lastScanned; + } + + public UUID getEndOfPage() { + return endOfPage; + } + + public void setEndOfPage(UUID endOfPage) { + this.endOfPage = endOfPage; + } + + public long getNumOfNotSeenNotifications() { + return numOfNotSeenNotifications; + } + + public void setNumOfNotSeenNotifications(long numOfNotSeenNotifications) { + this.numOfNotSeenNotifications = numOfNotSeenNotifications; + } + + @Override + public String toString() { + return "NotificationsStatusDto{" + + "notifications=" + notifications + + ", newEntries=" + newEntries + + ", lastScanned=" + lastScanned + + ", endOfPage=" + endOfPage + + ", numOfNotSeenNotifications=" + numOfNotSeenNotifications + + '}'; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NewNotificationsReader.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NewNotificationsReader.java new file mode 100644 index 0000000000..75b9f5c786 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NewNotificationsReader.java @@ -0,0 +1,29 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.workers; + +import org.openecomp.sdc.notification.types.NotificationsStatusDto; + +import java.util.UUID; + +public interface NewNotificationsReader { + NotificationsStatusDto getNewNotifications(String ownerId, UUID eventId, int limit); +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationReceiver.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationReceiver.java new file mode 100644 index 0000000000..ee802640c4 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationReceiver.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.workers; + +import org.openecomp.sdc.notification.types.NotificationsStatusDto; + +import java.util.UUID; +import java.util.function.Consumer; + + + +public class NotificationReceiver { + + public String ownerId = null; + public Consumer<NotificationsStatusDto> notesProcessor = null; + public UUID lastEventId = null; + + NotificationReceiver(String ownerId, UUID lastEventId, Consumer<NotificationsStatusDto> notesProcessor) { + this.ownerId = ownerId; + this.lastEventId = lastEventId; + this.notesProcessor = notesProcessor; + } + + NotificationReceiver(String ownerId, Consumer<NotificationsStatusDto> notesProcessor) { + this(ownerId, null, notesProcessor); + } + + public void setOwnerId(String ownerId) { + this.ownerId = ownerId; + } + + public String getOwnerId() { + return this.ownerId; + } + + public void setNotesProcessor(Consumer<NotificationsStatusDto> notesProcessor) { + this.notesProcessor = notesProcessor; + } + + public Consumer<NotificationsStatusDto> getNotesProcessor() { + return this.notesProcessor; + } + + public void setLastEventId(UUID lastEventId) { + this.lastEventId = lastEventId; + } + + public UUID getlastEventId() { + return this.lastEventId; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationWorker.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationWorker.java new file mode 100644 index 0000000000..e8c2006d5c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/NotificationWorker.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.workers; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.notification.config.ConfigurationManager; +import org.openecomp.sdc.notification.types.NotificationsStatusDto; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; + +public class NotificationWorker { + + private static final int DEFAULT_POLLING_INTERVAL = 2000; + private static final String POLLING_INTERVAL = "pollingIntervalMsec"; + private static final int DEFAULT_SELECTION_LIMIT = 10; + private static final String SELECTION_SIZE = "selectionSize"; + + private static boolean stopRunning = false; + + private int selectionLimit = DEFAULT_SELECTION_LIMIT; + private int pollingSleepInterval = DEFAULT_POLLING_INTERVAL; + + private static final Logger LOGGER = LoggerFactory.getLogger(NotificationWorker.class); + + private static Map<String, NotificationReceiver> activeUsers = new ConcurrentHashMap<>(); + private NewNotificationsReader news = null; + + public NotificationWorker(NewNotificationsReader news) { + ConfigurationManager cm = ConfigurationManager.getInstance(); + pollingSleepInterval = cm.getConfigValue(POLLING_INTERVAL, DEFAULT_POLLING_INTERVAL); + selectionLimit = cm.getConfigValue(SELECTION_SIZE, DEFAULT_SELECTION_LIMIT); + + Objects.requireNonNull(news, "NotificationNews object is not initialized."); + this.news = news; + + NotificationWorker.Poller p = new Poller(); + Thread thread = new Thread(p); + thread.start(); + } + + public Map<String, NotificationReceiver> getActiveUsers() { + return activeUsers; + } + + public class Poller extends Thread { + public void run() { + try { + while (!stopRunning) { + pollNotifications(); + Thread.sleep(pollingSleepInterval); + } + } + catch (InterruptedException e) { + LOGGER.error("Interrupted Exception during Notification poller launch.", e); + } + } + + private void pollNotifications() { + + Map<String, NotificationReceiver> currUsers = new HashMap<>(); + currUsers.putAll(getActiveUsers()); + + for (NotificationReceiver receiver : currUsers.values()) { + String ownerId = receiver.getOwnerId(); + UUID eventId = receiver.getlastEventId(); + NotificationsStatusDto status = news.getNewNotifications(ownerId, eventId, selectionLimit); + if(Objects.nonNull(status) && CollectionUtils.isNotEmpty(status.getNotifications())) { + receiver.setLastEventId(status.getLastScanned()); + receiver.getNotesProcessor().accept(status); + } + } + } + + } + + public void register(String ownerId, UUID lastDelivered, Consumer<NotificationsStatusDto> notesProcessor) { + NotificationReceiver receiver = new NotificationReceiver(ownerId, lastDelivered, notesProcessor); + activeUsers.put(ownerId, receiver); + LOGGER.debug("User {} is registered with eventId: {}", ownerId, receiver.getlastEventId()); + } + + public void unregister(String ownerId) { + activeUsers.remove(ownerId); + LOGGER.debug("User {} is unregistered.", ownerId); + } + + public void stopPolling() { + LOGGER.debug("Stop notification polling."); + stopRunning = true; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/impl/NewNotificationsReaderRestImpl.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/impl/NewNotificationsReaderRestImpl.java new file mode 100644 index 0000000000..a332efaf5a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/java/org/openecomp/sdc/notification/workers/impl/NewNotificationsReaderRestImpl.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.workers.impl; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.HttpClientBuilder; +import org.codehaus.jackson.map.ObjectMapper; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.notification.config.ConfigurationManager; +import org.openecomp.sdc.notification.types.NotificationsStatusDto; +import org.openecomp.sdc.notification.workers.NewNotificationsReader; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import java.io.InputStreamReader; +import java.util.UUID; + +public class NewNotificationsReaderRestImpl implements NewNotificationsReader { + + private static final String USER_ID_HEADER_PARAM = "USER_ID"; + private static final String LAST_DELIVERED_QUERY_PARAM = "LAST_DELIVERED_EVENT_ID"; + private static final String LIMIT_QUERY_PARAM = "NOTIFICATION_ROWS_LIMIT"; + private static final String BE_HOST = "beHost"; + private static final String BE_PORT = "beHttpPort"; + private static final String DEFAULT_BE_HOST = "localhost"; + private static final int DEFAULT_BE_PORT = 8080; + private static final String URL = "http://%s:%d/onboarding-api/v1.0/notifications/worker?"; + private static final ObjectMapper mapper = new ObjectMapper(); + + private static String beHost; + private static int bePort; + + private static final Logger LOGGER = LoggerFactory.getLogger(NewNotificationsReaderRestImpl.class); + + public NewNotificationsReaderRestImpl() { + ConfigurationManager cm = ConfigurationManager.getInstance(); + bePort = cm.getConfigValue(BE_PORT, DEFAULT_BE_PORT); + beHost = cm.getConfigValue(BE_HOST, DEFAULT_BE_HOST); + } + + public NotificationsStatusDto getNewNotifications(String ownerId, UUID eventId, int limit) { + HttpClient client = HttpClientBuilder.create().build(); + String url = String.format(URL, beHost, bePort); + + url = url + LIMIT_QUERY_PARAM + "=" + limit; + if (eventId != null) { + url = url + "&" + LAST_DELIVERED_QUERY_PARAM + "=" + eventId; + } + + HttpGet request = new HttpGet(url); + request.addHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + request.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + request.addHeader(USER_ID_HEADER_PARAM, ownerId); + + try { + HttpResponse response = client.execute(request); + return mapper.readValue(new InputStreamReader(response.getEntity().getContent()), NotificationsStatusDto.class); + } catch (Exception e) { + LOGGER.error("Failed to execute the request {}", url, e); + return null; + } + } +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..5f5693fb92 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.config.api.ConfigurationManager": "org.openecomp.config.impl.ConfigurationImpl" +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/onboarding_configuration.yaml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/onboarding_configuration.yaml new file mode 100644 index 0000000000..a1b7ba5d9e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/main/resources/onboarding_configuration.yaml @@ -0,0 +1,5 @@ +notifications: + pollingIntervalMsec: 2000 + selectionSize: 10 + beHost: localhost + beHttpPort: 8080 diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/java/org/openecomp/sdc/notification/workers/NotificationWorkerTest.java b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/java/org/openecomp/sdc/notification/workers/NotificationWorkerTest.java new file mode 100644 index 0000000000..457ba071cd --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/java/org/openecomp/sdc/notification/workers/NotificationWorkerTest.java @@ -0,0 +1,134 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.notification.workers; + +import com.datastax.driver.core.utils.UUIDs; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.notification.types.NotificationEntityDto; +import org.openecomp.sdc.notification.types.NotificationsStatusDto; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +//import org.junit.Before; + + +public class NotificationWorkerTest { + + private static final String OWNER = "owner_1"; + + private String fileName = null; + private NewNotificationsReader news = this.new SimNewNotificationsReader(); + private NotificationWorker worker = new NotificationWorker(news); + + @BeforeClass + public static void beforeClass() throws Exception { + } + + @Test + public void testBasicResourceCreation() throws IOException, InterruptedException { + + Consumer<NotificationsStatusDto> notesProcessor = this::notifyReceiver; + + fileName = "notification_1.csv"; + + worker.register(OWNER, null, notesProcessor); + worker.register("owner_2", null, notesProcessor); + worker.register("owner_3", null, notesProcessor); + + int pollInterval = 2000; + Thread.sleep(pollInterval); + + worker.unregister("owner_2"); + + fileName = "notification_2.csv"; + + Thread.sleep(pollInterval); + + worker.stopPolling(); + + } + + private void notifyReceiver(NotificationsStatusDto notes) { + if (Objects.nonNull(notes)) { + System.out.println("Received notes:"); + System.out.println(notes); + } + } + + + private class SimNewNotificationsReader implements NewNotificationsReader { + + + private String resourcesDir = "src/test/resources/"; + + public NotificationsStatusDto getNewNotifications(String ownerId, UUID eventId, int limit) { + if (fileName == null) { + return null; + } + String fn = fileName; + fileName = null; + + return getNotifications(fn); + } + + private NotificationsStatusDto getNotifications(String fn) { + NotificationsStatusDto notificationsStatusDto = new NotificationsStatusDto(); + List<NotificationEntityDto> inputList = new ArrayList<>(); + try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(resourcesDir + fn))))) { + int limit = 10; + inputList = br.lines().skip(1).limit(limit).map(mapToEntity).collect(Collectors.toCollection(ArrayList::new)); + } catch (IOException e) { + System.err.println("getNotifications(): file " + resourcesDir + fn + " open exception: " + e.getMessage()); + } + notificationsStatusDto.setNotifications(inputList); + notificationsStatusDto.setLastScanned(inputList.get(0).getEventId()); + return notificationsStatusDto; + } + + private Function<String, NotificationEntityDto> mapToEntity = (line) -> { + String[] p = line.split("\\|"); + NotificationEntityDto entity = new NotificationEntityDto(); + DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT); + entity.setRead(Boolean.parseBoolean(p[1])); + entity.setEventId(UUID.fromString(p[2])); + entity.setEventType(p[4]); + entity.setDateTime(formatter.format(UUIDs.unixTimestamp(entity.getEventId()))); + entity.setEventAttributes(JsonUtil.json2Object(p[5], Map.class)); + return entity; + }; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/logback.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/logback.xml new file mode 100644 index 0000000000..c1932e31e8 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/logback.xml @@ -0,0 +1,15 @@ +<configuration> + + <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> + <!-- encoders are assigned the type + ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> + <encoder> + <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> + </encoder> + </appender> + + <root level="warn"> + <appender-ref ref="STDOUT" /> + </root> + +</configuration>
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_1.csv b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_1.csv new file mode 100644 index 0000000000..8b7de38ce5 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_1.csv @@ -0,0 +1,11 @@ +# Owner|Read|EventId|EventType|OriginatorId|EventAttributes +owner_1|false|1dc38a90-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc387d4-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38702-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc385fe-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc384a0-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc383c4-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc3818a-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc380b8-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc37fdc-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc37ee2-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_2.csv b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_2.csv new file mode 100644 index 0000000000..565e80bce8 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/notification_2.csv @@ -0,0 +1,11 @@ +# Owner|Read|EventId|EventType|OriginatorId|EventAttributes +owner_1|false|1dc39346-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc39288-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc391c0-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38f2c-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38e64-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38da6-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38ce8-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38c2a-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc38b62-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} +owner_1|false|1dc37c08-5e85-11e7-907b-a6006ad3dba0|type_1|orig_1|{attr_1: val_1, attr_2: val_2} diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/onboarding_configuration.yaml b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/onboarding_configuration.yaml new file mode 100644 index 0000000000..cc04531c7c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/openecomp-sdc-notification-worker/src/test/resources/onboarding_configuration.yaml @@ -0,0 +1,5 @@ +notifications: + pollingIntervalMsec: 3000 + selectionSize: 5 + beHost: localhost + beHttpPort: 8080 diff --git a/openecomp-be/lib/openecomp-sdc-notification-lib/pom.xml b/openecomp-be/lib/openecomp-sdc-notification-lib/pom.xml new file mode 100644 index 0000000000..9dc0dcfd3e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-notification-lib/pom.xml @@ -0,0 +1,23 @@ +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <name>openecomp-sdc-notification-lib</name> + <artifactId>openecomp-sdc-notification-lib</artifactId> + + <packaging>pom</packaging> + <parent> + <artifactId>openecomp-sdc-lib</artifactId> + <groupId>org.openecomp.sdc</groupId> + <version>1.2.0-SNAPSHOT</version> + <relativePath>..</relativePath> + </parent> + + <modules> + <module>openecomp-sdc-notification-api</module> + <module>openecomp-sdc-notification-core</module> + <module>openecomp-sdc-notification-worker</module> + <module>openecomp-sdc-notification-websocket</module> + </modules> + +</project> diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/services/ManualVspToscaGenerationService.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/services/ManualVspToscaGenerationService.java index 6ec7bfca9f..8234179017 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/services/ManualVspToscaGenerationService.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/services/ManualVspToscaGenerationService.java @@ -1,21 +1,5 @@ package org.openecomp.sdc.generator.core.services; -import static org.openecomp.sdc.generator.util.GeneratorConstants.ALLOWED_FLAVORS_PROPERTY; -import static org.openecomp.sdc.generator.util.GeneratorConstants.DISK_SIZE; -import static org.openecomp.sdc.generator.util.GeneratorConstants.DISK_SIZE_PROP_DESC_PREFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.IMAGES_PROPERTY; -import static org.openecomp.sdc.generator.util.GeneratorConstants.MEM_SIZE; -import static org.openecomp.sdc.generator.util.GeneratorConstants.MEM_SIZE_PROP_DESC_PREFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.NUM_CPUS; -import static org.openecomp.sdc.generator.util.GeneratorConstants.NUM_CPUS_PROP_DESC_PREFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_NODE_TEMPLATE_ID_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_TYPE_EXTERNAL_NODE_TEMPLATE_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_TYPE_INTERNAL_NODE_TEMPLATE_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.RELEASE_VENDOR; -import static org.openecomp.sdc.generator.util.GeneratorConstants.TOSCA_SERVICE_TEMPLATE_FILE_NAME_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.VNF_CONFIG_NODE_TEMPLATE_ID_SUFFIX; -import static org.openecomp.sdc.generator.util.GeneratorConstants.VNF_NODE_TEMPLATE_ID_SUFFIX; - import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.generator.core.utils.GeneratorUtils; @@ -48,6 +32,22 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import static org.openecomp.sdc.generator.util.GeneratorConstants.ALLOWED_FLAVORS_PROPERTY; +import static org.openecomp.sdc.generator.util.GeneratorConstants.DISK_SIZE; +import static org.openecomp.sdc.generator.util.GeneratorConstants.DISK_SIZE_PROP_DESC_PREFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.IMAGES_PROPERTY; +import static org.openecomp.sdc.generator.util.GeneratorConstants.MEM_SIZE; +import static org.openecomp.sdc.generator.util.GeneratorConstants.MEM_SIZE_PROP_DESC_PREFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.NUM_CPUS; +import static org.openecomp.sdc.generator.util.GeneratorConstants.NUM_CPUS_PROP_DESC_PREFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_NODE_TEMPLATE_ID_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_TYPE_EXTERNAL_NODE_TEMPLATE_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.PORT_TYPE_INTERNAL_NODE_TEMPLATE_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.RELEASE_VENDOR; +import static org.openecomp.sdc.generator.util.GeneratorConstants.TOSCA_SERVICE_TEMPLATE_FILE_NAME_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.VNF_CONFIG_NODE_TEMPLATE_ID_SUFFIX; +import static org.openecomp.sdc.generator.util.GeneratorConstants.VNF_NODE_TEMPLATE_ID_SUFFIX; + /** * The type Manual vsp tosca generator. */ @@ -329,7 +329,6 @@ public class ManualVspToscaGenerationService { ToscaServiceModel toscaServiceModel, String substitutionNodeTypeId, String componentName) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); ServiceTemplate globalSubstitutionServiceTemplate = fetchGlobalSubstitutionServiceTemplate(); NodeType substitutionNodeType = createGlobalSubstitutionNodeType(substitutionServiceTemplate, componentName); diff --git a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java index 7e493f2151..129929ae30 100644 --- a/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java +++ b/openecomp-be/lib/openecomp-sdc-tosca-generator-lib/openecomp-sdc-tosca-generator-core/src/main/java/org/openecomp/sdc/generator/core/utils/GeneratorUtils.java @@ -1,7 +1,5 @@ package org.openecomp.sdc.generator.core.utils; -import static org.openecomp.sdc.tosca.services.DataModelUtil.addSubstitutionNodeTypeRequirements; - import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; @@ -29,6 +27,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import static org.openecomp.sdc.tosca.services.DataModelUtil.addSubstitutionNodeTypeRequirements; + /** * The type Generator utils. */ diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java index 3686a516b3..87c578cd5d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java @@ -20,7 +20,6 @@ package org.openecomp.sdc.translator.datatypes.heattotosca; -import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.openecomp.config.api.Configuration; import org.openecomp.config.api.ConfigurationManager; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java index d3f2a721c9..628186e9d7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java @@ -3,7 +3,6 @@ package org.openecomp.sdc.translator.services.heattotosca; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java index 895b3f9670..9d875d20f4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java @@ -27,10 +27,9 @@ import org.openecomp.core.translator.datatypes.TranslatorOutput; import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.common.togglz.ToggleableFeature; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.core.validation.util.MessageContainerUtil; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.togglz.ToggleableFeature; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; @@ -73,9 +72,10 @@ import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; -import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedPropertyVal; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.ReferenceType; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java index 244434c1b8..bd0fbcb47a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca; -import static org.openecomp.sdc.tosca.services.DataModelUtil.getClonedObject; -import static org.openecomp.sdc.translator.services.heattotosca.Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX; -import static org.openecomp.sdc.translator.services.heattotosca.Constants.COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX; -import static org.openecomp.sdc.translator.services.heattotosca.Constants.COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX; -import static org.openecomp.sdc.translator.services.heattotosca.Constants.PORT_IDENTICAL_VALUE_PROPERTY_PREFIX; - import org.apache.commons.collections.map.HashedMap; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; @@ -94,6 +88,12 @@ import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; +import static org.openecomp.sdc.tosca.services.DataModelUtil.getClonedObject; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.COMPUTE_IDENTICAL_VALUE_PROPERTY_PREFIX; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.COMPUTE_IDENTICAL_VALUE_PROPERTY_SUFFIX; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.PORT_IDENTICAL_VALUE_PROPERTY_PREFIX; + public class UnifiedCompositionService { protected static Logger logger = diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java index 531de16998..dff208f101 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java @@ -5,8 +5,8 @@ import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; +import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.utils.ResourceWalker; import java.util.HashMap; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java index ef75f315f6..87bf36b9d5 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.helper; -import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE; - import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; @@ -45,6 +43,8 @@ import java.util.Optional; import java.util.function.Predicate; import java.util.stream.Collectors; +import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE; + public class VolumeTranslationHelper { private final Logger logger; private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java index 48d564227e..1d35795e4c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.heat.services.HeatConstants; @@ -29,6 +28,7 @@ import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java index bc0926c9d0..374f8a9ebe 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java @@ -30,8 +30,8 @@ import org.openecomp.sdc.tosca.datatypes.model.Template; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.tosca.services.ToscaFileOutputService; import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; -import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import java.util.ArrayList; import java.util.HashMap; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java index 877659ee10..184aa52424 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java @@ -25,9 +25,9 @@ import org.openecomp.sdc.heat.datatypes.model.HeatPseudoParameters; import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; -import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import java.util.ArrayList; import java.util.HashMap; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java index b2d11e3804..ce160cee49 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java @@ -23,8 +23,8 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslati import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.model.Template; -import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; import org.openecomp.sdc.translator.services.heattotosca.helper.FunctionTranslationHelper; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java index b0094b0a7c..459c44e117 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.apache.commons.collections4.MapUtils; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; @@ -44,6 +43,7 @@ import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java index 231190a16f..3a3a7c7817 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java @@ -20,7 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import org.openecomp.sdc.common.utils.CommonUtil; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; @@ -32,7 +31,6 @@ import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java index 72739d3f51..e439935517 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java @@ -22,7 +22,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslati import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java index 4cf817bcae..ea8f78a20a 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; - import org.apache.commons.lang3.StringUtils; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.datatypes.error.ErrorLevel; @@ -56,6 +54,8 @@ import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatT import java.util.List; import java.util.Optional; +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; + public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTranslationBase { protected static Logger logger = (Logger) LoggerFactory.getLogger(ResourceTranslationCinderVolumeAttachmentImpl.class); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java index d729c04cca..90206cf7c7 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java @@ -20,11 +20,11 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; @@ -32,9 +32,9 @@ import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java index 71efc18816..d12075de27 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java @@ -20,7 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import org.openecomp.sdc.common.utils.CommonUtil; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java index 875903f8a2..9ed59e04db 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java @@ -24,9 +24,9 @@ import org.apache.commons.collections4.CollectionUtils; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.ToscaGroupType; import org.openecomp.sdc.tosca.datatypes.ToscaPolicyType; +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; import org.openecomp.sdc.tosca.datatypes.model.PolicyDefinition; -import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java index 96c105c04a..2a2ecf919e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java @@ -44,14 +44,12 @@ import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; - import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; import org.openecomp.sdc.translator.services.heattotosca.Constants; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; - import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; import java.util.ArrayList; @@ -398,28 +396,23 @@ public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { private void manageNovaServerNetwork(TranslateTo translateTo, NodeTemplate novaNodeTemplate) { + mdcDataDebugMessage.debugEntryMessage(null, null); - - String heatFileName = translateTo.getHeatFileName(); - ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); - HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo - .getHeatOrchestrationTemplate(); Resource resource = translateTo.getResource(); String translatedId = translateTo.getTranslatedId(); - TranslationContext context = translateTo.getContext(); - - mdcDataDebugMessage.debugEntryMessage(null, null); if (resource.getProperties() == null) { return; } - List<Map<String, Object>> heatNetworkList = - (List<Map<String, Object>>) resource.getProperties().get("networks"); - - if (CollectionUtils.isEmpty(heatNetworkList)) { + Object networks = resource.getProperties().get("networks"); + if(Objects.isNull(networks) + || !(networks instanceof List)){ return; } + List<Map<String, Object>> heatNetworkList = + (List<Map<String, Object>>) networks; + for (Map<String, Object> heatNetwork : heatNetworkList) { getOrTranslatePortTemplate(translateTo, heatNetwork.get( Constants.PORT_PROPERTY_NAME), translatedId, novaNodeTemplate); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java index 3d183b1ad9..b32ea2d9de 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; import org.openecomp.sdc.heat.datatypes.manifest.FileData; - import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; import org.openecomp.sdc.heat.datatypes.model.Resource; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/TestUtils.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/TestUtils.java index 27298ff9b4..c7d3931961 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/TestUtils.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/TestUtils.java @@ -36,7 +36,19 @@ import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.*; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileComputeConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileNestedConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FilePortConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.RequirementAssignmentData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.TypeComputeConsolidationData; import java.io.File; import java.io.FileInputStream; @@ -45,7 +57,13 @@ import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.NotDirectoryException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; public class TestUtils { private static final String MANIFEST_NAME = SdcCommon.MANIFEST_NAME; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/impl/heattotosca/resources/OSNovaServerTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/impl/heattotosca/resources/OSNovaServerTest.java index ebb34503bb..9743483d42 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/impl/heattotosca/resources/OSNovaServerTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/impl/heattotosca/resources/OSNovaServerTest.java @@ -20,9 +20,6 @@ package org.openecomp.sdc.translator.impl.heattotosca.resources; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_PORT_POSITIVE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; @@ -30,6 +27,9 @@ import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslatio import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_PORT_POSITIVE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_POSITIVE; + public class OSNovaServerTest extends BaseResourceTranslationTest { @Override diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtilTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtilTest.java index 019d143792..3f294eb924 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtilTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtilTest.java @@ -1,6 +1,7 @@ package org.openecomp.sdc.translator.services.heattotosca; import org.testng.annotations.Test; + import static org.testng.Assert.assertEquals; public class ConsolidationDataUtilTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationServiceTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationServiceTest.java index 085c329e7f..4af2415381 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationServiceTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationServiceTest.java @@ -1,39 +1,5 @@ package org.openecomp.sdc.translator.services.heattotosca; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.apache.commons.lang3.tuple.ImmutablePair; -import org.apache.commons.lang3.tuple.Pair; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Captor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.Spy; -import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.TestUtils; -import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionMode; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - /** * Created by TALIO on 3/7/2017. */ diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionServiceTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionServiceTest.java index 69db1b2d84..7de9ae5588 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionServiceTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionServiceTest.java @@ -1,9 +1,5 @@ package org.openecomp.sdc.translator.services.heattotosca; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; - import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.junit.Before; @@ -13,22 +9,40 @@ import org.mockito.InjectMocks; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.translator.TestUtils; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionEntity; import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedSubstitutionData; -import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.*; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.RequirementAssignmentData; import org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition.UnifiedCompositionSingleSubstitution; import java.io.IOException; import java.net.URL; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.anyString; public class UnifiedCompositionServiceTest { private static final String BASE_DIRECTORY = "/mock/services/heattotosca/unifiedComposition/"; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/buildconsolidationdata/ConsolidationDataTestUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/buildconsolidationdata/ConsolidationDataTestUtil.java index dd48e618d4..bb1f898dc4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/buildconsolidationdata/ConsolidationDataTestUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/buildconsolidationdata/ConsolidationDataTestUtil.java @@ -1,19 +1,5 @@ package org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.MAIN_SERVICE_TEMPLATE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_INVALID_DEPENDENCY_CANDIDATE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_MULTIPLE_COMPUTE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN_AND_OUT; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_OUT; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NO_DEPENDENCY; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_MULTIPLE_MULTI_LEVEL_NESTED_RESOURCE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_MULTIPLE_NESTED_RESOURCE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_MULTI_LEVEL_NESTED_CONNECTION; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_MULTI_LEVEL_NESTED_SHARED_PORT; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_NESTED_CONNECTION; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SINGLE_NESTED_RESOURCE; - import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.collections4.CollectionUtils; import org.junit.Assert; @@ -51,6 +37,20 @@ import java.util.Objects; import java.util.Optional; import java.util.Set; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.MAIN_SERVICE_TEMPLATE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_INVALID_DEPENDENCY_CANDIDATE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_MULTIPLE_COMPUTE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN_AND_OUT; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_OUT; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NO_DEPENDENCY; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_MULTIPLE_MULTI_LEVEL_NESTED_RESOURCE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_MULTIPLE_NESTED_RESOURCE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_MULTI_LEVEL_NESTED_CONNECTION; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_MULTI_LEVEL_NESTED_SHARED_PORT; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SECURITY_RULE_PORT_NESTED_CONNECTION; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_SINGLE_NESTED_RESOURCE; + public class ConsolidationDataTestUtil { public static void validateVolumeInConsolidationData(String computeNodeTemplateId, diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelperTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelperTest.java index 9b4a59b01f..1a108ce42f 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelperTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelperTest.java @@ -31,7 +31,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; /** * @author SHIRIA diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImplTest.java index b79671d763..2a633da55b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImplTest.java @@ -28,8 +28,8 @@ import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.tosca.services.ToscaFileOutputService; import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; -import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; import java.util.HashMap; import java.util.List; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImplTest.java index 981c061e0a..860074ba70 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImplTest.java @@ -30,7 +30,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; public class FunctionTranslationGetParamImplTest extends BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImplTest.java index 9fdd2db4cb..9a249d7b29 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImplTest.java @@ -23,7 +23,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; import org.junit.Assert; import org.junit.Test; import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor.NameExtractorContrailComputeImpl; import java.util.HashMap; import java.util.Map; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImplTest.java index 58237975b6..3095b528e3 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImplTest.java @@ -23,7 +23,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; import org.junit.Test; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor.NameExtractorNovaServerImpl; import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationNovaServerImpl; import java.util.Arrays; @@ -31,7 +30,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.*; +import static org.junit.Assert.assertTrue; /** * @author SHIRIA diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceTranslationTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceTranslationTest.java index 528db5ee77..dcfe1270ea 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceTranslationTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceTranslationTest.java @@ -20,19 +20,6 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.junit.Assert.assertEquals; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateComputeConnectivityIn; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateComputeConnectivityOut; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateDependsOnInConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateGetAttr; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateGroupsInConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortConnectivityIn; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortConnectivityOut; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortsInConsolidationData; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedConsolidationDataNodeTemplateIds; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateVolumeInConsolidationData; - import org.apache.commons.collections4.MapUtils; import org.junit.AfterClass; import org.junit.Assert; @@ -86,6 +73,19 @@ import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; +import static org.junit.Assert.assertEquals; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateComputeConnectivityIn; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateComputeConnectivityOut; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateDependsOnInConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateGetAttr; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateGroupsInConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedConsolidationDataNodeTemplateIds; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortConnectivityIn; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortConnectivityOut; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validatePortsInConsolidationData; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateVolumeInConsolidationData; + public class BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/DependsOnResourceBaseTranslationlTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/DependsOnResourceBaseTranslationlTest.java index 117dd0cd59..9c4c3a40c4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/DependsOnResourceBaseTranslationlTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/DependsOnResourceBaseTranslationlTest.java @@ -20,6 +20,12 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; + +import java.io.IOException; + import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_INVALID_DEPENDENCY_CANDIDATE; import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_MULTIPLE_COMPUTE; import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODES_CONNECTED_IN; @@ -28,12 +34,6 @@ import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidati import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NODE_TEMPLATE_TRANSLATION_ORDER_INVARIANCE; import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_DEPENDS_ON_NO_DEPENDENCY; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; - -import java.io.IOException; - public class DependsOnResourceBaseTranslationlTest extends BaseResourceTranslationTest { @Override diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImplTest.java index 786b613d0f..637b131712 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImplTest.java @@ -20,15 +20,15 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_NEGATIVE; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_NEGATIVE; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_VOLUME_POSITIVE; + public class ResourceTranslationCinderVolumeAttachmentImplTest extends BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImplTest.java index 3e69ed17c0..74a6ce5a5b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImplTest.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_CONNECTIVITY_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_CONNECTIVITY_POSITIVE; + /** * @author Avrahamg * @since August 10, 2016 diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImplTest.java index 854a2632b3..97a59c3934 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImplTest.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_CONNECTIVITY_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_CONNECTIVITY_POSITIVE; + public class ResourceTranslationNeutronPortImplTest extends BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImplTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImplTest.java index 03b9402e01..6767db4217 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImplTest.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_GROUP_POSITIVE; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataValidationType; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants.TEST_GROUP_POSITIVE; + public class ResourceTranslationNovaServerGroupsImplTest extends BaseResourceTranslationTest { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnectionTest.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnectionTest.java index 724f6247af..15bf0f28bc 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnectionTest.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/test/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnectionTest.java @@ -20,14 +20,14 @@ package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; -import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedNodesConnectedInSecurityRuleToPort; - import org.junit.Before; import org.junit.Test; import org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.TestConstants; import java.io.IOException; +import static org.openecomp.sdc.translator.services.heattotosca.buildconsolidationdata.ConsolidationDataTestUtil.validateNestedNodesConnectedInSecurityRuleToPort; + public class SecurityRulesToPortResourceConnectionTest extends BaseResourceTranslationTest { @Override diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/GlobalValidationContext.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/GlobalValidationContext.java index bc401d4a45..97da6ef631 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/GlobalValidationContext.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-api/src/main/java/org/openecomp/core/validation/types/GlobalValidationContext.java @@ -22,9 +22,9 @@ package org.openecomp.core.validation.types; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.validation.ErrorMessageCode; +import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.logging.context.MdcUtil; import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerImpl.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerImpl.java index acb4eed448..2f5a8ce399 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/main/java/org/openecomp/sdc/validation/impl/ValidationManagerImpl.java @@ -21,13 +21,13 @@ package org.openecomp.sdc.validation.impl; import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.core.validation.api.ValidationManager; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.core.validation.types.MessageContainer; import org.openecomp.sdc.datatypes.error.ErrorMessage; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.services.ValidationFactory; import java.util.HashMap; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/test/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/test/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerTest.java index e3464db8d8..e5d1a88821 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/test/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-core/src/test/java/org/openecomp/sdc/heat/services/tree/HeatTreeManagerTest.java @@ -20,7 +20,6 @@ package org.openecomp.sdc.heat.services.tree; -import org.openecomp.config.ConfigurationUtils; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree; @@ -33,9 +32,6 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; public class HeatTreeManagerTest { diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java index 90750a48ec..e437892758 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java @@ -17,13 +17,15 @@ package org.openecomp.sdc.validation.impl.util; import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.sdc.heat.datatypes.model.*; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.DefinedHeatParameterTypes; +import org.openecomp.sdc.heat.datatypes.model.Environment; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.Parameter; +import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; @@ -32,10 +34,18 @@ import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.sdc.validation.impl.validators.HeatValidator; import java.io.InputStream; -import java.util.*; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; public class HeatValidationService { diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java index 5045c80d11..eb23930216 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java @@ -22,9 +22,7 @@ package org.openecomp.sdc.validation.impl.validators; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.tosca.services.YamlUtil; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; @@ -39,6 +37,8 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.tos.ContrailResourcesMappingTo; import org.openecomp.sdc.validation.util.ValidationUtil; @@ -62,7 +62,7 @@ public class ContrailValidator implements Validator { ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { logger.debug("",exception); return; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java index 2dad766c45..2107825c6c 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java @@ -63,7 +63,7 @@ public class ForbiddenResourceGuideLineValidator implements Validator { public void validate(GlobalValidationContext globalContext) { ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { log.debug("",exception); return; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java index 10cfe352f6..89e96efa36 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java @@ -14,7 +14,6 @@ import org.openecomp.sdc.heat.services.HeatStructureUtil; import org.openecomp.sdc.heat.services.manifest.ManifestUtil; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.base.ResourceBaseValidator; import org.openecomp.sdc.validation.type.ConfigConstants; @@ -31,8 +30,7 @@ import java.util.Objects; import java.util.Set; public class HeatResourceValidator extends ResourceBaseValidator { - public static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private static Logger logger = (Logger) LoggerFactory.getLogger(ResourceBaseValidator.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ResourceBaseValidator.class); private static final ErrorMessageCode ERROR_CODE_HTR_1 = new ErrorMessageCode("HTR1"); @Override @@ -42,14 +40,14 @@ public class HeatResourceValidator extends ResourceBaseValidator { @Override public ValidationContext createValidationContext(String fileName, - String envFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { + String envFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { ManifestContent manifestContent = new ManifestContent(); try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { - logger.debug("",exception); + LOGGER.debug("", exception); } Set<String> baseFiles = ManifestUtil.getBaseFiles(manifestContent); String baseFileName = CollectionUtils.isEmpty(baseFiles) ? null : baseFiles.iterator().next(); @@ -58,7 +56,7 @@ public class HeatResourceValidator extends ResourceBaseValidator { ValidationUtil.checkHeatOrchestrationPreCondition(baseFileName, globalContext); Set<String> securityGroupsNamesFromBaseFileOutputs = baseFileName == null ? new HashSet<>() : checkForBaseFilePortsExistenceAndReturnSecurityGroupNamesFromOutputsIfNot - (baseFileName, baseHot, globalContext); + (baseHot); Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources() == null ? new HashMap<>() @@ -86,7 +84,7 @@ public class HeatResourceValidator extends ResourceBaseValidator { GlobalValidationContext globalContext) { initTypeRelationsMapFromResourcesMap - (fileName, resourceMap, securityGroupsNamesFromBaseFileOutputs, + (fileName, resourceMap, typeToPointingResourcesMap, globalContext); initTypeRelationsMapFromOutputsMap @@ -133,13 +131,13 @@ public class HeatResourceValidator extends ResourceBaseValidator { private void initTypeRelationsMapFromResourcesMap(String fileName, Map<String, Resource> resourceMap, - Set<String> securityGroupsNamesFromBaseFileOutputs, Map<String, Map<String, Map<String, List<String>>>> typeToPointingResourcesMap, GlobalValidationContext globalContext) { for (Map.Entry<String, Resource> resourceEntry : resourceMap.entrySet()) { Resource pointingResource = resourceEntry.getValue(); Map<String, Object> properties = - pointingResource.getProperties() == null ? new HashMap<>() : pointingResource.getProperties(); + pointingResource.getProperties() == null ? new HashMap<>() + : pointingResource.getProperties(); Set<String> referencedResourcesByGetResource = getResourcesIdsPointedByCurrentResource(fileName, ResourceReferenceFunctions.GET_RESOURCE, @@ -231,9 +229,9 @@ public class HeatResourceValidator extends ResourceBaseValidator { (pointingResourceType, new ArrayList<>()); } - private Set<String> handleGetAttrBetweenResources(Map<String, Object> properties){ + private Set<String> handleGetAttrBetweenResources(Map<String, Object> properties) { Set<String> referencedResourcesByGetAttr = new HashSet<>(); - for(Map.Entry<String, Object> proprtyEntry : properties.entrySet()){ + for (Map.Entry<String, Object> proprtyEntry : properties.entrySet()) { referencedResourcesByGetAttr.addAll(getGetAttrReferencesInCaseOfContrail(proprtyEntry .getValue())); } @@ -242,7 +240,7 @@ public class HeatResourceValidator extends ResourceBaseValidator { } - private Set<String> getGetAttrReferencesInCaseOfContrail(Object propertyValue){ + private Set<String> getGetAttrReferencesInCaseOfContrail(Object propertyValue) { Object value; Set<String> getAttrReferences = new HashSet<>(); @@ -255,11 +253,11 @@ public class HeatResourceValidator extends ResourceBaseValidator { getAttrReferences.add((String) ((List) value).get(0)); return getAttrReferences; } else { - logger.warn("invalid format of 'get_attr' function - " + propertyValue.toString()); + LOGGER.warn("invalid format of 'get_attr' function - " + propertyValue.toString()); } } } - }else { + } else { Collection<Object> valCollection = ((Map) propertyValue).values(); for (Object entryValue : valCollection) { getAttrReferences.addAll(getGetAttrReferencesInCaseOfContrail(entryValue)); @@ -294,8 +292,7 @@ public class HeatResourceValidator extends ResourceBaseValidator { } private Set<String> checkForBaseFilePortsExistenceAndReturnSecurityGroupNamesFromOutputsIfNot( - String baseFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { + HeatOrchestrationTemplate heatOrchestrationTemplate) { Set<String> securityGroupsNamesFromOutputsMap = new HashSet<>(); if (heatOrchestrationTemplate != null) { diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java index da87a13eb4..8064c6f20a 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java @@ -23,11 +23,6 @@ package org.openecomp.sdc.validation.impl.validators; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; -import org.openecomp.sdc.logging.types.LoggerConstants; -import org.openecomp.sdc.logging.types.LoggerErrorCode; -import org.openecomp.sdc.tosca.services.YamlUtil; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; @@ -48,13 +43,24 @@ import org.openecomp.sdc.heat.services.manifest.ManifestUtil; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.impl.util.HeatValidationService; import org.openecomp.sdc.validation.util.ValidationUtil; import java.io.InputStream; -import java.util.*; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; public class HeatValidator implements Validator { public static final MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @@ -126,91 +132,91 @@ public class HeatValidator implements Validator { : heatOrchestrationTemplate.getResources().values(); Collection<Output> outputsValues = heatOrchestrationTemplate.getOutputs() == null ? null : heatOrchestrationTemplate.getOutputs().values(); - checkResourceExistenceFromResourcesMap(fileName, resourcesNames, resourcesValues, - globalContext); - checkResourceExistenceFromResourcesMap(fileName, resourcesNames, outputsValues, - globalContext); + checkResourceExistenceFromResourcesMap(fileName, resourcesNames, resourcesValues, + globalContext); + checkResourceExistenceFromResourcesMap(fileName, resourcesNames, outputsValues, + globalContext); mdcDataDebugMessage.debugExitMessage("file", fileName); } - private static void checkResourceExistenceFromResourcesMap(String fileName, - Set<String> resourcesNames, - Collection<?> valuesToSearchIn, - GlobalValidationContext globalContext) { - - mdcDataDebugMessage.debugEntryMessage("file", fileName); - - if (CollectionUtils.isNotEmpty(valuesToSearchIn)) { - for (Object value : valuesToSearchIn) { - if (value instanceof Resource) { - extractResourceProperty(fileName, resourcesNames, globalContext, (Resource) value); - } else if (value instanceof Output) { - Output output = (Output) value; - Object outputsValue = output.getValue(); - handleReferencedResources(fileName, outputsValue, resourcesNames, - globalContext); - } - } + private static void checkResourceExistenceFromResourcesMap(String fileName, + Set<String> resourcesNames, + Collection<?> valuesToSearchIn, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + if (CollectionUtils.isNotEmpty(valuesToSearchIn)) { + for (Object value : valuesToSearchIn) { + if (value instanceof Resource) { + extractResourceProperty(fileName, resourcesNames, globalContext, (Resource) value); + } else if (value instanceof Output) { + Output output = (Output) value; + Object outputsValue = output.getValue(); + handleReferencedResources(fileName, outputsValue, resourcesNames, + globalContext); } + } } + } private static void extractResourceProperty(String fileName, Set<String> resourcesNames, GlobalValidationContext globalContext, Resource value) { Resource resource = value; Collection<Object> resourcePropertiesValues = - resource.getProperties() == null ? null : resource.getProperties() - .values(); + resource.getProperties() == null ? null : resource.getProperties() + .values(); if (CollectionUtils.isNotEmpty(resourcePropertiesValues)) { - for (Object propertyValue : resourcePropertiesValues) { - handleReferencedResources(fileName, propertyValue, resourcesNames, - globalContext); - } + for (Object propertyValue : resourcePropertiesValues) { + handleReferencedResources(fileName, propertyValue, resourcesNames, + globalContext); + } } } private static void handleReferencedResources(String fileName, Object valueToSearchReferencesIn, - Set<String> resourcesNames, - GlobalValidationContext globalContext) { - - - mdcDataDebugMessage.debugEntryMessage("file", fileName); - globalContext.setMessageCode(ERROR_CODE_HOT_13); - Set<String> referencedResourcesNames = HeatStructureUtil - .getReferencedValuesByFunctionName(fileName, - ResourceReferenceFunctions.GET_RESOURCE.getFunction(), - valueToSearchReferencesIn, globalContext); - if (CollectionUtils.isNotEmpty(referencedResourcesNames)) { - checkIfResourceReferenceExist(fileName, resourcesNames, referencedResourcesNames, - globalContext); - } + Set<String> resourcesNames, + GlobalValidationContext globalContext) { + - mdcDataDebugMessage.debugExitMessage("file", fileName); + mdcDataDebugMessage.debugEntryMessage("file", fileName); + globalContext.setMessageCode(ERROR_CODE_HOT_13); + Set<String> referencedResourcesNames = HeatStructureUtil + .getReferencedValuesByFunctionName(fileName, + ResourceReferenceFunctions.GET_RESOURCE.getFunction(), + valueToSearchReferencesIn, globalContext); + if (CollectionUtils.isNotEmpty(referencedResourcesNames)) { + checkIfResourceReferenceExist(fileName, resourcesNames, referencedResourcesNames, + globalContext); } - private static void checkIfResourceReferenceExist(String fileName, - Set<String> referencedResourcesNames, - Set<String> referencedResources, - GlobalValidationContext globalContext) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + private static void checkIfResourceReferenceExist(String fileName, + Set<String> referencedResourcesNames, + Set<String> referencedResources, + GlobalValidationContext globalContext) { - mdcDataDebugMessage.debugEntryMessage("file", fileName); - referencedResources.stream() - .filter(referencedResource -> !referencedResourcesNames.contains(referencedResource)) - .forEach(referencedResource -> { - globalContext.addMessage(fileName, - ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_16,Messages - .REFERENCED_RESOURCE_NOT_FOUND.getErrorMessage(), referencedResource), - LoggerTragetServiceName.VALIDATE_RESOURCE_REFERENCE_EXISTENCE, - LoggerErrorDescription.RESOURCE_NOT_FOUND); - }); + mdcDataDebugMessage.debugEntryMessage("file", fileName); - mdcDataDebugMessage.debugExitMessage("file", fileName); - } + referencedResources.stream() + .filter(referencedResource -> !referencedResourcesNames.contains(referencedResource)) + .forEach(referencedResource -> { + globalContext.addMessage(fileName, + ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_16,Messages + .REFERENCED_RESOURCE_NOT_FOUND.getErrorMessage(), referencedResource), + LoggerTragetServiceName.VALIDATE_RESOURCE_REFERENCE_EXISTENCE, + LoggerErrorDescription.RESOURCE_NOT_FOUND); + }); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } /* validation 16 */ @@ -294,79 +300,79 @@ public class HeatValidator implements Validator { mdcDataDebugMessage.debugExitMessage("file", fileName); } - private static void loopOverOutputMapAndValidateGetAttrFromNested(String fileName, - Map<String, Output> outputMap, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext - globalContext) { - for (Output output : outputMap.values()) { - Object outputValue = output.getValue(); - if (outputValue != null && outputValue instanceof Map) { - Map<String, Object> outputValueMap = (Map<String, Object>) outputValue; - List<String> getAttrValue = - (List<String>) outputValueMap.get( - ResourceReferenceFunctions.GET_ATTR.getFunction()); - if (!CollectionUtils.isEmpty(getAttrValue)) { - String resourceName = getAttrValue.get(0); - Object attNameObject = getAttrValue.get(1); - if (!(attNameObject instanceof String)) { - return; - } - String attName = getAttrValue.get(1); - String resourceType = - getResourceTypeFromResourcesMap(resourceName, heatOrchestrationTemplate); - - if (Objects.nonNull(resourceType) - && HeatValidationService.isNestedResource(resourceType)) { - handleGetAttrNestedResource(fileName, globalContext, resourceName, attName, - resourceType); - } - } - } - } - } - - private static void handleGetAttrNestedResource(String fileName, - GlobalValidationContext globalContext, - String resourceName, String attName, - String resourceType) { - Map<String, Output> nestedOutputMap; - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; - try { - Optional<InputStream> fileContent = globalContext.getFileContent(resourceType); - if (fileContent.isPresent()) { - nestedHeatOrchestrationTemplate = - new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); - } else { - MdcDataErrorMessage - .createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, - LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, - ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), - LoggerErrorDescription.EMPTY_FILE); - throw new Exception("The file '" + resourceType + "' has no content"); - } - } catch (Exception exception) { - logger.debug("",exception); + private static void loopOverOutputMapAndValidateGetAttrFromNested(String fileName, + Map<String, Output> outputMap, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + GlobalValidationContext + globalContext) { + for (Output output : outputMap.values()) { + Object outputValue = output.getValue(); + if (outputValue != null && outputValue instanceof Map) { + Map<String, Object> outputValueMap = (Map<String, Object>) outputValue; + List<String> getAttrValue = + (List<String>) outputValueMap.get( + ResourceReferenceFunctions.GET_ATTR.getFunction()); + if (!CollectionUtils.isEmpty(getAttrValue)) { + String resourceName = getAttrValue.get(0); + Object attNameObject = getAttrValue.get(1); + if (!(attNameObject instanceof String)) { return; + } + String attName = getAttrValue.get(1); + String resourceType = + getResourceTypeFromResourcesMap(resourceName, heatOrchestrationTemplate); + + if (Objects.nonNull(resourceType) + && HeatValidationService.isNestedResource(resourceType)) { + handleGetAttrNestedResource(fileName, globalContext, resourceName, attName, + resourceType); + } } - nestedOutputMap = nestedHeatOrchestrationTemplate.getOutputs(); + } + } + } - if (MapUtils.isEmpty(nestedOutputMap) || !nestedOutputMap.containsKey(attName)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_17,Messages. - GET_ATTR_NOT_FOUND.getErrorMessage(), - attName, resourceName), - LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, - LoggerErrorDescription.GET_ATTR_NOT_FOUND); - } + private static void handleGetAttrNestedResource(String fileName, + GlobalValidationContext globalContext, + String resourceName, String attName, + String resourceType) { + Map<String, Output> nestedOutputMap; + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; + try { + Optional<InputStream> fileContent = globalContext.getFileContent(resourceType); + if (fileContent.isPresent()) { + nestedHeatOrchestrationTemplate = + new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); + } else { + MdcDataErrorMessage + .createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, + ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.EMPTY_FILE); + throw new Exception("The file '" + resourceType + "' has no content"); + } + } catch (Exception exception) { + logger.debug("",exception); + return; } + nestedOutputMap = nestedHeatOrchestrationTemplate.getOutputs(); - private static String getResourceTypeFromResourcesMap(String resourceName, - HeatOrchestrationTemplate - heatOrchestrationTemplate) { - return heatOrchestrationTemplate.getResources().get(resourceName).getType(); + if (MapUtils.isEmpty(nestedOutputMap) || !nestedOutputMap.containsKey(attName)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_17,Messages. + GET_ATTR_NOT_FOUND.getErrorMessage(), + attName, resourceName), + LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, + LoggerErrorDescription.GET_ATTR_NOT_FOUND); } + } + + private static String getResourceTypeFromResourcesMap(String resourceName, + HeatOrchestrationTemplate + heatOrchestrationTemplate) { + return heatOrchestrationTemplate.getResources().get(resourceName).getType(); + } /* validation 17 + */ private static void validateEnvFile(String fileName, String envFileName, @@ -416,7 +422,7 @@ public class HeatValidator implements Validator { if (parametersNames != null && !parametersNames.contains(envParameter)) { globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder .getErrorWithParameters( - ERROR_CODE_HOT_3,Messages. + ERROR_CODE_HOT_3,Messages. ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), envFile, envParameter), LoggerTragetServiceName.VALIDATE_ENV_FILE, LoggerErrorDescription.ENV_PARAMETER_NOT_IN_HEAT); @@ -459,7 +465,7 @@ public class HeatValidator implements Validator { if (!isValueMatchDefault) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder .getErrorWithParameters( - ERROR_CODE_HOT_4,Messages. + ERROR_CODE_HOT_4,Messages. PARAMETER_DEFAULT_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), parameterEntry.getKey(), parameterType), LoggerTragetServiceName.VALIDATE_PARAMTER_DEFAULT_MATCH_TYPE, @@ -495,7 +501,7 @@ public class HeatValidator implements Validator { .isValueIsFromGivenType(parameterEnvValue, parameterType)) { globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder .getErrorWithParameters( - ERROR_CODE_HOT_5,Messages. + ERROR_CODE_HOT_5,Messages. PARAMETER_ENV_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), parameterName), LoggerTragetServiceName.VALIDATE_ENV_PARAMETER_MATCH_TYPE, LoggerErrorDescription.PARAMETER_DEFAULT_VALUE_NOT_ALIGNED_WITH_TYPE); @@ -513,7 +519,7 @@ public class HeatValidator implements Validator { mdcDataDebugMessage.debugEntryMessage(null, null); ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { logger.debug("",exception); return; @@ -546,9 +552,9 @@ public class HeatValidator implements Validator { .filter(fileName -> isManifestArtifact(manifestArtifacts, fileName) && isNotArtifact(artifacts, fileName)) .forEach(fileName -> globalContext.addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(ERROR_CODE_HOT_11, - Messages.ARTIFACT_FILE_NOT_REFERENCED.getErrorMessage()), + ErrorMessagesFormatBuilder + .getErrorWithParameters(ERROR_CODE_HOT_11, + Messages.ARTIFACT_FILE_NOT_REFERENCED.getErrorMessage()), LoggerTragetServiceName.CHECK_FOR_ORPHAN_ARTIFACTS, LoggerErrorDescription.ARTIFACT_NOT_REFERENCED)); @@ -567,10 +573,10 @@ public class HeatValidator implements Validator { private void validate(String fileName, String envFileName, String baseFileName, Set<String> artifacts, Set<String> securityGroupsNamesFromBaseFileOutputs, GlobalValidationContext globalContext) { - globalContext.setMessageCode(ERROR_CODE_HOT_12); + globalContext.setMessageCode(ERROR_CODE_HOT_12); HeatOrchestrationTemplate heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition( - fileName, globalContext); + fileName, globalContext); if (heatOrchestrationTemplate != null) { diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java index 2ad2f9afb4..e3a35af6dc 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java @@ -22,7 +22,6 @@ package org.openecomp.sdc.validation.impl.validators; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; @@ -38,6 +37,7 @@ import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.Validator; import java.io.InputStream; import java.util.ArrayList; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java index 724b7e4735..43e8e9404f 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java @@ -1,8 +1,8 @@ package org.openecomp.sdc.validation.impl.validators; -import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.base.ResourceBaseValidator; import org.openecomp.sdc.validation.type.ConfigConstants; import org.openecomp.sdc.validation.type.NamingConventionValidationContext; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java index 424f8d3517..fb7d6a2c97 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java @@ -3,13 +3,10 @@ package org.openecomp.sdc.validation.impl.validators; import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.common.utils.SdcCommon; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; @@ -18,9 +15,12 @@ import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; import org.openecomp.sdc.heat.services.HeatStructureUtil; import org.openecomp.sdc.heat.services.manifest.ManifestUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationUtil; import java.util.HashSet; @@ -44,7 +44,7 @@ public class SharedResourceGuideLineValidator implements Validator { public void validate(GlobalValidationContext globalContext) { ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { log.debug("",exception); return; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java index c0468f8b5a..ab2e427f23 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java @@ -21,8 +21,6 @@ package org.openecomp.sdc.validation.impl.validators; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.tosca.services.YamlUtil; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; @@ -32,6 +30,8 @@ import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.impl.util.YamlValidatorUtil; import java.io.InputStream; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java index 9c9f4bcdc0..33d20d5714 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java @@ -2,7 +2,6 @@ package org.openecomp.sdc.validation.impl.validators.heatresource; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.validation.ErrorMessageCode; -import org.openecomp.sdc.validation.ResourceValidator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; @@ -15,6 +14,7 @@ import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.type.HeatResourceValidationContext; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java index b98b6d6600..795bdf0f9f 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java @@ -1,7 +1,5 @@ package org.openecomp.sdc.validation.impl.validators.namingconvention; -import static java.util.Objects.nonNull; - import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; @@ -36,6 +34,8 @@ import java.util.Map; import java.util.Objects; import java.util.TreeMap; +import static java.util.Objects.nonNull; + public class NovaServerNamingConventionGuideLineValidator implements ResourceValidator { private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private static final ErrorMessageCode ERROR_CODE_NNS1 = new ErrorMessageCode("NNS1"); diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ContrailValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ContrailValidatorTest.java index f921102957..96db0fd19d 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ContrailValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ContrailValidatorTest.java @@ -20,9 +20,9 @@ package org.openecomp.sdc.validation.impl.validators; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.MessageContainer; import org.openecomp.sdc.datatypes.error.ErrorMessage; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ErrorMessagesTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ErrorMessagesTest.java index 64b3d2bb3c..5c2c0c0bf0 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ErrorMessagesTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/ErrorMessagesTest.java @@ -21,10 +21,10 @@ package org.openecomp.sdc.validation.impl.validators; import org.junit.Test; +import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.sdc.common.errors.Messages; import org.testng.Assert; -import org.openecomp.core.validation.ErrorMessageCode; public class ErrorMessagesTest { diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/HeatValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/HeatValidatorTest.java index a523627081..2ec119e665 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/HeatValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/HeatValidatorTest.java @@ -21,8 +21,8 @@ package org.openecomp.sdc.validation.impl.validators; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.MessageContainer; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidatorTest.java index e7c2d37d32..58400b91da 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidatorTest.java @@ -1,7 +1,7 @@ package org.openecomp.sdc.validation.impl.validators; -import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.types.MessageContainer; +import org.openecomp.sdc.validation.Validator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidatorTest.java index 681c54b12e..0db8c221b9 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidatorTest.java @@ -1,9 +1,8 @@ package org.openecomp.sdc.validation.impl.validators.namingconvention; -import org.openecomp.sdc.validation.impl.validators.HeatResourceValidator; - import org.openecomp.core.validation.types.MessageContainer; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.validation.impl.validators.HeatResourceValidator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidatorTest.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidatorTest.java index 1a7b6081d1..3837f3b260 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidatorTest.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/test/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidatorTest.java @@ -1,9 +1,8 @@ package org.openecomp.sdc.validation.impl.validators.namingconvention; -import org.openecomp.sdc.validation.impl.validators.NamingConventionGuideLineValidator; - import org.openecomp.core.validation.types.MessageContainer; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.validation.impl.validators.NamingConventionGuideLineValidator; import org.openecomp.sdc.validation.util.ValidationTestUtil; import org.testng.Assert; import org.testng.annotations.Test; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/base/ResourceBaseValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/base/ResourceBaseValidator.java index c4d6f88074..68c1b74c99 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/base/ResourceBaseValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/base/ResourceBaseValidator.java @@ -4,7 +4,9 @@ import org.apache.commons.collections4.MapUtils; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.validation.ErrorMessageCode; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; @@ -12,15 +14,13 @@ import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.heat.services.HeatStructureUtil; import org.openecomp.sdc.heat.services.manifest.ManifestUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.validation.ResourceValidator; import org.openecomp.sdc.validation.ValidationContext; import org.openecomp.sdc.validation.Validator; -import org.openecomp.core.validation.types.GlobalValidationContext; -import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.validation.type.ConfigConstants; import org.openecomp.sdc.validation.util.ValidationUtil; @@ -54,7 +54,7 @@ public class ResourceBaseValidator implements Validator { public void validate(GlobalValidationContext globalContext) { ManifestContent manifestContent; try { - manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + manifestContent = ValidationUtil.validateManifest(globalContext); } catch (Exception exception) { logger.debug("",exception); return; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java index 2b58a30e50..08a3548a7d 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationTestUtil.java @@ -25,7 +25,6 @@ import org.testng.Assert; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringWriter; import java.net.URL; @@ -97,7 +96,7 @@ public class ValidationTestUtil { String resourceTypeToValidate, String path) { GlobalValidationContext globalContext = createGlobalContextFromPath(path); - ManifestContent manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + ManifestContent manifestContent = ValidationUtil.validateManifest(globalContext); Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); Map<String, FileData> fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent); diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationUtil.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationUtil.java index d9e0351578..76b4aff1f5 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationUtil.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-sdk/src/main/java/org/openecomp/sdc/validation/util/ValidationUtil.java @@ -6,6 +6,7 @@ import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; import org.openecomp.core.validation.types.GlobalValidationContext; import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.common.errors.SdcRuntimeException; import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; @@ -176,7 +177,7 @@ public class ValidationUtil { return false; } - public static ManifestContent checkValidationPreCondition(GlobalValidationContext globalContext) { + public static ManifestContent validateManifest(GlobalValidationContext globalContext) { Optional<InputStream> manifest = globalContext.getFileContent(SdcCommon.MANIFEST_NAME); if (!manifest.isPresent()) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, @@ -192,7 +193,7 @@ public class ValidationUtil { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.VALIDATE_MANIFEST_CONTENT, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_MANIFEST); - throw new RuntimeException("Can't load manifest file for Heat Validator"); + throw new SdcRuntimeException("Can't load manifest file for Heat Validator"); } return manifestContent; diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseUtil.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseUtil.java new file mode 100644 index 0000000000..3ee326af4c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/VendorLicenseUtil.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.vendorlicense; + +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; + +import java.text.ParseException; +import java.text.SimpleDateFormat; + +public class VendorLicenseUtil { + + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + public static String getIsoFormatDate(String inputDate) { + mdcDataDebugMessage.debugEntryMessage("inputDate date", inputDate); + String isoFormatDate = null; + SimpleDateFormat isoDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); + SimpleDateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ss'Z'"); + + try { + isoFormatDate = isoDateFormat.format(inputDateFormat.parse(inputDate)); + } catch (ParseException e) { + mdcDataDebugMessage.debugExitMessage("parsing error", isoFormatDate); + isoFormatDate = null; + } + + mdcDataDebugMessage.debugExitMessage("formatted date", isoFormatDate); + return isoFormatDate; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolEntity.java index 2b7b3a6ded..6c4ba90d96 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/EntitlementPoolEntity.java @@ -26,6 +26,9 @@ import com.datastax.driver.mapping.annotations.Enumerated; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.vendorlicense.VendorLicenseUtil; import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitForXml; import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitXml; import org.openecomp.sdc.vendorlicense.dao.types.xml.OperationalScopeForXml; @@ -40,6 +43,8 @@ import java.util.Set; @Table(keyspace = "dox", name = "entitlement_pool") public class EntitlementPoolEntity implements VersionableEntity { + + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private static final String ENTITY_TYPE = "Entitlement Pool"; @PartitionKey @@ -201,7 +206,7 @@ public class EntitlementPoolEntity implements VersionableEntity { } public void setOperationalScope(MultiChoiceOrOther<OperationalScope> operationalScope) { - if(operationalScope != null) { + if (operationalScope != null) { operationalScope.resolveEnum(OperationalScope.class); } this.operationalScope = operationalScope; @@ -220,7 +225,8 @@ public class EntitlementPoolEntity implements VersionableEntity { } /** - * Gets version for artifact. + * Gets version for artifact. + * * @return version in format suitable for artifact */ public String getVersionForArtifact() { @@ -251,17 +257,18 @@ public class EntitlementPoolEntity implements VersionableEntity { this.limits = limits; } - public LimitForXml getSPLimits(){ - if(limits != null){ + public LimitForXml getSPLimits() { + if (limits != null) { Set<LimitXml> hs = new HashSet<>(); - for(LimitEntity obj : limits){ - if(obj.getType().equals(LimitType.ServiceProvider)){ + for (LimitEntity obj : limits) { + if (obj.getType().equals(LimitType.ServiceProvider)) { LimitXml xmlObj = new LimitXml(); xmlObj.setDescription(obj.getDescription()); xmlObj.setMetric(obj.getMetric()); xmlObj.setValues(obj.getValue()); xmlObj.setUnit(obj.getUnit()); - xmlObj.setAggregationFunction(obj.getAggregationFunction()!=null?obj.getAggregationFunction().name():null); + xmlObj.setAggregationFunction( + obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); xmlObj.setTime(obj.getTime()); hs.add(xmlObj); } @@ -274,17 +281,18 @@ public class EntitlementPoolEntity implements VersionableEntity { return null; } - public LimitForXml getVendorLimits(){ - if(limits != null){ + public LimitForXml getVendorLimits() { + if (limits != null) { Set<LimitXml> hs = new HashSet<>(); - for(LimitEntity obj : limits){ - if(obj.getType().equals(LimitType.Vendor)){ + for (LimitEntity obj : limits) { + if (obj.getType().equals(LimitType.Vendor)) { LimitXml xmlObj = new LimitXml(); xmlObj.setDescription(obj.getDescription()); xmlObj.setMetric(obj.getMetric()); xmlObj.setValues(obj.getValue()); xmlObj.setUnit(obj.getUnit()); - xmlObj.setAggregationFunction(obj.getAggregationFunction()!=null?obj.getAggregationFunction().name():null); + xmlObj.setAggregationFunction( + obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); xmlObj.setTime(obj.getTime()); hs.add(xmlObj); } @@ -324,7 +332,9 @@ public class EntitlementPoolEntity implements VersionableEntity { && Objects.equals(operationalScope, that.operationalScope) && Objects.equals(referencingFeatureGroups, that.referencingFeatureGroups) && Objects.equals(startDate, that.startDate) - && Objects.equals(expiryDate, that.expiryDate); + && Objects.equals(expiryDate, that.expiryDate) + && Objects.equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber) + && Objects.equals(version, that.version); } @Override @@ -354,7 +364,7 @@ public class EntitlementPoolEntity implements VersionableEntity { public OperationalScopeForXml getOperationalScopeForArtifact() { OperationalScopeForXml obj = new OperationalScopeForXml(); if (operationalScope != null) { - if(operationalScope.getResults().size() > 0) { + if (operationalScope.getResults().size() > 0) { obj.setValue(operationalScope.getResults()); } } @@ -369,4 +379,27 @@ public class EntitlementPoolEntity implements VersionableEntity { public String getManufacturerReferenceNumber() { return manufacturerReferenceNumber; } + + public String getIsoFormatStartDate() { + mdcDataDebugMessage.debugEntryMessage("start date", startDate); + String isoFormatStartDate = null; + if (!StringUtils.isEmpty(startDate)) { + isoFormatStartDate = VendorLicenseUtil.getIsoFormatDate(startDate); + mdcDataDebugMessage.debugExitMessage("start date", "iso format start date", startDate, + isoFormatStartDate); + } + return isoFormatStartDate; + } + + + public String getIsoFormatExpiryDate() { + mdcDataDebugMessage.debugEntryMessage("expiry date", expiryDate); + String isoFormatExpDate = null; + if (!StringUtils.isEmpty(expiryDate)) { + isoFormatExpDate = VendorLicenseUtil.getIsoFormatDate(expiryDate); + mdcDataDebugMessage.debugExitMessage("expiry date", "iso format expiry date", expiryDate, + isoFormatExpDate); + } + return isoFormatExpDate; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyGroupEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyGroupEntity.java index 364a240498..7794aaf275 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyGroupEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LicenseKeyGroupEntity.java @@ -26,9 +26,12 @@ import com.datastax.driver.mapping.annotations.Enumerated; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.vendorlicense.VendorLicenseUtil; import org.openecomp.sdc.vendorlicense.dao.types.xml.LicenseKeyTypeForXml; -import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitXml; import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitForXml; +import org.openecomp.sdc.vendorlicense.dao.types.xml.LimitXml; import org.openecomp.sdc.vendorlicense.dao.types.xml.OperationalScopeForXml; import org.openecomp.sdc.vendorlicense.dao.types.xml.ThresholdForXml; import org.openecomp.sdc.versioning.dao.types.Version; @@ -41,6 +44,8 @@ import java.util.Set; @Table(keyspace = "dox", name = "license_key_group") public class LicenseKeyGroupEntity implements VersionableEntity { + + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private static final String ENTITY_TYPE = "License Key Group"; @PartitionKey @@ -164,7 +169,7 @@ public class LicenseKeyGroupEntity implements VersionableEntity { } public void setOperationalScope(MultiChoiceOrOther<OperationalScope> operationalScope) { - if(operationalScope != null) { + if (operationalScope != null) { operationalScope.resolveEnum(OperationalScope.class); } this.operationalScope = operationalScope; @@ -217,17 +222,18 @@ public class LicenseKeyGroupEntity implements VersionableEntity { this.limits = limits; } - public LimitForXml getSPLimits(){ - if(limits != null){ + public LimitForXml getSPLimits() { + if (limits != null) { Set<LimitXml> hs = new HashSet<>(); - for(LimitEntity obj : limits){ - if(obj.getType().equals(LimitType.ServiceProvider)){ + for (LimitEntity obj : limits) { + if (obj.getType().equals(LimitType.ServiceProvider)) { LimitXml xmlObj = new LimitXml(); xmlObj.setDescription(obj.getDescription()); xmlObj.setMetric(obj.getMetric()); xmlObj.setValues(obj.getValue()); xmlObj.setUnit(obj.getUnit()); - xmlObj.setAggregationFunction(obj.getAggregationFunction()!=null?obj.getAggregationFunction().name():null); + xmlObj.setAggregationFunction( + obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); xmlObj.setTime(obj.getTime()); hs.add(xmlObj); } @@ -240,17 +246,18 @@ public class LicenseKeyGroupEntity implements VersionableEntity { return null; } - public LimitForXml getVendorLimits(){ - if(limits != null){ + public LimitForXml getVendorLimits() { + if (limits != null) { Set<LimitXml> hs = new HashSet<>(); - for(LimitEntity obj : limits){ - if(obj.getType().equals(LimitType.Vendor)){ + for (LimitEntity obj : limits) { + if (obj.getType().equals(LimitType.Vendor)) { LimitXml xmlObj = new LimitXml(); xmlObj.setDescription(obj.getDescription()); xmlObj.setMetric(obj.getMetric()); xmlObj.setValues(obj.getValue()); xmlObj.setUnit(obj.getUnit()); - xmlObj.setAggregationFunction(obj.getAggregationFunction()!=null?obj.getAggregationFunction().name():null); + xmlObj.setAggregationFunction( + obj.getAggregationFunction() != null ? obj.getAggregationFunction().name() : null); xmlObj.setTime(obj.getTime()); hs.add(xmlObj); } @@ -297,6 +304,7 @@ public class LicenseKeyGroupEntity implements VersionableEntity { } LicenseKeyGroupEntity that = (LicenseKeyGroupEntity) obj; return Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) + && Objects.equals(version, that.version) && Objects.equals(id, that.id) && Objects.equals(name, that.name) && Objects.equals(description, that.description) @@ -307,7 +315,8 @@ public class LicenseKeyGroupEntity implements VersionableEntity { && Objects.equals(expiryDate, that.expiryDate) && Objects.equals(thresholdValue, that.thresholdValue) && Objects.equals(thresholdUnits, that.thresholdUnits) - && Objects.equals(increments, that.increments); + && Objects.equals(increments, that.increments) + && Objects.equals(manufacturerReferenceNumber, that.manufacturerReferenceNumber); } @Override @@ -337,7 +346,7 @@ public class LicenseKeyGroupEntity implements VersionableEntity { public OperationalScopeForXml getOperationalScopeForArtifact() { OperationalScopeForXml obj = new OperationalScopeForXml(); if (operationalScope != null) { - if(operationalScope.getResults().size() > 0) { + if (operationalScope.getResults().size() > 0) { obj.setValue(operationalScope.getResults()); } } @@ -346,6 +355,7 @@ public class LicenseKeyGroupEntity implements VersionableEntity { /** * Gets version for artifact. + * * @return version in format suitable for artifact */ public String getVersionForArtifact() { @@ -375,4 +385,29 @@ public class LicenseKeyGroupEntity implements VersionableEntity { public void setManufacturerReferenceNumber(String manufacturerReferenceNumber) { this.manufacturerReferenceNumber = manufacturerReferenceNumber; } + + public String getIsoFormatStartDate() { + mdcDataDebugMessage.debugEntryMessage("start date", startDate); + String isoFormatStartDate = null; + if (!StringUtils.isEmpty(startDate)) { + isoFormatStartDate = VendorLicenseUtil.getIsoFormatDate(startDate); + mdcDataDebugMessage.debugExitMessage("start date", "iso format start date", startDate, + isoFormatStartDate); + } + return isoFormatStartDate; + } + + + public String getIsoFormatExpiryDate() { + mdcDataDebugMessage.debugEntryMessage("expiry date", expiryDate); + String isoFormatExpDate = null; + if (!StringUtils.isEmpty(expiryDate)) { + isoFormatExpDate = VendorLicenseUtil.getIsoFormatDate(expiryDate); + mdcDataDebugMessage.debugExitMessage("expiry date", "iso format expiry date", expiryDate, + isoFormatExpDate); + } + return isoFormatExpDate; + } + + } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitEntity.java index 58ccd5e608..0860c243b0 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/LimitEntity.java @@ -47,7 +47,7 @@ public class LimitEntity implements VersionableEntity { } public void setAggregationFunction( - AggregationFunction aggregationFunction) { + AggregationFunction aggregationFunction) { this.aggregationFunction = aggregationFunction; } @@ -159,7 +159,7 @@ public class LimitEntity implements VersionableEntity { @Override public int hashCode() { return Objects.hash(vendorLicenseModelId, version, epLkgId, id, name, description, type, - metric, unit, time, aggregationFunction, value); + metric, unit, time, aggregationFunction, value); } @Override @@ -172,35 +172,35 @@ public class LimitEntity implements VersionableEntity { } LimitEntity that = (LimitEntity) obj; return Objects.equals(that.unit, unit) - && Objects.equals(that.value, value) - && Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) - && Objects.equals(epLkgId, that.epLkgId) - && Objects.equals(id, that.id) - && Objects.equals(name, that.name) - && Objects.equals(description, that.description) - && Objects.equals(type, that.type) - && Objects.equals(metric, that.metric) - && Objects.equals(aggregationFunction, that.aggregationFunction); + && Objects.equals(that.value, value) + && Objects.equals(vendorLicenseModelId, that.vendorLicenseModelId) + && Objects.equals(epLkgId, that.epLkgId) + && Objects.equals(id, that.id) + && Objects.equals(name, that.name) + && Objects.equals(description, that.description) + && Objects.equals(type, that.type) + && Objects.equals(metric, that.metric) + && Objects.equals(aggregationFunction, that.aggregationFunction); } @Override public String toString() { return "LimitEntity{" - + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' - + ", version=" + version - + ", epLkgId=" + epLkgId - + ", id='" + id + '\'' - + ", name='" + name + '\'' - + ", description='" + description + '\'' - + ", type=" + type - + ", metric=" + metric - + ", value='" + value + '\'' - + ", unit='" + unit + '\'' - + ", aggregationFunction=" + aggregationFunction - + ", time=" + time - - + '}'; + + "vendorLicenseModelId='" + vendorLicenseModelId + '\'' + + ", version=" + version + + ", epLkgId=" + epLkgId + + ", id='" + id + '\'' + + ", name='" + name + '\'' + + ", description='" + description + '\'' + + ", type=" + type + + ", metric=" + metric + + ", value='" + value + '\'' + + ", unit='" + unit + '\'' + + ", aggregationFunction=" + aggregationFunction + + ", time=" + time + + + '}'; } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/VendorLicenseModelEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/VendorLicenseModelEntity.java index b57b850f60..05cc78f855 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/VendorLicenseModelEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/dao/types/VendorLicenseModelEntity.java @@ -45,6 +45,7 @@ public class VendorLicenseModelEntity implements VersionableEntity { @Column(name = "vendor_name") private String vendorName; private String description; + private String oldVersion; @Column(name = "icon") private String iconRef; @@ -111,6 +112,15 @@ public class VendorLicenseModelEntity implements VersionableEntity { this.iconRef = iconRef; } + public void setOldVersion(String oldVersion) { + this.oldVersion = oldVersion; + } + + public String getOldVersion() { + return oldVersion; + } + + @Override public int hashCode() { return Objects.hash(id, version, vendorName, description, iconRef); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacade.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacade.java index 3d27de3a88..dda42eeff3 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacade.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/facade/VendorLicenseFacade.java @@ -29,72 +29,52 @@ import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementModel; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; -import org.openecomp.sdc.vendorlicense.types.VersionedVendorLicenseModel; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; import java.util.Collection; public interface VendorLicenseFacade { - Version checkin(String vendorLicenseModelId, String user); - - Version submit(String vendorLicenseModelId, String user); - - FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup, String user); - - FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup, String user); - LicenseAgreementEntity getLicenseAgreement(String vlmId, Version version, - String licenseAgreementId, String user); + String licenseAgreementId); LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId, String user); + String licenseAgreementId); + + LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement); - EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool, String user); + Collection<FeatureGroupEntity> listFeatureGroups(String vlmId, Version version); - void updateEntitlementPool(EntitlementPoolEntity entitlementPool, String user); + FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup); - Collection<LicenseKeyGroupEntity> listLicenseKeyGroups(String vlmId, Version version, - String user); + FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup); - Collection<EntitlementPoolEntity> listEntitlementPools(String vlmId, Version version, - String user); + FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup); - void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user); + Collection<EntitlementPoolEntity> listEntitlementPools(String vlmId, Version version); - LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user); + EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool); + void updateEntitlementPool(EntitlementPoolEntity entitlementPool); - VersionedVendorLicenseModel getVendorLicenseModel(String vlmId, Version version, String user); + Collection<LicenseKeyGroupEntity> listLicenseKeyGroups(String vlmId, Version version); - VendorLicenseModelEntity createVendorLicenseModel( - VendorLicenseModelEntity vendorLicenseModelEntity, String user); + LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); + void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup); - LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement, - String user); + Collection<LimitEntity> listLimits(String vlmId, Version version, String epLkgId); - Collection<FeatureGroupEntity> listFeatureGroups(String vlmId, Version version, - String user); + LimitEntity createLimit(LimitEntity limit); - FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup, String user); + void updateLimit(LimitEntity limit); + + VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version); Collection<ErrorCode> validateLicensingData(String vlmId, Version vlmVersion, String licenseAgreementId, Collection<String> featureGroupIds); - VersionInfo getVersionInfo(String vendorLicenseModelId, VersionableEntityAction action, - String user); - - void updateVlmLastModificationTime(String vendorLicenseModelId, Version version); - - LimitEntity createLimit(LimitEntity limit, String user); - - Collection<LimitEntity> listLimits(String vlmId, Version version, String epLkgId - ,String user); - - void updateLimit(LimitEntity limit, String user); + void validate(String vendorLicenseModelId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/healing/HealingService.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/healing/HealingService.java index 6ae2de1a63..a3a5b7263f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/healing/HealingService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/healing/HealingService.java @@ -24,7 +24,7 @@ import org.openecomp.sdc.versioning.dao.types.VersionableEntity; public interface HealingService { - VersionableEntity heal(VersionableEntity toHeal, String user); + VersionableEntity heal(VersionableEntity toHeal); void persistNoHealing(VersionableEntity alreadyHealed); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/VendorLicenseArtifactsService.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/VendorLicenseArtifactsService.java index c0610a99cd..66ac7ab33f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/VendorLicenseArtifactsService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-api/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/VendorLicenseArtifactsService.java @@ -28,5 +28,5 @@ import java.util.List; public interface VendorLicenseArtifactsService { FileContentHandler createLicenseArtifacts(String vspId, String vlmId, Version vlmVersion, - List<String> featureGroups, String user); + List<String> featureGroups); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupCassandraDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupCassandraDaoImpl.java index 2568d719e2..dd22397760 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupCassandraDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/FeatureGroupCassandraDaoImpl.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.vendorlicense.dao.impl; -import static org.openecomp.core.utilities.CommonMethods.toSingleElementSet; - import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.UDTValue; import com.datastax.driver.mapping.Mapper; @@ -47,6 +45,8 @@ import java.util.Collections; import java.util.HashSet; import java.util.Set; +import static org.openecomp.core.utilities.CommonMethods.toSingleElementSet; + public class FeatureGroupCassandraDaoImpl extends CassandraBaseDao<FeatureGroupEntity> implements FeatureGroupDao { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/EntitlementPoolZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/EntitlementPoolZusammenDaoImpl.java index b880c67cbc..35182a3502 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/EntitlementPoolZusammenDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/EntitlementPoolZusammenDaoImpl.java @@ -10,25 +10,20 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.EntitlementPoolDao; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToEntitlementPoolConvertor; import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; -import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; -import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; -import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; -import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; -/** - * Created by ayalaben on 3/28/2017. - */ +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; + public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { private ZusammenAdaptor zusammenAdaptor; @@ -48,18 +43,22 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { buildEntitlementPoolElement(entitlementPool, Action.CREATE); ZusammenElement entitlementPoolsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.EntitlementPools, null); + ZusammenUtil.buildStructuralElement(ElementType.EntitlementPools, Action.IGNORE); + + ZusammenElement limitsElement = + ZusammenUtil.buildStructuralElement(ElementType.Limits, Action.CREATE); + entitlementPoolElement.addSubElement(limitsElement); entitlementPoolsElement.addSubElement(entitlementPoolElement); SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - Optional<Element> savedElement = zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + Element epsSavedElement = zusammenAdaptor.saveElement(context, + new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()), entitlementPoolsElement, "Create entitlement pool"); - savedElement.ifPresent(element -> entitlementPool - .setId(element.getSubElements().iterator().next().getElementId().getValue())); + entitlementPool + .setId(epsSavedElement.getSubElements().iterator().next().getElementId().getValue()); } @Override @@ -68,9 +67,8 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { buildEntitlementPoolElement(entitlementPool, Action.UPDATE); SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); Optional<ElementInfo> epFromDb = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); @@ -84,35 +82,33 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { } } - zusammenAdaptor.saveElement(context,elementContext, entitlmentpoolElement, + zusammenAdaptor.saveElement(context, elementContext, entitlmentpoolElement, String.format("Update entitlement pool with id %s", entitlementPool.getId())); } @Override public EntitlementPoolEntity get(EntitlementPoolEntity entitlementPool) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(entitlementPool.getVersion())); - + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); + ElementToEntitlementPoolConvertor convertor = new ElementToEntitlementPoolConvertor(); return zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())) - .map(elementInfo -> mapElementInfoToEntitlementPool( - entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(), elementInfo)) + .map(elementInfo -> { + EntitlementPoolEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(entitlementPool.getVendorLicenseModelId()); + entity.setVersion(entitlementPool.getVersion()); + return entity; + }) .orElse(null); } @Override public void delete(EntitlementPoolEntity entitlementPool) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(entitlementPool.getId())); + ZusammenElement zusammenElement = buildElement(new Id(entitlementPool.getId()), Action.DELETE); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = - new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete entitlement pool. id:" + entitlementPool.getId() + "."); } @@ -120,28 +116,27 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { @Override public Collection<EntitlementPoolEntity> list(EntitlementPoolEntity entitlementPool) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(entitlementPool.getVersion())); - + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); + ElementToEntitlementPoolConvertor convertor = new ElementToEntitlementPoolConvertor(); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.EntitlementPools.name()) - .stream().map(elementInfo -> mapElementInfoToEntitlementPool( - entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion(), elementInfo)) - .collect(Collectors.toList()); + .listElementsByName(context, elementContext, null, ElementType.EntitlementPools.name()) + .stream().map(elementInfo -> { + EntitlementPoolEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(entitlementPool.getVendorLicenseModelId()); + entity.setVersion(entitlementPool.getVersion()); + return entity; + }).collect(Collectors.toList()); } @Override public long count(EntitlementPoolEntity entitlementPool) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(entitlementPool.getVersion())); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.EntitlementPools.name()) + .listElementsByName(context, elementContext, null, ElementType.EntitlementPools.name()) .size(); } @@ -149,9 +144,8 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { public void removeReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, String referencingFeatureGroupId) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); @@ -173,9 +167,8 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { public void addReferencingFeatureGroup(EntitlementPoolEntity entitlementPool, String referencingFeatureGroupId) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPool.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ElementContext elementContext = new ElementContext(entitlementPool.getVendorLicenseModelId(), + entitlementPool.getVersion().getId()); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPool.getId())); @@ -199,17 +192,32 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { //not supported } - private ZusammenElement buildEntitlementPoolElement(EntitlementPoolEntity entitlementPool, - Action action) { + @Override + public String getManufacturerReferenceNumber(EntitlementPoolEntity entitlementPoolEntity) { + SessionContext context = ZusammenUtil.createSessionContext(); + ElementContext elementContext = + new ElementContext(entitlementPoolEntity.getVendorLicenseModelId(), + entitlementPoolEntity.getVersion().getId()); - ZusammenElement entitlementPoolElement = new ZusammenElement(); - entitlementPoolElement.setAction(action); - if (entitlementPool.getId() != null) { - entitlementPoolElement.setElementId(new Id(entitlementPool.getId())); + Optional<ElementInfo> elementInfo1 = zusammenAdaptor + .getElementInfo(context, elementContext, new Id(entitlementPoolEntity.getId())); + Map<String, Object> properties = elementInfo1.get().getInfo().getProperties(); + String manufacturerReferenceNumber = null; + if (properties != null && properties.containsKey("manufacturerReferenceNumber")) { + manufacturerReferenceNumber = (String) properties.get("manufacturerReferenceNumber"); } + return manufacturerReferenceNumber; + } + + private ZusammenElement buildEntitlementPoolElement(EntitlementPoolEntity entitlementPool, + Action action) { + ZusammenElement entitlementPoolElement = + buildElement(entitlementPool.getId() == null ? null : new Id(entitlementPool.getId()), + action); Info info = new Info(); info.setName(entitlementPool.getName()); info.setDescription(entitlementPool.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.EntitlementPool); info.addProperty("version_uuid", entitlementPool.getVersionUuId()); info.addProperty("thresholdValue", entitlementPool.getThresholdValue()); info.addProperty("threshold_unit", entitlementPool.getThresholdUnit()); @@ -219,8 +227,8 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { info.addProperty("expiryDate", entitlementPool.getExpiryDate()); entitlementPoolElement.setInfo(info); - if (entitlementPool.getReferencingFeatureGroups() != null - && entitlementPool.getReferencingFeatureGroups().size() > 0) { + if (entitlementPool.getReferencingFeatureGroups() != null + && entitlementPool.getReferencingFeatureGroups().size() > 0) { entitlementPoolElement.setRelations(entitlementPool.getReferencingFeatureGroups().stream() .map(rel -> VlmZusammenUtil .createRelation(RelationType.EntitlmentPoolToReferencingFeatureGroup, rel)) @@ -229,62 +237,5 @@ public class EntitlementPoolZusammenDaoImpl implements EntitlementPoolDao { return entitlementPoolElement; } - private EntitlementPoolEntity mapElementInfoToEntitlementPool(String vlmId, Version version, - ElementInfo elementInfo) { - EntitlementPoolEntity entitlmentPool = - new EntitlementPoolEntity(vlmId, version, elementInfo.getId().getValue()); - entitlmentPool.setName(elementInfo.getInfo().getName()); - entitlmentPool.setDescription(elementInfo.getInfo().getDescription()); - entitlmentPool.setVersionUuId(elementInfo.getInfo().getProperty("version_uuid")); - entitlmentPool - .setThresholdValue(elementInfo.getInfo().getProperty("thresholdValue") != null - ? VlmZusammenUtil.toInteger(elementInfo.getInfo().getProperty("thresholdValue")) : null); - - Object threshold_unit = elementInfo.getInfo().getProperty("threshold_unit"); - entitlmentPool.setThresholdUnit( threshold_unit != null ? - ThresholdUnit.valueOf(elementInfo.getInfo().getProperty("threshold_unit")) : null); - entitlmentPool.setIncrements(elementInfo.getInfo().getProperty("increments")); - entitlmentPool.setOperationalScope(getOperationalScopeMultiChoiceOrOther( - elementInfo.getInfo().getProperty("operational_scope"))); - entitlmentPool.setStartDate(elementInfo.getInfo().getProperty("startDate")); - entitlmentPool.setExpiryDate(elementInfo.getInfo().getProperty("expiryDate")); - - if (elementInfo.getRelations() != null && elementInfo.getRelations().size() > 0) { - entitlmentPool - .setReferencingFeatureGroups(elementInfo.getRelations().stream().map(relation -> relation - .getEdge2().getElementId().getValue()).collect(Collectors.toSet())); - } - return entitlmentPool; - } - - private MultiChoiceOrOther<OperationalScope> getOperationalScopeMultiChoiceOrOther - (Map<String, Object> - operationalScope) { - if(operationalScope != null && !operationalScope.isEmpty()) { - Set<OperationalScope> choices = new HashSet<>(); - ((List<String>) operationalScope.get("choices")). - forEach(choice -> choices.add(OperationalScope.valueOf(choice))); - - return new MultiChoiceOrOther<>(choices, operationalScope.get("other")==null?null: - (String) operationalScope.get("other")); - } - return null; - } - - @Override - public String getManufacturerReferenceNumber(EntitlementPoolEntity entitlementPoolEntity){ - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entitlementPoolEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(entitlementPoolEntity.getVersion())); - Optional<ElementInfo> elementInfo1 = zusammenAdaptor.getElementInfo(context, elementContext, new Id(entitlementPoolEntity.getId())); - Map<String, Object> properties = elementInfo1.get().getInfo().getProperties(); - String manufacturerReferenceNumber = null; - if(properties != null && properties.containsKey("manufacturerReferenceNumber") ) { - manufacturerReferenceNumber = (String)properties.get("manufacturerReferenceNumber"); - } - return manufacturerReferenceNumber; - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java index aa9e6c7ae0..8dcc964e7d 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/FeatureGroupDaoZusammenImpl.java @@ -10,21 +10,22 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Relation; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToFeatureGroupConvertor; import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; -import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; -/** - * Created by ayalaben on 3/27/2017. - */ +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { private ZusammenAdaptor zusammenAdaptor; @@ -40,88 +41,86 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { @Override public void create(FeatureGroupEntity featureGroup) { - ZusammenElement featureGroupElement = - buildFeatureGroupElement(featureGroup, Action.CREATE); + ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.CREATE); ZusammenElement featureGroupsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.FeatureGroups, null); + buildStructuralElement(ElementType.FeatureGroups, Action.IGNORE); featureGroupsElement.addSubElement(featureGroupElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - Optional<Element> savedElement = zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - featureGroupsElement, "Create feature group"); + SessionContext context = createSessionContext(); + Element featureGroupsSavedElement = zusammenAdaptor.saveElement(context, + new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()), featureGroupsElement, "Create feature group"); - savedElement.ifPresent(element -> featureGroup - .setId(element.getSubElements().iterator().next().getElementId().getValue())); + featureGroup.setId( + featureGroupsSavedElement.getSubElements().iterator().next().getElementId().getValue()); } @Override public void update(FeatureGroupEntity featureGroup) { ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), featureGroupElement, + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()), featureGroupElement, String.format("Update feature group with id %s", featureGroup.getId())); } @Override public FeatureGroupEntity get(FeatureGroupEntity featureGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(featureGroup.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); return zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())) - .map(elementInfo -> mapElementInfoToFeatureGroup( - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), elementInfo)) + .map(elementInfo -> { + FeatureGroupEntity entity = new ElementToFeatureGroupConvertor().convert(elementInfo); + entity.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); + entity.setVersion(featureGroup.getVersion()); + return entity; + }) .orElse(null); } @Override public void delete(FeatureGroupEntity featureGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(featureGroup.getId())); - - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ZusammenElement zusammenElement = buildElement(new Id(featureGroup.getId()), Action.DELETE); + + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete feature group. id:" + featureGroup.getId() + "."); } @Override public Collection<FeatureGroupEntity> list(FeatureGroupEntity featureGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(featureGroup.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); + ElementToFeatureGroupConvertor convertor = new ElementToFeatureGroupConvertor(); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.FeatureGroups.name()) - .stream().map(elementInfo -> mapElementInfoToFeatureGroup( - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), elementInfo)) + .listElementsByName(context, elementContext, null, ElementType.FeatureGroups.name()) + .stream().map(elementInfo -> { + FeatureGroupEntity entity = convertor.convert( + elementInfo); + entity.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); + entity.setVersion(featureGroup.getVersion()); + return entity; + }) .collect(Collectors.toList()); } @Override public long count(FeatureGroupEntity featureGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(featureGroup.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.FeatureGroups.name()) + .listElementsByName(context, elementContext, null, ElementType.FeatureGroups.name()) .size(); } @@ -138,10 +137,9 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { private void removeRelationToContainedEntity(FeatureGroupEntity featureGroup, String containedEntityId, String containedEntityType) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); @@ -158,25 +156,23 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { } @Override - public void updateFeatureGroup(FeatureGroupEntity - featureGroup, Set<String> addedEntitlementPools, + public void updateFeatureGroup(FeatureGroupEntity featureGroup, + Set<String> addedEntitlementPools, Set<String> removedEntitlementPools, Set<String> addedLicenseKeyGroups, Set<String> removedLicenseKeyGroups) { ZusammenElement featureGroupElement = buildFeatureGroupElement(featureGroup, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); + ElementToFeatureGroupConvertor convertor = new ElementToFeatureGroupConvertor(); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); if (elementInfo.isPresent()) { - FeatureGroupEntity currentFeatureGroup = - mapElementInfoToFeatureGroup(featureGroup.getId(), featureGroup.getVersion(), - elementInfo.get()); - - if (!(removedEntitlementPools == null )) { + FeatureGroupEntity currentFeatureGroup = convertor.convert(elementInfo.get()); + currentFeatureGroup.setVendorLicenseModelId(featureGroup.getVendorLicenseModelId()); + currentFeatureGroup.setVersion(featureGroup.getVersion()); + if (!(removedEntitlementPools == null)) { currentFeatureGroup.getEntitlementPoolIds().removeAll(removedEntitlementPools); } if (!(addedEntitlementPools == null)) { @@ -192,22 +188,24 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { .createRelation(RelationType.FeatureGroupToEntitlmentPool, relation)) .collect(Collectors.toList())); - if (! ( removedLicenseKeyGroups == null)) { + if (!(removedLicenseKeyGroups == null)) { currentFeatureGroup.getLicenseKeyGroupIds().removeAll(removedLicenseKeyGroups); } - if (! ( addedLicenseKeyGroups == null)) { + if (!(addedLicenseKeyGroups == null)) { currentFeatureGroup.getLicenseKeyGroupIds().addAll(addedLicenseKeyGroups); } + featureGroupElement.getRelations() .addAll(currentFeatureGroup.getLicenseKeyGroupIds().stream() .map(relation -> VlmZusammenUtil .createRelation(RelationType.FeatureGroupToLicenseKeyGroup, relation)) .collect(Collectors.toList())); - Collection<Relation> LaRelations = elementInfo.get().getRelations().stream().filter - (rel->rel.getType().equals(RelationType.FeatureGroupToReferencingLicenseAgreement.name())) - .map(rel ->VlmZusammenUtil.createRelation(RelationType - .FeatureGroupToReferencingLicenseAgreement,rel.getEdge2().getElementId().toString())) + Collection<Relation> LaRelations = elementInfo.get().getRelations().stream().filter + (rel -> rel.getType() + .equals(RelationType.FeatureGroupToReferencingLicenseAgreement.name())) + .map(rel -> VlmZusammenUtil.createRelation(RelationType + .FeatureGroupToReferencingLicenseAgreement, rel.getEdge2().getElementId().toString())) .collect(Collectors.toList()); featureGroupElement.getRelations().addAll(LaRelations); @@ -226,10 +224,9 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { @Override public void addReferencingLicenseAgreement(FeatureGroupEntity featureGroup, String licenseAgreementId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); @@ -247,10 +244,9 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { @Override public void removeReferencingLicenseAgreement(FeatureGroupEntity featureGroup, String licenseAgreementId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(featureGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion().getId()); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(featureGroup.getId())); @@ -268,15 +264,12 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { } private ZusammenElement buildFeatureGroupElement(FeatureGroupEntity featureGroup, Action action) { - - ZusammenElement featureGroupElement = new ZusammenElement(); - featureGroupElement.setAction(action); - if (featureGroup.getId() != null) { - featureGroupElement.setElementId(new Id(featureGroup.getId())); - } + ZusammenElement featureGroupElement = + buildElement(featureGroup.getId() == null ? null : new Id(featureGroup.getId()), action); Info info = new Info(); info.setName(featureGroup.getName()); info.setDescription(featureGroup.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.FeatureGroup); info.addProperty("partNumber", featureGroup.getPartNumber()); info.addProperty("manufacturerReferenceNumber", featureGroup.getManufacturerReferenceNumber()); featureGroupElement.setInfo(info); @@ -310,39 +303,5 @@ public class FeatureGroupDaoZusammenImpl implements FeatureGroupDao { .collect(Collectors.toList())); } return featureGroupElement; - - } - - private FeatureGroupEntity mapElementInfoToFeatureGroup(String vlmId, Version version, - ElementInfo elementInfo) { - FeatureGroupEntity featureGroup = - new FeatureGroupEntity(vlmId, version, elementInfo.getId().getValue()); - featureGroup.setName(elementInfo.getInfo().getName()); - featureGroup.setDescription(elementInfo.getInfo().getDescription()); - featureGroup.setPartNumber(elementInfo.getInfo().getProperty("partNumber")); - featureGroup.setManufacturerReferenceNumber(elementInfo.getInfo() - .getProperty("manufacturerReferenceNumber")); - - Set<String> entitlementPoolIds = new HashSet<>(); - Set<String> licenseAgreements = new HashSet<>(); - Set<String> licenseKeyGroupIds = new HashSet<>(); - - if (elementInfo.getRelations() != null) { - for (Relation relation : elementInfo.getRelations()) { - if (RelationType.FeatureGroupToEntitlmentPool.name().equals(relation.getType())) { - entitlementPoolIds.add(relation.getEdge2().getElementId().getValue()); - } else if (RelationType.FeatureGroupToLicenseKeyGroup.name().equals(relation.getType())) { - licenseKeyGroupIds.add(relation.getEdge2().getElementId().getValue()); - } else if (RelationType.FeatureGroupToReferencingLicenseAgreement.name() - .equals(relation.getType())) { - licenseAgreements.add(relation.getEdge2().getElementId().getValue()); - } - } - } - featureGroup.setEntitlementPoolIds(entitlementPoolIds); - featureGroup.setLicenseKeyGroupIds(licenseKeyGroupIds); - featureGroup.setReferencingLicenseAgreements(licenseAgreements); - - return featureGroup; } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java index 45c831fbd7..0fbac66b58 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseAgreementDaoZusammenImpl.java @@ -29,19 +29,21 @@ import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.LicenseAgreementDao; -import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLicenseAgreementConvertor; import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; -import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.util.Collection; -import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { @@ -61,16 +63,17 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { ZusammenElement licenseAgreementElement = buildLicenseAgreementElement(licenseAgreement, Action.CREATE); ZusammenElement licenseAgreementsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.LicenseAgreements, null); + buildStructuralElement(ElementType.LicenseAgreements, Action.IGNORE); licenseAgreementsElement.addSubElement(licenseAgreementElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - Optional<Element> savedElement = zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - licenseAgreementsElement, "Create license agreement"); - savedElement.ifPresent(element -> licenseAgreement - .setId(element.getSubElements().iterator().next().getElementId().getValue())); + SessionContext context = createSessionContext(); + Element licenseAgreementsSavedElement = zusammenAdaptor.saveElement(context, + new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()), licenseAgreementsElement, + "Create license agreement"); + licenseAgreement + .setId(licenseAgreementsSavedElement.getSubElements().iterator().next().getElementId() + .getValue()); } @Override @@ -78,38 +81,36 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { ZusammenElement licenseAgreementElement = buildLicenseAgreementElement(licenseAgreement, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - licenseAgreementElement, + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, + new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()), licenseAgreementElement, String.format("Update license agreement with id %s", licenseAgreement.getId())); } @Override public LicenseAgreementEntity get(LicenseAgreementEntity licenseAgreement) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseAgreement.getVersion())); - + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); + ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); return zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseAgreement.getId())) - .map(elementInfo -> mapElementInfoToLicenseAgreement( - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion(), elementInfo)) + .map(elementInfo -> { + LicenseAgreementEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); + entity.setVersion(licenseAgreement.getVersion()); + return entity; + }) .orElse(null); } @Override public void delete(LicenseAgreementEntity licenseAgreement) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(licenseAgreement.getId())); - - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ZusammenElement zusammenElement = buildElement(new Id(licenseAgreement.getId()), Action.DELETE); + + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete license agreement. id:" + licenseAgreement.getId() + "."); } @@ -117,30 +118,30 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { @Override public Collection<LicenseAgreementEntity> list(LicenseAgreementEntity licenseAgreement) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseAgreement.getVersion())); - + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); + ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); return zusammenAdaptor .listElementsByName(context, elementContext, null, - StructureElement.LicenseAgreements.name()) - .stream().map(elementInfo -> mapElementInfoToLicenseAgreement( - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion(), elementInfo)) + ElementType.LicenseAgreements.name()) + .stream().map(elementInfo -> { + LicenseAgreementEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); + entity.setVersion(licenseAgreement.getVersion()); + return entity; + }) .collect(Collectors.toList()); } @Override public long count(LicenseAgreementEntity licenseAgreement) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseAgreement.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); return zusammenAdaptor.listElementsByName(context, elementContext, null, - StructureElement.LicenseAgreements.name()) + ElementType.LicenseAgreements.name()) .size(); } @@ -151,10 +152,9 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { @Override public void removeFeatureGroup(LicenseAgreementEntity licenseAgreement, String featureGroupId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseAgreement.getId())); @@ -175,23 +175,22 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { ZusammenElement licenseAgreementElement = buildLicenseAgreementElement(licenseAgreement, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseAgreement.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion().getId()); + ElementToLicenseAgreementConvertor convertor = new ElementToLicenseAgreementConvertor(); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseAgreement.getId())); if (elementInfo.isPresent()) { LicenseAgreementEntity currentLicenseAgreement = - mapElementInfoToLicenseAgreement(licenseAgreement.getId(), licenseAgreement.getVersion(), - elementInfo.get()); - - if (! (removedFeatureGroupIds == null) ) { + convertor.convert(elementInfo.get()); + currentLicenseAgreement.setVendorLicenseModelId(licenseAgreement.getVendorLicenseModelId()); + currentLicenseAgreement.setVersion(licenseAgreement.getVersion()); + if (!(removedFeatureGroupIds == null)) { currentLicenseAgreement.getFeatureGroupIds().removeAll(removedFeatureGroupIds); } - if (! (addedFeatureGroupIds == null)) { + if (!(addedFeatureGroupIds == null)) { currentLicenseAgreement.getFeatureGroupIds().addAll(addedFeatureGroupIds); } licenseAgreementElement.setRelations(currentLicenseAgreement.getFeatureGroupIds().stream() @@ -203,41 +202,15 @@ public class LicenseAgreementDaoZusammenImpl implements LicenseAgreementDao { } } - private LicenseAgreementEntity mapElementInfoToLicenseAgreement(String vlmId, Version version, - ElementInfo elementInfo) { - LicenseAgreementEntity licenseAgreement = - new LicenseAgreementEntity(vlmId, version, elementInfo.getId().getValue()); - licenseAgreement.setName(elementInfo.getInfo().getName()); - licenseAgreement.setDescription(elementInfo.getInfo().getDescription()); - - licenseAgreement - .setLicenseTerm(getCoiceOrOther(elementInfo.getInfo().getProperty("licenseTerm"))); - licenseAgreement.setRequirementsAndConstrains( - elementInfo.getInfo().getProperty("requirementsAndConstrains")); - if (elementInfo.getRelations() != null && elementInfo.getRelations().size() > 0) { - licenseAgreement.setFeatureGroupIds(elementInfo.getRelations().stream() - .map(relation -> relation.getEdge2().getElementId().getValue()) - .collect(Collectors.toSet())); - } - return licenseAgreement; - } - - private ChoiceOrOther<LicenseTerm> getCoiceOrOther(Map licenseTerm) { - return new ChoiceOrOther(LicenseTerm.valueOf((String) licenseTerm.get("choice")), - (String) licenseTerm.get("other")); - } - - private ZusammenElement buildLicenseAgreementElement(LicenseAgreementEntity licenseAgreement, Action action) { - ZusammenElement licenseAgreementElement = new ZusammenElement(); - licenseAgreementElement.setAction(action); - if (licenseAgreement.getId() != null) { - licenseAgreementElement.setElementId(new Id(licenseAgreement.getId())); - } + ZusammenElement licenseAgreementElement = + buildElement(licenseAgreement.getId() == null ? null : new Id(licenseAgreement.getId()), + action); Info info = new Info(); info.setName(licenseAgreement.getName()); info.setDescription(licenseAgreement.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.LicenseAgreement); info.addProperty("licenseTerm", licenseAgreement.getLicenseTerm()); info.addProperty("requirementsAndConstrains", licenseAgreement.getRequirementsAndConstrains()); licenseAgreementElement.setInfo(info); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseKeyGroupZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseKeyGroupZusammenDaoImpl.java index 976db94f39..4e7aee377a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseKeyGroupZusammenDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LicenseKeyGroupZusammenDaoImpl.java @@ -9,27 +9,22 @@ import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.LicenseKeyGroupDao; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToLicenseKeyGroupConvertor; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; -import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyType; -import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; -import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; -import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; -import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.util.ArrayList; import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; import java.util.Optional; -import java.util.Set; import java.util.stream.Collectors; -/** - * Created by ayalaben on 3/30/2017. - */ +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + + public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { private ZusammenAdaptor zusammenAdaptor; @@ -47,18 +42,20 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { ZusammenElement licenseKeyGroupElement = buildLicenseKeyGroupElement(licenseKeyGroup, Action.CREATE); + ZusammenElement limitsElement = buildStructuralElement(ElementType.Limits, Action.CREATE); + licenseKeyGroupElement.addSubElement(limitsElement); + ZusammenElement lkgsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.LicenseKeyGroups, null); + buildStructuralElement(ElementType.LicenseKeyGroups, Action.IGNORE); lkgsElement.addSubElement(licenseKeyGroupElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - Optional<Element> savedElement = zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - lkgsElement, "Create license Key Group"); + SessionContext context = createSessionContext(); + Element lkgsSavedElement = zusammenAdaptor.saveElement(context, + new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()), lkgsElement, "Create license Key Group"); - savedElement.ifPresent(element -> licenseKeyGroup - .setId(element.getSubElements().iterator().next().getElementId().getValue())); + licenseKeyGroup + .setId(lkgsSavedElement.getSubElements().iterator().next().getElementId().getValue()); } @Override @@ -66,55 +63,50 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { ZusammenElement licenseKeyGroupElement = buildLicenseKeyGroupElement(licenseKeyGroup, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); Optional<ElementInfo> lkgFromDb = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); - if(lkgFromDb.isPresent()) { + if (lkgFromDb.isPresent()) { - if( licenseKeyGroupElement.getRelations() == null) { - licenseKeyGroupElement.setRelations(new ArrayList<>()); + if (licenseKeyGroupElement.getRelations() == null) { + licenseKeyGroupElement.setRelations(new ArrayList<>()); } if (lkgFromDb.get().getRelations() != null && lkgFromDb.get().getRelations().size() > 0) { licenseKeyGroupElement.getRelations().addAll(lkgFromDb.get().getRelations()); } } - - zusammenAdaptor.saveElement(context, elementContext, - licenseKeyGroupElement, + zusammenAdaptor.saveElement(context, elementContext, licenseKeyGroupElement, String.format("Update license key group with id %s", licenseKeyGroup.getId())); } @Override public LicenseKeyGroupEntity get(LicenseKeyGroupEntity licenseKeyGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseKeyGroup.getVersion())); - + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); + ElementToLicenseKeyGroupConvertor convertor = new ElementToLicenseKeyGroupConvertor(); return zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())) - .map(elementInfo -> mapElementInfoToLicenseKeyGroup( - licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(), elementInfo)) + .map(elementInfo -> { + LicenseKeyGroupEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(licenseKeyGroup.getVendorLicenseModelId()); + entity.setVersion(licenseKeyGroup.getVersion()); + return entity; + }) .orElse(null); } @Override public void delete(LicenseKeyGroupEntity licenseKeyGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(licenseKeyGroup.getId())); + ZusammenElement zusammenElement = buildElement(new Id(licenseKeyGroup.getId()), Action.DELETE); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, zusammenElement, "delete license key group. id:" + licenseKeyGroup.getId() + "."); @@ -122,29 +114,29 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { @Override public Collection<LicenseKeyGroupEntity> list(LicenseKeyGroupEntity licenseKeyGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseKeyGroup.getVersion())); - + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); + ElementToLicenseKeyGroupConvertor convertor = new ElementToLicenseKeyGroupConvertor(); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.LicenseKeyGroups.name()) - .stream().map(elementInfo -> mapElementInfoToLicenseKeyGroup( - licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion(), elementInfo)) + .listElementsByName(context, elementContext, null, ElementType.LicenseKeyGroups.name()) + .stream().map(elementInfo -> { + LicenseKeyGroupEntity entity = convertor.convert(elementInfo); + entity.setVendorLicenseModelId(licenseKeyGroup.getVendorLicenseModelId()); + entity.setVersion(licenseKeyGroup.getVersion()); + return entity; + }) .collect(Collectors.toList()); } @Override public long count(LicenseKeyGroupEntity licenseKeyGroup) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(licenseKeyGroup.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.LicenseKeyGroups.name()) + .listElementsByName(context, elementContext, null, ElementType.LicenseKeyGroups.name()) .size(); } @@ -156,10 +148,9 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { @Override public void removeReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); @@ -180,10 +171,9 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { @Override public void addReferencingFeatureGroup(LicenseKeyGroupEntity licenseKeyGroup, String featureGroupId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(licenseKeyGroup.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(licenseKeyGroup.getVendorLicenseModelId(), + licenseKeyGroup.getVersion().getId()); Optional<ElementInfo> elementInfo = zusammenAdaptor.getElementInfo(context, elementContext, new Id(licenseKeyGroup.getId())); @@ -204,18 +194,15 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { private ZusammenElement buildLicenseKeyGroupElement(LicenseKeyGroupEntity licenseKeyGroup, Action action) { - - ZusammenElement lkgElement = new ZusammenElement(); - lkgElement.setAction(action); - if (licenseKeyGroup.getId() != null) { - lkgElement.setElementId(new Id(licenseKeyGroup.getId())); - } + ZusammenElement lkgElement = + buildElement(licenseKeyGroup.getId() == null ? null : new Id(licenseKeyGroup.getId()), + action); Info info = new Info(); info.setName(licenseKeyGroup.getName()); info.setDescription(licenseKeyGroup.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.LicenseKeyGroup); info.addProperty("version_uuid", licenseKeyGroup.getVersionUuId()); info.addProperty("LicenseKeyType", licenseKeyGroup.getType()); - info.addProperty("version_uuid", licenseKeyGroup.getVersionUuId()); info.addProperty("operational_scope", licenseKeyGroup.getOperationalScope()); info.addProperty("startDate", licenseKeyGroup.getStartDate()); info.addProperty("expiryDate", licenseKeyGroup.getExpiryDate()); @@ -224,70 +211,15 @@ public class LicenseKeyGroupZusammenDaoImpl implements LicenseKeyGroupDao { info.addProperty("increments", licenseKeyGroup.getIncrements()); lkgElement.setInfo(info); - if (licenseKeyGroup.getReferencingFeatureGroups() != null - && licenseKeyGroup.getReferencingFeatureGroups().size() > 0) { + if (licenseKeyGroup.getReferencingFeatureGroups() != null + && licenseKeyGroup.getReferencingFeatureGroups().size() > 0) { lkgElement.setRelations(licenseKeyGroup.getReferencingFeatureGroups().stream() .map(rel -> VlmZusammenUtil .createRelation(RelationType.LicenseKeyGroupToReferencingFeatureGroup, rel)) .collect(Collectors.toList())); } - return lkgElement; } - private LicenseKeyGroupEntity mapElementInfoToLicenseKeyGroup(String vlmId, Version version, - ElementInfo elementInfo) { - LicenseKeyGroupEntity licenseKeyGroup = - new LicenseKeyGroupEntity(vlmId, version, elementInfo.getId().getValue()); - licenseKeyGroup.setName(elementInfo.getInfo().getName()); - licenseKeyGroup.setDescription(elementInfo.getInfo().getDescription()); - licenseKeyGroup.setVersionUuId(elementInfo.getInfo().getProperty("version_uuid")); - licenseKeyGroup - .setType(LicenseKeyType.valueOf(elementInfo.getInfo().getProperty("LicenseKeyType"))); - licenseKeyGroup.setVersionUuId(elementInfo.getInfo().getProperty("version_uuid")); - licenseKeyGroup.setOperationalScope(getOperationalScopeMultiChoiceOrOther( - elementInfo.getInfo().getProperty("operational_scope"))); - licenseKeyGroup.setStartDate(elementInfo.getInfo().getProperty("startDate")); - licenseKeyGroup.setExpiryDate(elementInfo.getInfo().getProperty("expiryDate")); - if (elementInfo.getInfo().getProperty("thresholdUnits") != null ){ - licenseKeyGroup.setThresholdUnits(ThresholdUnit.valueOf(elementInfo - .getInfo().getProperty("thresholdUnits"))); - } - if (elementInfo.getInfo().getProperty("thresholdValue") != null ){ - licenseKeyGroup.setThresholdValue(toInteger(elementInfo.getInfo().getProperty - ("thresholdValue"))); - } - licenseKeyGroup.setIncrements(elementInfo.getInfo().getProperty("increments")); - - if (elementInfo.getRelations() != null && elementInfo.getRelations().size() > 0) { - licenseKeyGroup - .setReferencingFeatureGroups(elementInfo.getRelations().stream().map(relation -> relation - .getEdge2().getElementId().getValue()).collect(Collectors.toSet())); - } - return licenseKeyGroup; - } - private MultiChoiceOrOther<OperationalScope> getOperationalScopeMultiChoiceOrOther - (Map<String, Object> - operationalScope) { - if(operationalScope != null && !operationalScope.isEmpty()) { - Set<OperationalScope> choices = new HashSet<>(); - ((List<String>) operationalScope.get("choices")) - .forEach(choice -> choices.add(OperationalScope.valueOf(choice))); - - return new MultiChoiceOrOther<>(choices, operationalScope.get("other")==null?null:(String) operationalScope.get("other")); - } - return null; - } - - private Integer toInteger(Object val) { - if (val instanceof Double) { - return ((Double) val).intValue(); - } else if (val instanceof String) { - return new Integer((String) val); - } else if (val instanceof Integer) { - return (Integer) val; - } - throw new RuntimeException("invalid value for integer:" + val.getClass()); - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LimitZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LimitZusammenDaoImpl.java index 78c26c83d3..7b19236409 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LimitZusammenDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/LimitZusammenDaoImpl.java @@ -9,26 +9,30 @@ import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.LimitDao; import org.openecomp.sdc.vendorlicense.dao.types.AggregationFunction; import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; import org.openecomp.sdc.vendorlicense.dao.types.LimitType; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.util.Collection; import java.util.Collections; -import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class LimitZusammenDaoImpl implements LimitDao { - public static final String LIMT_TYPE = "type"; - public static final String METRIC = "metric"; - public static final String AGGREGATIONFUNCTION = "aggregationfunction"; - public static final String TIME = "time"; - public static final String UNIT = "unit"; - public static final String VALUE = "value"; + private static final String LIMT_TYPE = "type"; + private static final String METRIC = "metric"; + private static final String AGGREGATIONFUNCTION = "aggregationfunction"; + private static final String TIME = "time"; + private static final String UNIT = "unit"; + private static final String VALUE = "value"; private ZusammenAdaptor zusammenAdaptor; public LimitZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { @@ -39,36 +43,30 @@ public class LimitZusammenDaoImpl implements LimitDao { public void create(LimitEntity limitEntity) { ZusammenElement limitElement = limitToZusammen(limitEntity, Action.CREATE); - ZusammenElement limitsElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.Limits, null); + ZusammenElement limitsElement = buildStructuralElement(ElementType.Limits, null); limitsElement.setSubElements(Collections.singletonList(limitElement)); - ZusammenElement epLkgElement = - buildZusammenElement(new Id(limitEntity.getEpLkgId()), Action.IGNORE); + ZusammenElement epLkgElement = buildElement(new Id(limitEntity.getEpLkgId()), Action.IGNORE); epLkgElement.setSubElements(Collections.singletonList(limitsElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(limitEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); - Optional<Element> savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, epLkgElement, "Create limit"); - savedElement.ifPresent(element -> - limitEntity.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + limitEntity.setId(savedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public boolean isLimitPresent(LimitEntity limitEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(limitEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(limitEntity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); Collection<ElementInfo> elementInfos = zusammenAdaptor.listElementsByName(context, - elementContext, new Id(limitEntity.getEpLkgId()),StructureElement.Limits.name()); + elementContext, new Id(limitEntity.getEpLkgId()), ElementType.Limits.name()); for (ElementInfo elementInfo : elementInfos) { if (elementInfo.getId().getValue().equals(limitEntity.getId())) { @@ -81,20 +79,18 @@ public class LimitZusammenDaoImpl implements LimitDao { @Override public Collection<LimitEntity> list(LimitEntity limitEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(limitEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(limitEntity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); return listLimits(context, elementContext, limitEntity); } private Collection<LimitEntity> listLimits(SessionContext context, ElementContext elementContext, - LimitEntity limitEntity) { + LimitEntity limitEntity) { return zusammenAdaptor .listElementsByName(context, elementContext, new Id(limitEntity.getEpLkgId()), - StructureElement.Limits.name()) + ElementType.Limits.name()) .stream().map(elementInfo -> mapElementInfoToLimit( limitEntity.getVendorLicenseModelId(), limitEntity.getVersion(), limitEntity.getEpLkgId(), elementInfo)) @@ -102,18 +98,18 @@ public class LimitZusammenDaoImpl implements LimitDao { } private LimitEntity mapElementInfoToLimit(String vlmId, Version version, - String epLkgId, ElementInfo elementInfo) { + String epLkgId, ElementInfo elementInfo) { LimitEntity limitEntity = new LimitEntity(vlmId, version, epLkgId, elementInfo.getId().getValue()); limitEntity.setName(elementInfo.getInfo().getName()); limitEntity.setDescription(elementInfo.getInfo().getDescription()); - limitEntity.setType( elementInfo.getInfo().getProperties().get(LIMT_TYPE) != null ? + limitEntity.setType(elementInfo.getInfo().getProperties().get(LIMT_TYPE) != null ? LimitType.valueOf((String) elementInfo.getInfo().getProperties().get(LIMT_TYPE)) : null); - limitEntity.setTime((String) elementInfo.getInfo().getProperties().get(TIME) ); - limitEntity.setMetric( (String) elementInfo.getInfo().getProperties().get(METRIC)); - limitEntity.setAggregationFunction( elementInfo.getInfo().getProperties().get + limitEntity.setTime((String) elementInfo.getInfo().getProperties().get(TIME)); + limitEntity.setMetric((String) elementInfo.getInfo().getProperties().get(METRIC)); + limitEntity.setAggregationFunction(elementInfo.getInfo().getProperties().get (AGGREGATIONFUNCTION) != null ? AggregationFunction.valueOf((String) elementInfo.getInfo().getProperties() .get(AGGREGATIONFUNCTION)) : null); @@ -126,25 +122,22 @@ public class LimitZusammenDaoImpl implements LimitDao { } @Override - public void update(LimitEntity entity) { - ZusammenElement limitElement = limitToZusammen(entity, Action.UPDATE); + public void update(LimitEntity limitEntity) { + ZusammenElement limitElement = limitToZusammen(limitEntity, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); - zusammenAdaptor.saveElement(context,elementContext, limitElement, - String.format("Update limit with id %s", entity.getId())); + zusammenAdaptor.saveElement(context, elementContext, limitElement, + String.format("Update limit with id %s", limitEntity.getId())); } @Override public LimitEntity get(LimitEntity limitEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(limitEntity.getVendorLicenseModelId()); - ElementContext elementContext = new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VlmZusammenUtil.getVersionTag(limitEntity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); return zusammenAdaptor.getElementInfo(context, elementContext, new Id(limitEntity.getId())) .map(elementInfo -> mapElementInfoToLimit( @@ -154,18 +147,14 @@ public class LimitZusammenDaoImpl implements LimitDao { } @Override - public void delete(LimitEntity entity) { - SessionContext context = ZusammenUtil.createSessionContext(); - ZusammenElement zusammenElement = new ZusammenElement(); - zusammenElement.setAction(Action.DELETE); - zusammenElement.setElementId(new Id(entity.getId())); + public void delete(LimitEntity limitEntity) { + ZusammenElement zusammenElement = buildElement(new Id(limitEntity.getId()), Action.DELETE); - Id itemId = new Id(entity.getVendorLicenseModelId()); + SessionContext context = createSessionContext(); ElementContext elementContext = - new ElementContext(itemId, - VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + new ElementContext(limitEntity.getVendorLicenseModelId(), limitEntity.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, zusammenElement, - "delete limit Id:" + entity.getId() + "."); + "delete limit Id:" + limitEntity.getId() + "."); } @Override @@ -173,23 +162,13 @@ public class LimitZusammenDaoImpl implements LimitDao { } - private ZusammenElement limitToZusammen(LimitEntity limit, - Action action) { - ZusammenElement limitElement = buildLimitElement(limit, action); - return limitElement; - } - - private ZusammenElement buildLimitElement(LimitEntity limit, - Action action) { - ZusammenElement limitElement = new ZusammenElement(); - limitElement.setAction(action); - if (limit.getId() != null) { - limitElement.setElementId(new Id(limit.getId())); - } - + private ZusammenElement limitToZusammen(LimitEntity limit, Action action) { + ZusammenElement limitElement = + buildElement(limit.getId() == null ? null : new Id(limit.getId()), action); Info info = new Info(); info.setName(limit.getName()); info.setDescription(limit.getDescription()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Limit); info.addProperty(LIMT_TYPE, limit.getType()); info.addProperty(METRIC, limit.getMetric()); info.addProperty(AGGREGATIONFUNCTION, limit.getAggregationFunction()); @@ -199,11 +178,4 @@ public class LimitZusammenDaoImpl implements LimitDao { limitElement.setInfo(info); return limitElement; } - - private ZusammenElement buildZusammenElement(Id elementId, Action action) { - ZusammenElement element = new ZusammenElement(); - element.setElementId(elementId); - element.setAction(action); - return element; - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VendorLicenseModelDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VendorLicenseModelDaoZusammenImpl.java index cd1ef0fbcf..13065515d8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VendorLicenseModelDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VendorLicenseModelDaoZusammenImpl.java @@ -1,23 +1,21 @@ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; -import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersion; import org.openecomp.core.zusammen.api.ZusammenAdaptor; import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorlicense.dao.VendorLicenseModelDao; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor.ElementToVLMGeneralConvertor; import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.versioning.VersioningManagerFactory; -import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; import org.openecomp.sdc.versioning.types.VersionableEntityStoreType; import java.util.Collection; -import java.util.Date; import java.util.stream.Collectors; public class VendorLicenseModelDaoZusammenImpl implements VendorLicenseModelDao { @@ -31,63 +29,91 @@ public class VendorLicenseModelDaoZusammenImpl implements VendorLicenseModelDao @Override public void registerVersioning(String versionableEntityType) { VersionableEntityMetadata metadata = - new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "vlm", null, null); + new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "VendorLicenseModel", + null, null); VersioningManagerFactory.getInstance().createInterface() .register(versionableEntityType, metadata); } @Override - public Collection<VendorLicenseModelEntity> list(VendorLicenseModelEntity entity) { + public Collection<VendorLicenseModelEntity> list( + VendorLicenseModelEntity vendorLicenseModelEntity) { + + ElementToVLMGeneralConvertor convertor = new ElementToVLMGeneralConvertor(); return zusammenAdaptor.listItems(ZusammenUtil.createSessionContext()).stream() - .map(item -> mapInfoToVlm( - item.getId().getValue(), null, item.getInfo(), - item.getModificationTime(), item.getCreationTime())) + .filter(item -> "VendorLicenseModel".equals(item.getInfo().getProperty("item_type"))) + .map(item -> { + VendorLicenseModelEntity entity = convertor.convert(item); + entity.setId(item.getId().getValue()); + entity.setVersion(null); + return entity; + }) .collect(Collectors.toList()); } @Override public void create(VendorLicenseModelEntity vendorLicenseModel) { + SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = zusammenAdaptor.createItem(context, mapVlmToZusammenItemInfo(vendorLicenseModel)); - Id versionId = - zusammenAdaptor.createVersion(context, itemId, null, ZusammenUtil.createFirstVersionData()); + ElementContext elementContext = new ElementContext(vendorLicenseModel.getId(), + vendorLicenseModel.getVersion().getId()); ZusammenElement generalElement = mapVlmToZusammenElement(vendorLicenseModel, Action.CREATE); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), - generalElement, "Create VSP General Info Element"); - vendorLicenseModel.setId(itemId.getValue());//set id for caller + zusammenAdaptor.saveElement(context, elementContext, generalElement, + "Create VLM General Info Element"); + + ZusammenElement licenseAgreementsElement = + ZusammenUtil.buildStructuralElement(ElementType.LicenseAgreements, Action.CREATE); + + zusammenAdaptor.saveElement(context, elementContext, licenseAgreementsElement, + "Create VLM licenseAgreementsElement"); + + ZusammenElement featureGroupsElement = + ZusammenUtil.buildStructuralElement(ElementType.FeatureGroups, Action.CREATE); + + zusammenAdaptor.saveElement(context, elementContext, featureGroupsElement, + "Create VLM featureGroupsElement"); + + ZusammenElement lkgsElement = + ZusammenUtil.buildStructuralElement(ElementType.LicenseKeyGroups, Action.CREATE); + + zusammenAdaptor.saveElement(context, elementContext, lkgsElement, + "Create VLM lkgsElement"); + + ZusammenElement entitlementPoolsElement = + ZusammenUtil.buildStructuralElement(ElementType.EntitlementPools, Action.CREATE); + + zusammenAdaptor.saveElement(context, elementContext, entitlementPoolsElement, + "Create VLM entitlementPoolsElement"); } @Override public void update(VendorLicenseModelEntity vendorLicenseModel) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vendorLicenseModel.getId()); - Id versionId = VlmZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - - zusammenAdaptor.updateItem(context, itemId, mapVlmToZusammenItemInfo(vendorLicenseModel)); - ZusammenElement generalElement = mapVlmToZusammenElement(vendorLicenseModel, Action.UPDATE); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), + + SessionContext context = ZusammenUtil.createSessionContext(); + zusammenAdaptor.saveElement(context, + new ElementContext(vendorLicenseModel.getId(), vendorLicenseModel.getVersion().getId()), generalElement, "Update VSP General Info Element"); } @Override public VendorLicenseModelEntity get(VendorLicenseModelEntity vendorLicenseModel) { SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vendorLicenseModel.getId()); - ItemVersion itemVersion = VlmZusammenUtil.getFirstVersion(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, itemVersion.getId(), - VlmZusammenUtil.getVersionTag(vendorLicenseModel.getVersion())); - + ElementContext elementContext = + new ElementContext(vendorLicenseModel.getId(), vendorLicenseModel.getVersion().getId()); + ElementToVLMGeneralConvertor convertor = new ElementToVLMGeneralConvertor(); return zusammenAdaptor - .getElementInfoByName(context, elementContext, null, StructureElement.General.name()) - .map(generalElementInfo -> mapInfoToVlm( - vendorLicenseModel.getId(), vendorLicenseModel.getVersion(), - generalElementInfo.getInfo(), - itemVersion.getModificationTime(), itemVersion.getCreationTime())) + .getElementInfoByName(context, elementContext, null, ElementType.VendorLicenseModel.name()) + .map(generalElementInfo -> { + VendorLicenseModelEntity entity = convertor.convert(generalElementInfo); + entity.setId(vendorLicenseModel.getId()); + entity.setVersion(vendorLicenseModel.getVersion()); + return entity; + }) .orElse(null); } @@ -96,19 +122,19 @@ public class VendorLicenseModelDaoZusammenImpl implements VendorLicenseModelDao } - private Info mapVlmToZusammenItemInfo(VendorLicenseModelEntity vendorLicenseModel) { + /* private Info mapVlmToZusammenItemInfo(VendorLicenseModelEntity vendorLicenseModel) { Info info = new Info(); info.setName(vendorLicenseModel.getVendorName()); info.setDescription(vendorLicenseModel.getDescription()); - info.addProperty("type", "vlm"); + info.addProperty("type", "VendorLicenseModel"); addVlmToInfo(info, vendorLicenseModel); return info; - } + }*/ private ZusammenElement mapVlmToZusammenElement(VendorLicenseModelEntity vendorLicenseModel, Action action) { ZusammenElement generalElement = - VlmZusammenUtil.buildStructuralElement(StructureElement.General, action); + ZusammenUtil.buildStructuralElement(ElementType.VendorLicenseModel, action); addVlmToInfo(generalElement.getInfo(), vendorLicenseModel); return generalElement; } @@ -117,22 +143,21 @@ public class VendorLicenseModelDaoZusammenImpl implements VendorLicenseModelDao info.addProperty(InfoPropertyName.name.name(), vendorLicenseModel.getVendorName()); info.addProperty(InfoPropertyName.description.name(), vendorLicenseModel.getDescription()); info.addProperty(InfoPropertyName.iconRef.name(), vendorLicenseModel.getIconRef()); + info.addProperty(InfoPropertyName.oldVersion.name(), vendorLicenseModel.getOldVersion()); } - private VendorLicenseModelEntity mapInfoToVlm(String vlmId, Version version, Info info, - Date modificationTime, Date creationTime) { + /*private VendorLicenseModelEntity mapInfoToVlm(String vlmId, Version version, Info info) { VendorLicenseModelEntity vendorLicenseModel = new VendorLicenseModelEntity(vlmId, version); vendorLicenseModel.setVendorName(info.getProperty(InfoPropertyName.name.name())); vendorLicenseModel.setDescription(info.getProperty(InfoPropertyName.description.name())); vendorLicenseModel.setIconRef(info.getProperty(InfoPropertyName.iconRef.name())); - vendorLicenseModel.setWritetimeMicroSeconds( - modificationTime == null ? creationTime.getTime() : modificationTime.getTime()); return vendorLicenseModel; - } + }*/ - private enum InfoPropertyName { + public enum InfoPropertyName { name, description, - iconRef + iconRef, + oldVersion } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VlmZusammenUtil.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VlmZusammenUtil.java index f16d0fae67..07a4f87e67 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VlmZusammenUtil.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/VlmZusammenUtil.java @@ -3,49 +3,13 @@ package org.openecomp.sdc.vendorlicense.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.Action; -import com.amdocs.zusammen.datatypes.item.ItemVersion; import com.amdocs.zusammen.datatypes.item.Relation; import com.amdocs.zusammen.datatypes.item.RelationEdge; -import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.vendorlicense.errors.VendorLicenseModelNotFoundErrorBuilder; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import java.util.Optional; import java.util.stream.Collectors; public class VlmZusammenUtil { - static ItemVersion getFirstVersion(SessionContext context, Id itemId, - ZusammenAdaptor zusammenAdaptor) { - Optional<ItemVersion> itemVersion = zusammenAdaptor.getFirstVersion(context, itemId); - - if (!itemVersion.isPresent()) { - throw new CoreException( - new VendorLicenseModelNotFoundErrorBuilder(itemId.getValue()).build()); - } - return itemVersion.get(); - } - - static Id getFirstVersionId(SessionContext context, Id itemId, ZusammenAdaptor zusammenAdaptor) { - return getFirstVersion(context, itemId, zusammenAdaptor).getId(); - } - - // TODO: 4/25/2017 remove upon working with more than one single version - static String getVersionTag(Version version) { - return version.getStatus() == VersionStatus.Locked - ? null - : version.toString(); - } - - static ZusammenElement buildStructuralElement(StructureElement structureElement, Action action) { - return ZusammenUtil.buildStructuralElement(structureElement.name(), action); - } - static ZusammenElement getZusammenElement(ElementInfo elementInfo) { ZusammenElement zusammenElement = new ZusammenElement(); zusammenElement.setElementId(elementInfo.getId()); @@ -67,6 +31,9 @@ public class VlmZusammenUtil { } public static Integer toInteger(Object val) { + if (val == null) { + return null; + } if (val instanceof Double) { return ((Double) val).intValue(); } else if (val instanceof String) { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToEntitlementPoolConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToEntitlementPoolConvertor.java new file mode 100644 index 0000000000..75fc6f2605 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToEntitlementPoolConvertor.java @@ -0,0 +1,95 @@ +package org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Relation; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; +import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; +import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil.toInteger; + + +public class ElementToEntitlementPoolConvertor extends ElementConvertor { + @Override + public EntitlementPoolEntity convert(Element element) { + if (element == null) { + return null; + } + return mapElementToEntitlementPoolEntity(element); + } + + @Override + public EntitlementPoolEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapElementInfoToEntitlementPoolEntity(elementInfo); + } + + private EntitlementPoolEntity mapElementToEntitlementPoolEntity(Element element) { + EntitlementPoolEntity entitlementPool = + new EntitlementPoolEntity(); + entitlementPool.setId(element.getElementId().getValue()); + mapInfoToEntitlementPoolEntity(entitlementPool, element.getInfo()); + mapRelationsToEntitlementPoolEntity(entitlementPool, element.getRelations()); + return entitlementPool; + } + + private EntitlementPoolEntity mapElementInfoToEntitlementPoolEntity(ElementInfo elementInfo) { + EntitlementPoolEntity entitlementPool = + new EntitlementPoolEntity(); + entitlementPool.setId(elementInfo.getId().getValue()); + mapInfoToEntitlementPoolEntity(entitlementPool, elementInfo.getInfo()); + mapRelationsToEntitlementPoolEntity(entitlementPool, elementInfo.getRelations()); + return entitlementPool; + } + + private void mapInfoToEntitlementPoolEntity(EntitlementPoolEntity entitlementPool, Info info) { + entitlementPool.setName(info.getName()); + entitlementPool.setDescription(info.getDescription()); + entitlementPool.setVersionUuId(info.getProperty("version_uuid")); + entitlementPool.setThresholdValue(toInteger(info.getProperty("thresholdValue"))); + String thresholdUnit = info.getProperty("threshold_unit"); + entitlementPool + .setThresholdUnit(thresholdUnit == null ? null : ThresholdUnit.valueOf(thresholdUnit)); + entitlementPool.setIncrements(info.getProperty("increments")); + entitlementPool.setOperationalScope( + getOperationalScopeMultiChoiceOrOther(info.getProperty("operational_scope"))); + entitlementPool.setStartDate(info.getProperty("startDate")); + entitlementPool.setExpiryDate(info.getProperty("expiryDate")); + } + + private void mapRelationsToEntitlementPoolEntity(EntitlementPoolEntity entitlementPool, + Collection<Relation> relations) { + if (relations != null && relations.size() > 0) { + entitlementPool + .setReferencingFeatureGroups(relations.stream().map(relation -> relation + .getEdge2().getElementId().getValue()).collect(Collectors.toSet())); + } + } + + private MultiChoiceOrOther<OperationalScope> getOperationalScopeMultiChoiceOrOther( + Map<String, Object> operationalScope) { + if (operationalScope == null || operationalScope.isEmpty()) { + return null; + } + + Set<OperationalScope> choices = new HashSet<>(); + ((List<String>) operationalScope.get("choices")). + forEach(choice -> choices.add(OperationalScope.valueOf(choice))); + + Object other = operationalScope.get("other"); + return new MultiChoiceOrOther<>(choices, other == null ? null : (String) other); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToFeatureGroupConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToFeatureGroupConvertor.java new file mode 100644 index 0000000000..e39c22e569 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToFeatureGroupConvertor.java @@ -0,0 +1,83 @@ +package org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Relation; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.RelationType; +import org.openecomp.sdc.vendorlicense.dao.types.FeatureGroupEntity; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + + +public class ElementToFeatureGroupConvertor extends ElementConvertor { + @Override + public FeatureGroupEntity convert(Element element) { + if (element == null) { + return null; + } + return mapElementToFeatureGroupEntity(element); + + } + + @Override + public FeatureGroupEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapElementInfoToFeatureGroupEntity(elementInfo); + + } + + + private FeatureGroupEntity mapElementToFeatureGroupEntity(Element element) { + FeatureGroupEntity featureGroup = + new FeatureGroupEntity(); + featureGroup.setId(element.getElementId().getValue()); + mapInfoToFeatureGroup(featureGroup, element.getInfo()); + mapRelationsToFeatureGroup(featureGroup, element.getRelations()); + return featureGroup; + } + + + private FeatureGroupEntity mapElementInfoToFeatureGroupEntity(ElementInfo elementInfo) { + FeatureGroupEntity featureGroup = new FeatureGroupEntity(); + featureGroup.setId(elementInfo.getId().getValue()); + mapInfoToFeatureGroup(featureGroup, elementInfo.getInfo()); + mapRelationsToFeatureGroup(featureGroup, elementInfo.getRelations()); + return featureGroup; + } + + private void mapInfoToFeatureGroup(FeatureGroupEntity featureGroup, Info info) { + featureGroup.setName(info.getName()); + featureGroup.setDescription(info.getDescription()); + featureGroup.setPartNumber(info.getProperty("partNumber")); + featureGroup.setManufacturerReferenceNumber(info.getProperty("manufacturerReferenceNumber")); + } + + private void mapRelationsToFeatureGroup(FeatureGroupEntity featureGroup, + Collection<Relation> relations) { + Set<String> entitlementPoolIds = new HashSet<>(); + Set<String> licenseAgreements = new HashSet<>(); + Set<String> licenseKeyGroupIds = new HashSet<>(); + + if (relations != null) { + for (Relation relation : relations) { + if (RelationType.FeatureGroupToEntitlmentPool.name().equals(relation.getType())) { + entitlementPoolIds.add(relation.getEdge2().getElementId().getValue()); + } else if (RelationType.FeatureGroupToLicenseKeyGroup.name().equals(relation.getType())) { + licenseKeyGroupIds.add(relation.getEdge2().getElementId().getValue()); + } else if (RelationType.FeatureGroupToReferencingLicenseAgreement.name() + .equals(relation.getType())) { + licenseAgreements.add(relation.getEdge2().getElementId().getValue()); + } + } + } + featureGroup.setEntitlementPoolIds(entitlementPoolIds); + featureGroup.setLicenseKeyGroupIds(licenseKeyGroupIds); + featureGroup.setReferencingLicenseAgreements(licenseAgreements); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseAgreementConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseAgreementConvertor.java new file mode 100644 index 0000000000..a0caa0cf5b --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseAgreementConvertor.java @@ -0,0 +1,86 @@ +package org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Relation; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.types.ChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseAgreementEntity; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseTerm; + +import java.util.Collection; +import java.util.Map; +import java.util.stream.Collectors; + + +public class ElementToLicenseAgreementConvertor extends ElementConvertor { + @Override + public LicenseAgreementEntity convert(Element element) { + if (element == null) { + return null; + } + return mapElementToLicenseAgreementEntity(element); + + } + + + @Override + public LicenseAgreementEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapElementInfoToLicenseAgreementEntity(elementInfo); + + } + + + private LicenseAgreementEntity mapElementToLicenseAgreementEntity(Element element) { + LicenseAgreementEntity licenseAgreement = + new LicenseAgreementEntity(); + licenseAgreement.setId(element.getElementId().getValue()); + mapInfoToLicenseAgreementEntity(licenseAgreement, element.getInfo()); + mapRelationsToLicenseAgreementEntity(licenseAgreement, element.getRelations()); + return licenseAgreement; + } + + + private LicenseAgreementEntity mapElementInfoToLicenseAgreementEntity(ElementInfo elementInfo) { + LicenseAgreementEntity licenseAgreement = + new LicenseAgreementEntity(); + licenseAgreement.setId( elementInfo.getId().getValue()); + mapInfoToLicenseAgreementEntity(licenseAgreement, elementInfo.getInfo()); + mapRelationsToLicenseAgreementEntity(licenseAgreement, elementInfo.getRelations()); + return licenseAgreement; + } + + private void mapRelationsToLicenseAgreementEntity(LicenseAgreementEntity licenseAgreementEntity, + Collection<Relation> relations) { + if (relations != null && relations.size() > 0) { + licenseAgreementEntity.setFeatureGroupIds(relations.stream() + .map(relation -> relation.getEdge2().getElementId().getValue()) + .collect(Collectors.toSet())); + } + + } + + private void mapInfoToLicenseAgreementEntity(LicenseAgreementEntity licenseAgreement, Info info) { + + + licenseAgreement.setName(info.getName()); + licenseAgreement.setDescription(info.getDescription()); + + licenseAgreement + .setLicenseTerm(getCoiceOrOther(info.getProperty("licenseTerm"))); + licenseAgreement.setRequirementsAndConstrains( + info.getProperty("requirementsAndConstrains")); + + } + + private ChoiceOrOther<LicenseTerm> getCoiceOrOther(Map licenseTerm) { + return new ChoiceOrOther<>(LicenseTerm.valueOf((String) licenseTerm.get("choice")), + (String) licenseTerm.get("other")); + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseKeyGroupConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseKeyGroupConvertor.java new file mode 100644 index 0000000000..5956c3e6f1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLicenseKeyGroupConvertor.java @@ -0,0 +1,104 @@ +package org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Relation; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; +import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyType; +import org.openecomp.sdc.vendorlicense.dao.types.MultiChoiceOrOther; +import org.openecomp.sdc.vendorlicense.dao.types.OperationalScope; +import org.openecomp.sdc.vendorlicense.dao.types.ThresholdUnit; + +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VlmZusammenUtil.toInteger; + + +public class ElementToLicenseKeyGroupConvertor extends ElementConvertor { + @Override + public LicenseKeyGroupEntity convert(Element element) { + if (element == null) { + return null; + } + return mapElementToLicenseKeyGroupEntity(element); + + } + + @Override + public LicenseKeyGroupEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapElementInfoToLicenseKeyGroupEntity(elementInfo); + + } + + private LicenseKeyGroupEntity mapElementToLicenseKeyGroupEntity( + Element element) { + LicenseKeyGroupEntity licenseKeyGroup = + new LicenseKeyGroupEntity(); + licenseKeyGroup.setId(element.getElementId().getValue()); + mapInfoToLicenseKeyGroup(licenseKeyGroup, element.getInfo()); + mapRelationsToLicenseKeyGroup(licenseKeyGroup, element.getRelations()); + return licenseKeyGroup; + } + + + private LicenseKeyGroupEntity mapElementInfoToLicenseKeyGroupEntity(ElementInfo elementInfo) { + LicenseKeyGroupEntity licenseKeyGroup = + new LicenseKeyGroupEntity(); + licenseKeyGroup.setId(elementInfo.getId().getValue()); + + mapInfoToLicenseKeyGroup(licenseKeyGroup, elementInfo.getInfo()); + mapRelationsToLicenseKeyGroup(licenseKeyGroup, elementInfo.getRelations()); + return licenseKeyGroup; + } + + private void mapInfoToLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, Info info) { + licenseKeyGroup.setName(info.getName()); + licenseKeyGroup.setDescription(info.getDescription()); + licenseKeyGroup.setVersionUuId(info.getProperty("version_uuid")); + licenseKeyGroup.setType(LicenseKeyType.valueOf(info.getProperty("LicenseKeyType"))); + licenseKeyGroup.setOperationalScope( + getOperationalScopeMultiChoiceOrOther(info.getProperty("operational_scope"))); + licenseKeyGroup.setStartDate(info.getProperty("startDate")); + licenseKeyGroup.setExpiryDate(info.getProperty("expiryDate")); + + String thresholdUnit = info.getProperty("thresholdUnits"); + licenseKeyGroup + .setThresholdUnits(thresholdUnit == null ? null : ThresholdUnit.valueOf(thresholdUnit)); + + licenseKeyGroup.setThresholdValue(toInteger(info.getProperty("thresholdValue"))); + licenseKeyGroup.setIncrements(info.getProperty("increments")); + } + + private void mapRelationsToLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, + Collection<Relation> relations) { + if (relations != null && relations.size() > 0) { + licenseKeyGroup + .setReferencingFeatureGroups((relations.stream().map(relation -> relation + .getEdge2().getElementId().getValue()).collect(Collectors.toSet()))); + } + } + + private MultiChoiceOrOther<OperationalScope> getOperationalScopeMultiChoiceOrOther( + Map<String, Object> operationalScope) { + if (operationalScope == null || operationalScope.isEmpty()) { + return null; + } + + Set<OperationalScope> choices = new HashSet<>(); + ((List<String>) operationalScope.get("choices")). + forEach(choice -> choices.add(OperationalScope.valueOf(choice))); + + Object other = operationalScope.get("other"); + return new MultiChoiceOrOther<>(choices, other == null ? null : (String) other); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLimitConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLimitConvertor.java new file mode 100644 index 0000000000..4b2370aea1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToLimitConvertor.java @@ -0,0 +1,44 @@ +package org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.types.LimitEntity; +import org.openecomp.sdc.vendorlicense.dao.types.LimitType; + +/** + * Created by ayalaben on 9/26/2017 + */ +public class ElementToLimitConvertor extends ElementConvertor { + @Override + public Object convert(Element element) { + if (element == null) { + return null; + } + return mapElementToLimitEntity(element); + } + + private LimitEntity mapElementToLimitEntity(Element element) { + LimitEntity limit = new LimitEntity(); + limit.setId(element.getElementId().getValue()); + limit.setName(element.getInfo().getName()); + limit.setDescription(element.getInfo().getDescription()); + limit.setUnit(element.getInfo().getProperty("unit")); + limit.setMetric(element.getInfo().getProperty("metric")); + limit.setValue(element.getInfo().getProperty("value")); + limit.setTime(element.getInfo().getProperty("time")); + limit.setAggregationFunction(element.getInfo().getProperty("aggregationFunction")); + setLimitType(limit,element.getInfo().getProperty("type")); + + return limit; + } + + private void setLimitType(LimitEntity limit, String type) { + switch (LimitType.valueOf(type)) { + case ServiceProvider: + limit.setType(LimitType.ServiceProvider); + break; + case Vendor: + limit.setType(LimitType.Vendor); + } + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToVLMGeneralConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToVLMGeneralConvertor.java new file mode 100644 index 0000000000..c2ef5a6c41 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/dao/impl/zusammen/convertor/ElementToVLMGeneralConvertor.java @@ -0,0 +1,52 @@ +package org.openecomp.sdc.vendorlicense.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Item; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorlicense.dao.impl.zusammen.VendorLicenseModelDaoZusammenImpl; +import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; + + +public class ElementToVLMGeneralConvertor extends ElementConvertor { + @Override + public VendorLicenseModelEntity convert(Element element) { + if(element == null) return null; + return mapInfoToVendorLicenseModelEntity( element.getInfo()); + + } + + @Override + public VendorLicenseModelEntity convert(Item item) { + if(item == null) return null; + return mapInfoToVendorLicenseModelEntity( item.getInfo()); + } + + @Override + public VendorLicenseModelEntity convert(ElementInfo elementInfo) { + if(elementInfo == null) return null; + return mapInfoToVendorLicenseModelEntity( elementInfo.getInfo()); + + } + + + private VendorLicenseModelEntity mapInfoToVendorLicenseModelEntity(Info info) { + + VendorLicenseModelEntity vendorLicenseModelEntity = new VendorLicenseModelEntity(); + + vendorLicenseModelEntity.setVendorName(info.getProperty( + VendorLicenseModelDaoZusammenImpl.InfoPropertyName.name.name())); + vendorLicenseModelEntity.setDescription(info.getProperty( + VendorLicenseModelDaoZusammenImpl.InfoPropertyName.description.name())); + vendorLicenseModelEntity.setIconRef(info.getProperty( + VendorLicenseModelDaoZusammenImpl.InfoPropertyName.iconRef.name())); + vendorLicenseModelEntity.setOldVersion(info.getProperty( + VendorLicenseModelDaoZusammenImpl.InfoPropertyName.oldVersion.name())); + + + return vendorLicenseModelEntity; + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeImpl.java index b2f2d488e9..0898e48b54 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/facade/impl/VendorLicenseFacadeImpl.java @@ -20,18 +20,12 @@ package org.openecomp.sdc.vendorlicense.facade.impl; -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE; -import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP; -import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG; - import org.apache.commons.collections4.CollectionUtils; import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; @@ -62,23 +56,21 @@ import org.openecomp.sdc.vendorlicense.dao.types.VendorLicenseModelEntity; import org.openecomp.sdc.vendorlicense.errors.SubmitUncompletedLicenseModelErrorBuilder; import org.openecomp.sdc.vendorlicense.errors.VendorLicenseModelNotFoundErrorBuilder; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; -import org.openecomp.sdc.vendorlicense.types.VersionedVendorLicenseModel; -import org.openecomp.sdc.versioning.VersioningManager; -import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.VersioningUtil; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.errors.RequestedVersionInvalidErrorBuilder; import org.openecomp.sdc.versioning.errors.VersionableSubEntityNotFoundErrorBuilder; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; -public class VendorLicenseFacadeImpl implements VendorLicenseFacade { - - private static final VersioningManager versioningManager = - VersioningManagerFactory.getInstance().createInterface(); +import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE; +import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP; +import static org.openecomp.sdc.vendorlicense.errors.UncompletedVendorLicenseModelErrorType.SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG; +public class VendorLicenseFacadeImpl implements VendorLicenseFacade { private static final VendorLicenseModelDao vendorLicenseModelDao = VendorLicenseModelDaoFactory.getInstance().createInterface(); private static final LicenseAgreementDao @@ -91,7 +83,6 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { licenseKeyGroupDao = LicenseKeyGroupDaoFactory.getInstance().createInterface(); private static final LimitDao limitDao = LimitDaoFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); /** * Instantiates a new Vendor license facade. @@ -106,32 +97,7 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } @Override - public Version checkin(String vendorLicenseModelId, String user) { - Version newVersion = versioningManager - .checkin(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelId, user, null); - updateVlmLastModificationTime(vendorLicenseModelId, newVersion); - return newVersion; - } - - @Override - public Version submit(String vendorLicenseModelId, String user) { - validateCompletedVendorLicenseModel(vendorLicenseModelId, user); - Version newVersion = versioningManager - .submit(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelId, user, null); - updateVlmLastModificationTime(vendorLicenseModelId, newVersion); - return newVersion; - } - - @Override - public FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup, String user) { - Version version = VersioningUtil.resolveVersion(featureGroup.getVersion(), - getVersionInfo(featureGroup.getVendorLicenseModelId(), VersionableEntityAction.Read, - user), user); - featureGroup.setVersion(version); - return getFeatureGroup(featureGroup); - } - - private FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup) { + public FeatureGroupEntity getFeatureGroup(FeatureGroupEntity featureGroup) { FeatureGroupEntity retrieved = featureGroupDao.get(featureGroup); VersioningUtil .validateEntityExistence(retrieved, featureGroup, VendorLicenseModelEntity.ENTITY_TYPE); @@ -142,8 +108,8 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } @Override - public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup, String user) { - FeatureGroupEntity retrieved = getFeatureGroup(featureGroup, user); + public FeatureGroupModel getFeatureGroupModel(FeatureGroupEntity featureGroup) { + FeatureGroupEntity retrieved = getFeatureGroup(featureGroup); FeatureGroupModel featureGroupModel = new FeatureGroupModel(); featureGroupModel.setFeatureGroup(retrieved); @@ -164,9 +130,9 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { @Override public LicenseAgreementModel getLicenseAgreementModel(String vlmId, Version version, - String licenseAgreementId, String user) { + String licenseAgreementId) { LicenseAgreementEntity retrieved = - getLicenseAgreement(vlmId, version, licenseAgreementId, user); + getLicenseAgreement(vlmId, version, licenseAgreementId); LicenseAgreementModel licenseAgreementModel = new LicenseAgreementModel(); licenseAgreementModel.setLicenseAgreement(retrieved); @@ -180,103 +146,71 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } @Override - public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool, - String user) { - entitlementPool.setVersion(VersioningUtil.resolveVersion(entitlementPool.getVersion(), - getVersionInfo(entitlementPool.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); - //entitlementPool.setId(CommonMethods.nextUuId()); + public EntitlementPoolEntity createEntitlementPool(EntitlementPoolEntity entitlementPool) { entitlementPool.setVersionUuId(CommonMethods.nextUuId()); UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, - entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().toString(), + entitlementPool.getVendorLicenseModelId(), entitlementPool.getVersion().getId(), entitlementPool.getName()); entitlementPoolDao.create(entitlementPool); - updateVlmLastModificationTime(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion()); return entitlementPool; } @Override - public void updateEntitlementPool(EntitlementPoolEntity entitlementPool, String user) { - entitlementPool.setVersion(VersioningUtil.resolveVersion(entitlementPool.getVersion(), - getVersionInfo(entitlementPool.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); + public void updateEntitlementPool(EntitlementPoolEntity entitlementPool) { EntitlementPoolEntity retrieved = entitlementPoolDao.get(entitlementPool); VersioningUtil .validateEntityExistence(retrieved, entitlementPool, VendorLicenseModelEntity.ENTITY_TYPE); - + if (retrieved.equals(entitlementPool)) { + return; + } UniqueValueUtil.updateUniqueValue(VendorLicenseConstants.UniqueValues.ENTITLEMENT_POOL_NAME, retrieved.getName(), entitlementPool.getName(), entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion().toString()); + entitlementPool.getVersion().getId()); entitlementPool.setVersionUuId(CommonMethods.nextUuId()); entitlementPoolDao.update(entitlementPool); - - updateVlmLastModificationTime(entitlementPool.getVendorLicenseModelId(), - entitlementPool.getVersion()); - } @Override - public Collection<LicenseKeyGroupEntity> listLicenseKeyGroups(String vlmId, Version version, - String user) { - return licenseKeyGroupDao.list(new LicenseKeyGroupEntity(vlmId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user), - null)); + public Collection<LicenseKeyGroupEntity> listLicenseKeyGroups(String vlmId, Version version) { + return licenseKeyGroupDao.list(new LicenseKeyGroupEntity(vlmId, version, null)); } @Override - public Collection<EntitlementPoolEntity> listEntitlementPools(String vlmId, Version version, - String user) { - return entitlementPoolDao.list(new EntitlementPoolEntity(vlmId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user), - null)); + public Collection<EntitlementPoolEntity> listEntitlementPools(String vlmId, Version version) { + return entitlementPoolDao.list(new EntitlementPoolEntity(vlmId, version, null)); } @Override - public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, String user) { - licenseKeyGroup.setVersion(VersioningUtil.resolveVersion(licenseKeyGroup.getVersion(), - getVersionInfo(licenseKeyGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); + public void updateLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { LicenseKeyGroupEntity retrieved = licenseKeyGroupDao.get(licenseKeyGroup); + if (retrieved.equals(licenseKeyGroup)) { + return; + } licenseKeyGroup.setVersionUuId((CommonMethods.nextUuId())); VersioningUtil .validateEntityExistence(retrieved, licenseKeyGroup, VendorLicenseModelEntity.ENTITY_TYPE); UniqueValueUtil.updateUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, retrieved.getName(), licenseKeyGroup.getName(), licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion().toString()); + licenseKeyGroup.getVersion().getId()); licenseKeyGroupDao.update(licenseKeyGroup); - - updateVlmLastModificationTime(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion()); } @Override - public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup, - String user) { - licenseKeyGroup.setVersion(VersioningUtil.resolveVersion(licenseKeyGroup.getVersion(), - getVersionInfo(licenseKeyGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); - //licenseKeyGroup.setId(CommonMethods.nextUuId()); + public LicenseKeyGroupEntity createLicenseKeyGroup(LicenseKeyGroupEntity licenseKeyGroup) { licenseKeyGroup.setVersionUuId(CommonMethods.nextUuId()); UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_KEY_GROUP_NAME, - licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().toString(), + licenseKeyGroup.getVendorLicenseModelId(), licenseKeyGroup.getVersion().getId(), licenseKeyGroup.getName()); licenseKeyGroupDao.create(licenseKeyGroup); - updateVlmLastModificationTime(licenseKeyGroup.getVendorLicenseModelId(), - licenseKeyGroup.getVersion()); return licenseKeyGroup; } @Override - public VersionedVendorLicenseModel getVendorLicenseModel(String vlmId, Version version, - String user) { + public VendorLicenseModelEntity getVendorLicenseModel(String vlmId, Version version) { mdcDataDebugMessage.debugEntryMessage("VLM id", vlmId); - VersionInfo versionInfo = getVersionInfo(vlmId, VersionableEntityAction.Read, user); - - VendorLicenseModelEntity vendorLicenseModel = vendorLicenseModelDao.get( - new VendorLicenseModelEntity(vlmId, - VersioningUtil.resolveVersion(version, versionInfo, user))); + VendorLicenseModelEntity vendorLicenseModel = + vendorLicenseModelDao.get(new VendorLicenseModelEntity(vlmId, version)); if (vendorLicenseModel == null) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.GET_VLM, ErrorLevel.ERROR.name(), @@ -285,90 +219,61 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } mdcDataDebugMessage.debugExitMessage("VLM id", vlmId); - return new VersionedVendorLicenseModel(vendorLicenseModel, versionInfo); - } - - @Override - public VendorLicenseModelEntity createVendorLicenseModel( - VendorLicenseModelEntity vendorLicenseModelEntity, String user) { - - mdcDataDebugMessage.debugEntryMessage(null, null); - - UniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.VENDOR_NAME, - vendorLicenseModelEntity.getVendorName()); - //vendorLicenseModelEntity.setId(CommonMethods.nextUuId()); - - vendorLicenseModelDao.create(vendorLicenseModelEntity); - UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.VENDOR_NAME, - vendorLicenseModelEntity.getVendorName()); - - Version version = versioningManager - .create(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelEntity.getId(), user); - vendorLicenseModelEntity.setVersion(version); - - mdcDataDebugMessage.debugExitMessage(null, null); - return vendorLicenseModelEntity; + return vendorLicenseModel; } @Override - public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement, - String user) { - Version version = VersioningUtil.resolveVersion(licenseAgreement.getVersion(), - getVersionInfo(licenseAgreement.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - licenseAgreement.setVersion(version); + public LicenseAgreementEntity createLicenseAgreement(LicenseAgreementEntity licenseAgreement) { //licenseAgreement.setId(CommonMethods.nextUuId()); VersioningUtil.validateEntitiesExistence(licenseAgreement.getFeatureGroupIds(), - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), version, null), + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion(), + null), featureGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); UniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().toString(), + licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId(), licenseAgreement.getName()); licenseAgreementDao.create(licenseAgreement); UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.LICENSE_AGREEMENT_NAME, - licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().toString(), + licenseAgreement.getVendorLicenseModelId(), licenseAgreement.getVersion().getId(), licenseAgreement.getName()); if (licenseAgreement.getFeatureGroupIds() != null) { for (String addedFgId : licenseAgreement.getFeatureGroupIds()) { featureGroupDao.addReferencingLicenseAgreement( - new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), version, + new FeatureGroupEntity(licenseAgreement.getVendorLicenseModelId(), + licenseAgreement.getVersion(), addedFgId), licenseAgreement.getId()); } } - updateVlmLastModificationTime(licenseAgreement.getVendorLicenseModelId(), - licenseAgreement.getVersion()); - return licenseAgreement; } @Override - public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup, String user) { - Version version = VersioningUtil.resolveVersion(featureGroup.getVersion(), - getVersionInfo(featureGroup.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user); - //featureGroup.setId(CommonMethods.nextUuId()); - featureGroup.setVersion(version); + public FeatureGroupEntity createFeatureGroup(FeatureGroupEntity featureGroup) { VersioningUtil.validateEntitiesExistence(featureGroup.getLicenseKeyGroupIds(), - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), version, null), + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), + null), licenseKeyGroupDao, VendorLicenseModelEntity.ENTITY_TYPE); VersioningUtil.validateEntitiesExistence(featureGroup.getEntitlementPoolIds(), - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), version, null), + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), featureGroup.getVersion(), + null), entitlementPoolDao, VendorLicenseModelEntity.ENTITY_TYPE); UniqueValueUtil.validateUniqueValue(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().toString(), + featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId(), featureGroup.getName()); featureGroupDao.create(featureGroup); UniqueValueUtil.createUniqueValue(VendorLicenseConstants.UniqueValues.FEATURE_GROUP_NAME, - featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().toString(), + featureGroup.getVendorLicenseModelId(), featureGroup.getVersion().getId(), featureGroup.getName()); if (featureGroup.getLicenseKeyGroupIds() != null) { for (String addedLkgId : featureGroup.getLicenseKeyGroupIds()) { licenseKeyGroupDao.addReferencingFeatureGroup( - new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), version, addedLkgId), + new LicenseKeyGroupEntity(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion(), addedLkgId), featureGroup.getId()); } } @@ -376,27 +281,20 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { if (featureGroup.getEntitlementPoolIds() != null) { for (String addedEpId : featureGroup.getEntitlementPoolIds()) { entitlementPoolDao.addReferencingFeatureGroup( - new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), version, addedEpId), - featureGroup.getId()); + new EntitlementPoolEntity(featureGroup.getVendorLicenseModelId(), + featureGroup.getVersion(), addedEpId), featureGroup.getId()); } } - - updateVlmLastModificationTime(featureGroup.getVendorLicenseModelId(), - featureGroup.getVersion()); - return featureGroup; } @Override - public Collection<FeatureGroupEntity> listFeatureGroups(String vlmId, Version version, - String user) { + public Collection<FeatureGroupEntity> listFeatureGroups(String vlmId, Version version) { Collection<FeatureGroupEntity> featureGroupEntities = - featureGroupDao.list(new FeatureGroupEntity(vlmId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), - user), null)); + featureGroupDao.list(new FeatureGroupEntity(vlmId, version, null)); featureGroupEntities.stream() .filter(fgEntity -> Objects.isNull(fgEntity.getManufacturerReferenceNumber())) - .forEach(fgEntity -> updateManufacturerNumberInFeatureGroup(fgEntity)); + .forEach(this::updateManufacturerNumberInFeatureGroup); return featureGroupEntities; } @@ -405,23 +303,22 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { public Collection<ErrorCode> validateLicensingData(String vlmId, Version version, String licenseAgreementId, Collection<String> featureGroupIds) { - try { + // TODO: 5/21/2017 validate version exists and final +/* try { VersionInfo versionInfo = getVersionInfo(vlmId, VersionableEntityAction.Read, ""); if (version == null || !version.isFinal() || !versionInfo.getViewableVersions().contains(version)) { return Collections.singletonList(new RequestedVersionInvalidErrorBuilder().build()); } } catch (CoreException exception) { - log.debug("",exception); return Collections.singletonList(exception.code()); - } + }*/ List<ErrorCode> errorMessages = new ArrayList<>(); try { - getLicenseAgreement(vlmId, licenseAgreementId, version); + getLicenseAgreement(vlmId, version, licenseAgreementId); } catch (CoreException exception) { - log.debug("",exception); errorMessages.add(exception.code()); } @@ -438,7 +335,6 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { version).build()); } } catch (CoreException exception) { - log.debug("",exception); errorMessages.add(exception.code()); } } @@ -447,71 +343,34 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } @Override - public VersionInfo getVersionInfo(String vendorLicenseModelId, VersionableEntityAction action, - String user) { - return versioningManager - .getEntityVersionInfo(VENDOR_LICENSE_MODEL_VERSIONABLE_TYPE, vendorLicenseModelId, user, - action); + public LicenseAgreementEntity getLicenseAgreement(String vlmId, Version version, + String licenseAgreementId) { + LicenseAgreementEntity input = new LicenseAgreementEntity(vlmId, version, licenseAgreementId); + LicenseAgreementEntity retrieved = licenseAgreementDao.get(input); + VersioningUtil.validateEntityExistence(retrieved, input, VendorLicenseModelEntity.ENTITY_TYPE); + return retrieved; } @Override - public void updateVlmLastModificationTime(String vendorLicenseModelId, Version version) { - VendorLicenseModelEntity retrieved = - vendorLicenseModelDao.get(new VendorLicenseModelEntity(vendorLicenseModelId, version)); - vendorLicenseModelDao.update(retrieved); + public Collection<LimitEntity> listLimits(String vlmId, Version version, String epLkgId) { + return limitDao.list(new LimitEntity(vlmId, version, epLkgId, null)); } @Override - public LicenseAgreementEntity getLicenseAgreement(String vlmId, Version version, - String licenseAgreementId, String user) { - return getLicenseAgreement(vlmId, licenseAgreementId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user)); - } - - @Override - public LimitEntity createLimit(LimitEntity limit, String user) { - limit.setVersion(VersioningUtil.resolveVersion(limit.getVersion(), - getVersionInfo(limit.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); - //limit.setVersionUuId(CommonMethods.nextUuId()); + public LimitEntity createLimit(LimitEntity limit) { limitDao.create(limit); - updateVlmLastModificationTime(limit.getVendorLicenseModelId(), - limit.getVersion()); return limit; } @Override - public Collection<LimitEntity> listLimits(String vlmId, Version version, String epLkgId, - String user) { - return limitDao.list(new LimitEntity(vlmId, VersioningUtil - .resolveVersion(version, getVersionInfo(vlmId, VersionableEntityAction.Read, user), user), - epLkgId, null)); - - } - - @Override - public void updateLimit(LimitEntity limit, String user) { - limit.setVersion(VersioningUtil.resolveVersion(limit.getVersion(), - getVersionInfo(limit.getVendorLicenseModelId(), VersionableEntityAction.Write, - user), user)); - //limit.setVersionUuId(CommonMethods.nextUuId()); + public void updateLimit(LimitEntity limit) { limitDao.update(limit); - updateVlmLastModificationTime(limit.getVendorLicenseModelId(), - limit.getVersion()); - } - - private LicenseAgreementEntity getLicenseAgreement(String vlmId, String licenseAgreementId, - Version version) { - LicenseAgreementEntity input = new LicenseAgreementEntity(vlmId, version, licenseAgreementId); - LicenseAgreementEntity retrieved = licenseAgreementDao.get(input); - VersioningUtil.validateEntityExistence(retrieved, input, VendorLicenseModelEntity.ENTITY_TYPE); - return retrieved; } private void updateManufacturerNumberInFeatureGroup(FeatureGroupEntity featureGroupEntity) { if (CollectionUtils.isNotEmpty(featureGroupEntity.getEntitlementPoolIds())) { Object[] entitlementPoolIdsList = featureGroupEntity.getEntitlementPoolIds().toArray(); - if (entitlementPoolIdsList != null && entitlementPoolIdsList.length > 0) { + if (entitlementPoolIdsList.length > 0) { String entitlementPoolId = entitlementPoolIdsList[0].toString(); EntitlementPoolEntity entitlementPoolEntity = new EntitlementPoolEntity(featureGroupEntity.getVendorLicenseModelId(), @@ -523,35 +382,40 @@ public class VendorLicenseFacadeImpl implements VendorLicenseFacade { } } } - private void validateCompletedVendorLicenseModel(String vendorLicenseModelId, String user) { + + @Override + public void validate(String vendorLicenseModelId, Version version) { Collection<String> allFeatureGroupEntities = new HashSet<>(); - Version version = VersioningUtil.resolveVersion(null, - getVersionInfo(vendorLicenseModelId, VersionableEntityAction.Read, user), user); Collection<LicenseAgreementEntity> licenseAgreements = licenseAgreementDao - .list(new LicenseAgreementEntity(vendorLicenseModelId, version, null)); + .list(new LicenseAgreementEntity(vendorLicenseModelId, version, null)); if (CollectionUtils.isNotEmpty(licenseAgreements)) { licenseAgreements.forEach(licenseAgreement -> { if (CollectionUtils.isEmpty(licenseAgreement.getFeatureGroupIds())) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.SUBMIT_ENTITY); + LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.SUBMIT_ENTITY); throw new CoreException( - new SubmitUncompletedLicenseModelErrorBuilder(SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG).build()); + new SubmitUncompletedLicenseModelErrorBuilder( + SUBMIT_UNCOMPLETED_VLM_MSG_LA_MISSING_FG).build()); } allFeatureGroupEntities.addAll(licenseAgreement.getFeatureGroupIds()); }); allFeatureGroupEntities.forEach(fg -> { - FeatureGroupEntity featureGroupEntity = featureGroupDao.get(new FeatureGroupEntity(vendorLicenseModelId, version, fg)); - if(CollectionUtils.isEmpty(featureGroupEntity.getEntitlementPoolIds())) { + FeatureGroupEntity featureGroupEntity = + featureGroupDao.get(new FeatureGroupEntity(vendorLicenseModelId, version, fg)); + if (CollectionUtils.isEmpty(featureGroupEntity.getEntitlementPoolIds())) { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.SUBMIT_ENTITY); + LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.SUBMIT_ENTITY); throw new CoreException( - new SubmitUncompletedLicenseModelErrorBuilder(SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP).build()); + new SubmitUncompletedLicenseModelErrorBuilder( + SUBMIT_UNCOMPLETED_VLM_MSG_FG_MISSING_EP).build()); } }); } } + + } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/healing/impl/SimpleHealingServiceImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/healing/impl/SimpleHealingServiceImpl.java index 7cb3e2e844..c62061e529 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/healing/impl/SimpleHealingServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/healing/impl/SimpleHealingServiceImpl.java @@ -40,14 +40,14 @@ import java.util.UUID; public class SimpleHealingServiceImpl implements HealingService { private static final EntitlementPoolDao entitlementPoolDao = - EntitlementPoolDaoFactory.getInstance().createInterface(); + EntitlementPoolDaoFactory.getInstance().createInterface(); private static final LicenseKeyGroupDao licenseKeyGroupDao = - LicenseKeyGroupDaoFactory.getInstance().createInterface(); + LicenseKeyGroupDaoFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @Override - public VersionableEntity heal(VersionableEntity toHeal, String user) { - return handleMissingVersionId(toHeal, user); + public VersionableEntity heal(VersionableEntity toHeal) { + return handleMissingVersionId(toHeal); } @Override @@ -59,10 +59,10 @@ public class SimpleHealingServiceImpl implements HealingService { } } - private VersionableEntity handleMissingVersionId(VersionableEntity toHeal, String user) { + private VersionableEntity handleMissingVersionId(VersionableEntity toHeal) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (toHeal != null && toHeal.getVersionUuId() != null) { return toHeal; @@ -76,13 +76,13 @@ public class SimpleHealingServiceImpl implements HealingService { licenseKeyGroupDao.update((LicenseKeyGroupEntity) toHeal); } else { MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, - LoggerTragetServiceName.SELF_HEALING, ErrorLevel.ERROR.name(), - LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.UNSUPPORTED_OPERATION); + LoggerTragetServiceName.SELF_HEALING, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.UNSUPPORTED_OPERATION); throw new UnsupportedOperationException( - "Unsupported operation for 1610 release/1607->1610 migration."); + "Unsupported operation for 1610 release/1607->1610 migration."); } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return toHeal; } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceImpl.java index 6dbed22db5..07f19b1e2b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/VendorLicenseArtifactsServiceImpl.java @@ -20,9 +20,6 @@ package org.openecomp.sdc.vendorlicense.licenseartifacts.impl; -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VENDOR_LICENSE_MODEL_ARTIFACT_NAME_WITH_PATH; -import static org.openecomp.sdc.vendorlicense.VendorLicenseConstants.VNF_ARTIFACT_NAME_WITH_PATH; - import org.apache.commons.collections.CollectionUtils; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; @@ -58,15 +55,14 @@ import static org.openecomp.sdc.vendorlicense.licenseartifacts.impl.util.VendorL public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifactsService { public static final VendorLicenseFacade vendorLicenseFacade = - VendorLicenseFacadeFactory.getInstance().createInterface(); + VendorLicenseFacadeFactory.getInstance().createInterface(); public static final HealingService healingService = - HealingServiceFactory.getInstance().createInterface(); + HealingServiceFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private static byte[] createVnfArtifact(String vspId, String vlmId, Version vlmVersion, - String vendorName, - List<String> featureGroups, String user) { + private static byte[] createVnfArtifact(String vspId, String vlmId, Version vlmVersion, String vendorName, + List<String> featureGroups) { mdcDataDebugMessage.debugEntryMessage("VLM name", vendorName); @@ -78,30 +74,31 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts if (featureGroups != null) { for (String featureGroupId : featureGroups) { FeatureGroupModel featureGroupModel = vendorLicenseFacade - .getFeatureGroupModel(new FeatureGroupEntity(vlmId, vlmVersion, featureGroupId), user); + .getFeatureGroupModel(new FeatureGroupEntity(vlmId, vlmVersion, featureGroupId)); Set<EntitlementPoolEntity> entitlementPoolEntities = - featureGroupModel.getEntitlementPools(); + featureGroupModel.getEntitlementPools(); for (EntitlementPoolEntity entitlementPoolEntity : entitlementPoolEntities) { entitlementPoolEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, vlmVersion, - entitlementPoolEntity.getId(), user)); + entitlementPoolEntity.getId())); entitlementPoolEntity.setManufacturerReferenceNumber(featureGroupModel. - getEntityManufacturerReferenceNumber()); + getEntityManufacturerReferenceNumber()); } + Set<LicenseKeyGroupEntity> licenseKeyGroupEntities = - featureGroupModel.getLicenseKeyGroups(); + featureGroupModel.getLicenseKeyGroups(); for (LicenseKeyGroupEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { licenseKeyGroupEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, vlmVersion, - licenseKeyGroupEntity.getId(), user)); + licenseKeyGroupEntity.getId())); licenseKeyGroupEntity.setManufacturerReferenceNumber(featureGroupModel. - getEntityManufacturerReferenceNumber()); + getEntityManufacturerReferenceNumber()); } featureGroupModel.setEntitlementPools(entitlementPoolEntities.stream().map( - entitlementPoolEntity -> (EntitlementPoolEntity) healingService - .heal(entitlementPoolEntity, user)).collect(Collectors.toSet())); + entitlementPoolEntity -> (EntitlementPoolEntity) healingService + .heal(entitlementPoolEntity)).collect(Collectors.toSet())); featureGroupModel.setLicenseKeyGroups(licenseKeyGroupEntities.stream().map( - licenseKeyGroupEntity -> (LicenseKeyGroupEntity) healingService - .heal(licenseKeyGroupEntity, user)).collect(Collectors.toSet())); + licenseKeyGroupEntity -> (LicenseKeyGroupEntity) healingService + .heal(licenseKeyGroupEntity)).collect(Collectors.toSet())); artifact.getFeatureGroups().add(featureGroupModel); } } @@ -110,7 +107,7 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts return artifact.toXml().getBytes(); } - private static byte[] createVendorLicenseArtifact(String vlmId, String vendorName, String user) { + private static byte[] createVendorLicenseArtifact(String vlmId, String vendorName) { mdcDataDebugMessage.debugEntryMessage("VLM name", vendorName); @@ -122,40 +119,37 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts List<Version> finalVersions = getFinalVersionsForVlm(vlmId); for (Version finalVersion : finalVersions) { - Collection<EntitlementPoolEntity> coll = vendorLicenseFacade.listEntitlementPools(vlmId, - finalVersion, user); - coll.stream().forEach(entitlementPoolEntity -> { + Collection<EntitlementPoolEntity> eps = + vendorLicenseFacade.listEntitlementPools(vlmId, finalVersion); + eps.forEach(entitlementPoolEntity -> { entitlementPoolEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, finalVersion, - entitlementPoolEntity.getId(), user)); + entitlementPoolEntity.getId())); Optional<String> manufacturerReferenceNumber = getFeatureGroupManufactureRefNumber - (entitlementPoolEntity.getReferencingFeatureGroups(), vlmId, finalVersion, user); + (entitlementPoolEntity.getReferencingFeatureGroups(), vlmId, finalVersion); manufacturerReferenceNumber - .ifPresent(entitlementPoolEntity::setManufacturerReferenceNumber); + .ifPresent(entitlementPoolEntity::setManufacturerReferenceNumber); }); + entitlementPoolEntities.addAll(eps); - entitlementPoolEntities.addAll(coll); + Collection<LicenseKeyGroupEntity> lkgs = + vendorLicenseFacade.listLicenseKeyGroups(vlmId, finalVersion); - Collection<LicenseKeyGroupEntity> coll2 = vendorLicenseFacade.listLicenseKeyGroups(vlmId, - finalVersion, user); - - coll2.stream().forEach(licenseKeyGroupEntity -> { + lkgs.forEach(licenseKeyGroupEntity -> { licenseKeyGroupEntity.setLimits(vendorLicenseFacade.listLimits(vlmId, finalVersion, - licenseKeyGroupEntity.getId(), user)); + licenseKeyGroupEntity.getId())); Optional<String> manufacturerReferenceNumber = getFeatureGroupManufactureRefNumber - (licenseKeyGroupEntity.getReferencingFeatureGroups(), vlmId, finalVersion, user); + (licenseKeyGroupEntity.getReferencingFeatureGroups(), vlmId, finalVersion); manufacturerReferenceNumber - .ifPresent(licenseKeyGroupEntity::setManufacturerReferenceNumber); + .ifPresent(licenseKeyGroupEntity::setManufacturerReferenceNumber); }); - - licenseKeyGroupEntities.addAll(coll2); + licenseKeyGroupEntities.addAll(lkgs); } + entitlementPoolEntities = - healEPs(user, filterChangedEntities(prepareForFiltering(entitlementPoolEntities, user, - true))); + healEPs(filterChangedEntities(prepareForFiltering(entitlementPoolEntities, true))); licenseKeyGroupEntities = - healLkgs(user, filterChangedEntities(prepareForFiltering(licenseKeyGroupEntities, user, - false))); + healLkgs(filterChangedEntities(prepareForFiltering(licenseKeyGroupEntities, false))); vendorLicenseArtifact.setEntitlementPoolEntities(entitlementPoolEntities); vendorLicenseArtifact.setLicenseKeyGroupEntities(licenseKeyGroupEntities); @@ -165,21 +159,20 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts private static Optional<String> getFeatureGroupManufactureRefNumber(Set<String> featureGroupIds, String vlmId, - Version finalVersion, - String user) { + Version finalVersion) { String manufactureReferenceNumber = null; if (CollectionUtils.isNotEmpty(featureGroupIds)) { Object[] featureGroupIdsList = featureGroupIds.toArray(); if (featureGroupIdsList.length > 0) { FeatureGroupEntity featureGroup = - vendorLicenseFacade.getFeatureGroup(new FeatureGroupEntity(vlmId, finalVersion, - featureGroupIdsList[0].toString()), user); + vendorLicenseFacade.getFeatureGroup(new FeatureGroupEntity(vlmId, finalVersion, + featureGroupIdsList[0].toString())); manufactureReferenceNumber = featureGroup != null ? featureGroup - .getManufacturerReferenceNumber() : null; + .getManufacturerReferenceNumber() : null; } } return manufactureReferenceNumber != null ? Optional.of(manufactureReferenceNumber) : - Optional.empty(); + Optional.empty(); } @@ -190,22 +183,21 @@ public class VendorLicenseArtifactsServiceImpl implements VendorLicenseArtifacts * @param vlmId vlmId * @param vlmVersion vlmVersion * @param featureGroups featureGroups - * @param user user * @return FileContentHandler */ public FileContentHandler createLicenseArtifacts(String vspId, String vlmId, Version vlmVersion, - List<String> featureGroups, String user) { + List<String> featureGroups) { mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); FileContentHandler artifacts = new FileContentHandler(); - String vendorName = getVendorName(vlmId, user); + String vendorName = getVendorName(vlmId); artifacts.addFile(VNF_ARTIFACT_NAME_WITH_PATH, - createVnfArtifact(vspId, vlmId, vlmVersion, vendorName, featureGroups, user)); + createVnfArtifact(vspId, vlmId, vlmVersion, vendorName, featureGroups)); artifacts.addFile(VENDOR_LICENSE_MODEL_ARTIFACT_NAME_WITH_PATH, - createVendorLicenseArtifact(vlmId, vendorName, user)); + createVendorLicenseArtifact(vlmId, vendorName)); mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VnfLicenseArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VnfLicenseArtifact.java index b2cb710eec..91a73b6377 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VnfLicenseArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/VnfLicenseArtifact.java @@ -38,11 +38,11 @@ import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins.MixinF import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins.MixinLicenseKeyGroupEntityForVnfArtifact; import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.types.mixins.MixinLimitArtifact; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamWriter; import java.io.Writer; import java.util.ArrayList; import java.util.List; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamWriter; @JacksonXmlRootElement(localName = "vf-license-model", namespace = "http://xmlns.openecomp.org/asdc/license-model/1.0") diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVendorLicenseArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVendorLicenseArtifact.java index ac45528acd..70ef26f573 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVendorLicenseArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVendorLicenseArtifact.java @@ -62,12 +62,18 @@ public abstract class MixinEntitlementPoolEntityForVendorLicenseArtifact { @JsonProperty(value = "version") abstract String getVersionForArtifact(); - @JsonProperty(value = "start-date") + @JsonIgnore abstract String getStartDate(); - @JsonProperty(value = "expiry-date") + @JsonIgnore abstract String getExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); + + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); + @JsonIgnore abstract String getVendorLicenseModelId(); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVnfArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVnfArtifact.java index ad1a9a6bdf..7618b7a54f 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVnfArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinEntitlementPoolEntityForVnfArtifact.java @@ -42,7 +42,7 @@ public abstract class MixinEntitlementPoolEntityForVnfArtifact { @JsonProperty(value = "threshold-value") abstract ThresholdForXml getThresholdForArtifact(); - @JsonIgnore + @JsonProperty(value = "entitlement-pool-invariant-uuid") abstract String getId(); @JsonProperty(value = "manufacturer-reference-number") @@ -60,7 +60,7 @@ public abstract class MixinEntitlementPoolEntityForVnfArtifact { @JsonIgnore abstract String getVersion(); - @JsonIgnore + @JsonProperty(value = "version") abstract String getVersionForArtifact(); @JsonIgnore @@ -72,12 +72,18 @@ public abstract class MixinEntitlementPoolEntityForVnfArtifact { @JsonIgnore abstract float getThresholdValue(); - @JsonProperty(value = "start-date") + @JsonIgnore abstract String getStartDate(); - @JsonProperty(value = "expiry-date") + @JsonIgnore abstract String getExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); + + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); + @JsonIgnore abstract ChoiceOrOther<EntitlementMetric> getEntitlementMetric(); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVendorLicenseArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVendorLicenseArtifact.java index 5a8e9966cc..eeaa7c0a3a 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVendorLicenseArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVendorLicenseArtifact.java @@ -79,12 +79,18 @@ public abstract class MixinLicenseKeyGroupEntityForVendorLicenseArtifact { @JsonIgnore abstract Collection<LimitEntity> getLimits(); - @JsonProperty(value = "start-date") + @JsonIgnore abstract String getStartDate(); - @JsonProperty(value = "expiry-date") + @JsonIgnore abstract String getExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); + + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); + @JsonProperty(value = "threshold-value") abstract ThresholdForXml getThresholdForArtifact(); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVnfArtifact.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVnfArtifact.java index 4af4b592a9..f560f363a1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVnfArtifact.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/types/mixins/MixinLicenseKeyGroupEntityForVnfArtifact.java @@ -34,7 +34,7 @@ import java.util.Collection; import java.util.Set; public abstract class MixinLicenseKeyGroupEntityForVnfArtifact { - @JsonIgnore + @JsonProperty(value = "license-key-group-invariant-uuid") abstract String getId(); @JsonProperty(value = "manufacturer-reference-number") @@ -46,7 +46,7 @@ public abstract class MixinLicenseKeyGroupEntityForVnfArtifact { @JsonIgnore abstract String getVersion(); - @JsonIgnore + @JsonProperty(value = "version") abstract String getVersionForArtifact(); @JsonIgnore @@ -87,12 +87,18 @@ public abstract class MixinLicenseKeyGroupEntityForVnfArtifact { @JsonIgnore abstract Collection<LimitEntity> getLimits(); - @JsonProperty(value = "start-date") + @JsonIgnore abstract String getStartDate(); - @JsonProperty(value = "expiry-date") + @JsonIgnore abstract String getExpiryDate(); + @JsonProperty(value = "start-date") + abstract String getIsoFormatStartDate(); + + @JsonProperty(value = "expiry-date") + abstract String getIsoFormatExpiryDate(); + @JsonIgnore abstract String getThresholdUnits(); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VendorLicenseArtifactsServiceUtils.java b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VendorLicenseArtifactsServiceUtils.java index 502aa350b9..bd209f9e81 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VendorLicenseArtifactsServiceUtils.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-license-lib/openecomp-sdc-vendor-license-core/src/main/java/org/openecomp/sdc/vendorlicense/licenseartifacts/impl/util/VendorLicenseArtifactsServiceUtils.java @@ -27,16 +27,19 @@ import org.openecomp.sdc.vendorlicense.dao.types.EntitlementPoolEntity; import org.openecomp.sdc.vendorlicense.dao.types.LicenseKeyGroupEntity; import org.openecomp.sdc.vendorlicense.healing.HealingService; import org.openecomp.sdc.vendorlicense.licenseartifacts.impl.VendorLicenseArtifactsServiceImpl; +import org.openecomp.sdc.versioning.ItemManagerFactory; +import org.openecomp.sdc.versioning.VersioningManager; +import org.openecomp.sdc.versioning.VersioningManagerFactory; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.stream.Collectors; /** * @author katyr @@ -45,7 +48,7 @@ import java.util.Set; public class VendorLicenseArtifactsServiceUtils { private static final HealingService healingService = - HealingServiceFactory.getInstance().createInterface(); + HealingServiceFactory.getInstance().createInterface(); /** * maps the entities by id @@ -53,7 +56,7 @@ public class VendorLicenseArtifactsServiceUtils { * @return a Map of id -> list of versionable entities with that id */ private static MultiValuedMap<String, VersionableEntity> mapById( - Collection<? extends VersionableEntity> versionableEntities) { + Collection<? extends VersionableEntity> versionableEntities) { MultiValuedMap<String, VersionableEntity> mappedById = new ArrayListValuedHashMap<>(); for (VersionableEntity ve : versionableEntities) { mappedById.put(ve.getId(), ve); @@ -62,17 +65,18 @@ public class VendorLicenseArtifactsServiceUtils { } /** - * For all entities with same id, only entities that differ from one another will be returned. - * If no change has occured, the entity with the earlier VLM version will be returned. - * If only one version of said entities exists it will be returned + * For all entities with same id, only entities that differ from one another will be returned. + * If no change has occured, the entity with the earlier VLM version will be returned. + * If only one version of said entities exists it will be returned + * * @return a list of entities that has been changed */ public static List<VersionableEntity> filterChangedEntities( - Collection<? extends VersionableEntity> versionableEntities) { + Collection<? extends VersionableEntity> versionableEntities) { MultiValuedMap<String, VersionableEntity> entitiesById = mapById( - versionableEntities); + versionableEntities); MultiValuedMap<String, VersionableEntity> entitiesByVersionUuId = - new ArrayListValuedHashMap<>(); + new ArrayListValuedHashMap<>(); List<VersionableEntity> changedOnly = new ArrayList<>(); for (String epId : entitiesById.keySet()) { @@ -85,7 +89,7 @@ public class VendorLicenseArtifactsServiceUtils { //for every list of eps which have the same uuid, get the one with the earliest vlm version. for (String versionUid : entitiesByVersionUuId.keySet()) { List<VersionableEntity> versionableEntitiesForUuid = - (List<VersionableEntity>) entitiesByVersionUuId.get(versionUid); + (List<VersionableEntity>) entitiesByVersionUuId.get(versionUid); versionableEntitiesForUuid.sort(new VersionableEntitySortByVlmMajorVersion()); changedOnly.add(versionableEntitiesForUuid.get(0)); } @@ -93,40 +97,38 @@ public class VendorLicenseArtifactsServiceUtils { return changedOnly; } - public static Set<LicenseKeyGroupEntity> healLkgs(String user, - Collection<? extends VersionableEntity> licenseKeyGroupEntities) { + public static Set<LicenseKeyGroupEntity> healLkgs( + Collection<? extends VersionableEntity> licenseKeyGroupEntities) { Set<LicenseKeyGroupEntity> healed = new HashSet<>(); for (VersionableEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { healed.add((LicenseKeyGroupEntity) VendorLicenseArtifactsServiceImpl.healingService - .heal(licenseKeyGroupEntity, user)); + .heal(licenseKeyGroupEntity)); } return healed; } - public static Set<EntitlementPoolEntity> healEPs(String user, - Collection<? extends VersionableEntity> entitlementPoolEntities) { + public static Set<EntitlementPoolEntity> healEPs( + Collection<? extends VersionableEntity> entitlementPoolEntities) { Set<EntitlementPoolEntity> healed = new HashSet<>(); for (VersionableEntity entitlementPoolEntity : entitlementPoolEntities) { healed.add((EntitlementPoolEntity) VendorLicenseArtifactsServiceImpl.healingService - .heal(entitlementPoolEntity, user)); + .heal(entitlementPoolEntity)); } return healed; } public static List<Version> getFinalVersionsForVlm(String vlmId) { - VersionInfo versionInfo = - VendorLicenseArtifactsServiceImpl.vendorLicenseFacade - .getVersionInfo(vlmId, VersionableEntityAction.Read, ""); - return versionInfo.getFinalVersions(); - + VersioningManager versioningManager = VersioningManagerFactory.getInstance().createInterface(); + return versioningManager.list(vlmId).stream() + .filter(version -> VersionStatus.Certified == version.getStatus()) + .map(certifiedVersion -> versioningManager.get(vlmId, certifiedVersion)) //sync to private + .collect(Collectors.toList()); } - public static String getVendorName(String vendorLicenseModelId, String user) { - return VendorLicenseArtifactsServiceImpl.vendorLicenseFacade - .getVendorLicenseModel(vendorLicenseModelId, null, user) - .getVendorLicenseModel().getVendorName(); + public static String getVendorName(String vendorLicenseModelId) { + return ItemManagerFactory.getInstance().createInterface().get(vendorLicenseModelId).getName(); } @@ -140,38 +142,36 @@ public class VendorLicenseArtifactsServiceUtils { * to healing as before. For VLMs created post-bugfix this code should not update any element */ public static Collection<? extends VersionableEntity> prepareForFiltering(Collection<? extends - VersionableEntity> versionableEntities, String user, boolean isEP) { + VersionableEntity> versionableEntities, boolean isEP) { MultiValuedMap<String, VersionableEntity> entitiesById = mapById( - versionableEntities); + versionableEntities); for (String epId : entitiesById.keySet()) { List<VersionableEntity> versionableEntitiesForId = new ArrayList<>(); versionableEntitiesForId.addAll(entitiesById.get(epId)); versionableEntitiesForId.sort(new VersionableEntitySortByVlmMajorVersion()); - healingService.heal(versionableEntitiesForId.get(0), user); + healingService.heal(versionableEntitiesForId.get(0)); for (int i = 1; i < versionableEntitiesForId.size(); i++) { if (isEP) { EntitlementPoolEntity current = (EntitlementPoolEntity) versionableEntitiesForId.get(i); EntitlementPoolEntity previous = (EntitlementPoolEntity) versionableEntitiesForId - .get(i - 1); + .get(i - 1); if (current.equals(previous) && current.getVersionUuId() == null) { current.setVersionUuId(previous.getVersionUuId()); healingService.persistNoHealing(current); } else { - versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i), - user)); + versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i))); } } else { LicenseKeyGroupEntity current = (LicenseKeyGroupEntity) versionableEntitiesForId.get(i); LicenseKeyGroupEntity previous = (LicenseKeyGroupEntity) versionableEntitiesForId - .get(i - 1); + .get(i - 1); if (current.equals(previous) && current.getVersionUuId() == null) { current.setVersionUuId(previous.getVersionUuId()); healingService.persistNoHealing(current); } else { - versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i), - user)); + versionableEntitiesForId.set(i, healingService.heal(versionableEntitiesForId.get(i))); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductConstants.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductConstants.java index 8010c40023..bf48bfb40e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductConstants.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/VendorSoftwareProductConstants.java @@ -22,14 +22,14 @@ package org.openecomp.sdc.vendorsoftwareproduct; public final class VendorSoftwareProductConstants { public static final String VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE = "VendorSoftwareProduct"; - public static final String GENERAL_COMPONENT_ID = "General"; public static final String VSP_PACKAGE_ZIP = "VSPPackage.zip"; public static final String CSAR = "CSAR"; public static final String UPLOAD_RAW_DATA = "UPLOAD_RAW_DATA"; public static final String INFORMATION_ARTIFACT_NAME = "VSP_%s_Information.txt"; - public static final String UNSUPPORTED_OPERATION_ERROR = - "An error has occurred: Unsupported operation for 1707 release."; + public static final String UNSUPPORTED_OPERATION_ERROR = + "An error has occurred: Unsupported operation for 1707 release."; public static final String NAME_PATTERN = "^[a-zA-Z0-9_]*$"; + public static final String VALIDATION_VSP_NAME = "validationOnlyVspName"; public final class UniqueValues { public static final String VENDOR_SOFTWARE_PRODUCT_NAME = "Vendor Software Product name"; diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDao.java index a980918c36..cbbb97b3c7 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ComponentDependencyModelDao.java @@ -3,10 +3,7 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; -import org.openecomp.sdc.versioning.dao.types.Version; public interface ComponentDependencyModelDao extends VersionableDao, BaseDao<ComponentDependencyModelEntity> { - - public void deleteAll(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDao.java index fceac0ac98..3d7c621d67 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateCandidateDao.java @@ -31,7 +31,9 @@ public interface OrchestrationTemplateCandidateDao extends VersionableDao { OrchestrationTemplateCandidateData get(String vspId, Version version); - void update(String vspId, OrchestrationTemplateCandidateData candidateData); + OrchestrationTemplateCandidateData getInfo(String vspId, Version version); + + void update(String vspId, Version version, OrchestrationTemplateCandidateData candidateData); void updateStructure(String vspId, Version version, FilesDataStructure fileDataStructure); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDao.java index a8c2eb8f7b..4d82ed37af 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/OrchestrationTemplateDao.java @@ -20,17 +20,16 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadData; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.VersionableDao; import org.openecomp.sdc.versioning.dao.types.Version; public interface OrchestrationTemplateDao extends VersionableDao { - String getValidationData(String vspId, Version version); + OrchestrationTemplateEntity getInfo(String vspId, Version version); - UploadDataEntity getOrchestrationTemplate(String vspId, Version version); + OrchestrationTemplateEntity get(String vspId, Version version); - void updateOrchestrationTemplateData(String vspId, UploadData uploadData); + void update(String vspId, Version version, OrchestrationTemplateEntity uploadData); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDao.java index d12069f480..36fff1e534 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/PackageInfoDao.java @@ -22,17 +22,9 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao; import org.openecomp.core.dao.BaseDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; -import org.openecomp.sdc.versioning.dao.types.Version; -import java.nio.ByteBuffer; import java.util.List; public interface PackageInfoDao extends BaseDao<PackageInfo> { List<PackageInfo> listByCategory(String category, String subCategory); - - public void deleteRowTranslateContent(String vspId, Version version); - - void updateTranslatedContent(String vspId, Version version, ByteBuffer translateContent); - - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDao.java index c6622ef8e5..aea93a352e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ProcessDao.java @@ -12,6 +12,11 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface ProcessDao extends VersionableDao, BaseDao<ProcessEntity> { void deleteAll(ProcessEntity entity); - void deleteVspAll(String vspId, Version version); + + ProcessEntity getArtifact(ProcessEntity entity); + + void uploadArtifact(ProcessEntity entity); + + void deleteArtifact(ProcessEntity entity); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductDao.java deleted file mode 100644 index 48d1e1606a..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductDao.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.dao; - -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; -import org.openecomp.sdc.versioning.dao.VersionableDao; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.util.Collection; -import java.util.List; - - -public interface VendorSoftwareProductDao extends VersionableDao { - - //VspDetails getVendorSoftwareProductInfo(VspDetails vspDetails); - - Collection<ComponentEntity> listComponents(String vspId, Version version); - - Collection<ComponentEntity> listComponentsQuestionnaire(String vspId, Version version); - - Collection<ComponentEntity> listComponentsCompositionAndQuestionnaire(String vspId, - Version version); - - - Collection<ProcessEntity> listProcesses(String vspId, Version version, String componentId); - - void deleteProcesses(String vspId, Version version, String componentId); - - ProcessEntity getProcess(String vspId, Version version, String componentId, String processId); - - void createProcess(ProcessEntity processEntity); - - void updateProcess(ProcessEntity processEntity); - - void deleteProcess(String vspId, Version version, String componentId, String processId); - - - void uploadProcessArtifact(String vspId, Version version, String componentId, String processId, - byte[] artifact, String artifactFileName); - - ProcessEntity getProcessArtifact(String vspId, Version version, String componentId, - String processId); - - void deleteProcessArtifact(String vspId, Version version, String componentId, String processId); - - - Collection<NicEntity> listNicsByVsp(String vspId, Version version); - - - void deleteUploadData(String vspId, Version version); - - //void updateVspLatestModificationTime(String vspId, Version version); - void createComponentDependencyModel( - List<ComponentDependencyModelEntity> componentDependencyModelEntity, String vspId, - Version version); - - Collection<ComponentDependencyModelEntity> listComponentDependencies(String vspId,Version - version); - - void createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor); - - Collection<DeploymentFlavorEntity> listDeploymentFlavors(String vspId, Version version); - - DeploymentFlavorEntity getDeploymentFlavor(String vspId, Version version, String - deploymentFlavorId); - void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId); - - - void createImage(ImageEntity imageEntity); - - Collection<ImageEntity> listImages(String vspId, Version version, String componentId); - - ImageEntity getImage(String vspId, Version version, String componentId, String imageId); - - Collection<ImageEntity> listImagesByVsp(String vspId, Version version); - - void createCompute(ComputeEntity computeEntity); - - Collection<ComputeEntity> listComputes(String vspId, Version version, String componentId); - - Collection<ComputeEntity> listComputesByVsp(String vspId, Version version); - - ComputeEntity getCompute(String vspId, Version version, String componentId, String - computeFlavorId); - - void deleteImage(String vspId, Version version, String componentId, String imageId); - - void updateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity); - - void updateImage(ImageEntity imageEntity); - - void updateImageQuestionnaire(String vspId, Version activeVersion, String componentId, - String imageId, String questionnaireData); - - void updateComputeQuestionnaire(String vspId, Version activeVersion, String componentId, - String computeId, String questionnaireData); - - void updateCompute(ComputeEntity compute); - - void deleteCompute(String vspId, Version version, String componentId, String computeFlavorId); - -} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDao.java index 0481829ebd..c44a9cd89e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDao.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VendorSoftwareProductInfoDao.java @@ -28,15 +28,9 @@ import org.openecomp.sdc.versioning.dao.types.Version; public interface VendorSoftwareProductInfoDao extends VersionableDao, BaseDao<VspDetails> { - void updateOldVersionIndication(VspDetails vspDetails); - void updateQuestionnaireData(String vspId, Version version, String questionnaireData); - String getQuestionnaireData(String vspId, Version version); - VspQuestionnaireEntity getQuestionnaire(String vspId, Version version); - void deleteAll(String vspId, Version version); - boolean isManual(String vspId, Version version); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDao.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDao.java new file mode 100644 index 0000000000..c9525bfbd8 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDao.java @@ -0,0 +1,16 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao; + +import com.amdocs.zusammen.datatypes.item.Resolution; +import org.openecomp.sdc.versioning.dao.types.Version; + +public interface VspMergeDao { + + boolean isVspModelConflicted(String vspId, Version version); + + void updateVspModelId(String vspId, Version version); + + // TODO: 11/7/2017 change to sdc Resolution + void updateVspModelConflictResolution(String vspId, Version version, Resolution resolution); + + void applyVspModelConflictResolution(String vspId, Version version); +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDaoFactory.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDaoFactory.java new file mode 100644 index 0000000000..40ef50a961 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/VspMergeDaoFactory.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class VspMergeDaoFactory extends AbstractComponentFactory<VspMergeDao> { + + public static VspMergeDaoFactory getInstance() { + return AbstractFactory.getInstance(VspMergeDaoFactory.class); + } +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/DeploymentFlavorEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/DeploymentFlavorEntity.java index b20e11077f..57161fbe2e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/DeploymentFlavorEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/DeploymentFlavorEntity.java @@ -1,6 +1,10 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import com.datastax.driver.mapping.annotations.*; +import com.datastax.driver.mapping.annotations.ClusteringColumn; +import com.datastax.driver.mapping.annotations.Column; +import com.datastax.driver.mapping.annotations.Frozen; +import com.datastax.driver.mapping.annotations.PartitionKey; +import com.datastax.driver.mapping.annotations.Table; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityId; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.CompositionEntityType; diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OnboardingMethod.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OnboardingMethod.java new file mode 100644 index 0000000000..108fd22c1b --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OnboardingMethod.java @@ -0,0 +1,6 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.type; + +public enum OnboardingMethod { + NetworkPackage, + Manual; +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateData.java index de70434d2f..7b19e8630c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateData.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateCandidateData.java @@ -5,15 +5,18 @@ import java.nio.ByteBuffer; public class OrchestrationTemplateCandidateData { private ByteBuffer contentData; private String filesDataStructure; - + private String fileSuffix; + private String fileName; public OrchestrationTemplateCandidateData() { } - public OrchestrationTemplateCandidateData(ByteBuffer contentData, - String dataStructureJson) { + public OrchestrationTemplateCandidateData(ByteBuffer contentData, String dataStructureJson, + String fileSuffix, String fileName) { this.contentData = contentData; this.filesDataStructure = dataStructureJson; + this.fileSuffix = fileSuffix; + this.fileName = fileName; } public ByteBuffer getContentData() { @@ -31,4 +34,20 @@ public class OrchestrationTemplateCandidateData { public void setFilesDataStructure(String filesDataStructure) { this.filesDataStructure = filesDataStructure; } + + public String getFileSuffix() { + return fileSuffix; + } + + public void setFileSuffix(String fileSuffix) { + this.fileSuffix = fileSuffix; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/UploadDataEntity.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateEntity.java index 2ade95b025..ef3a4b6012 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/UploadDataEntity.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/OrchestrationTemplateEntity.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -27,25 +27,22 @@ import org.openecomp.sdc.versioning.dao.types.VersionableEntity; import java.nio.ByteBuffer; -public class UploadDataEntity implements VersionableEntity { - private static final String ENTITY_TYPE = "Vendor Software Product Upload data"; +public class OrchestrationTemplateEntity implements VersionableEntity { + private static final String ENTITY_TYPE = "Vendor Software Product Orchestration Template"; private String id; - private Version version; - + private String fileSuffix; + private String fileName; private String packageName; - private String packageVersion; - private String validationData; - private ByteBuffer contentData; - public UploadDataEntity() { + public OrchestrationTemplateEntity() { } - public UploadDataEntity(String id, Version version) { + public OrchestrationTemplateEntity(String id, Version version) { this.id = id; this.version = version; } @@ -78,6 +75,22 @@ public class UploadDataEntity implements VersionableEntity { this.version = version; } + public String getFileSuffix() { + return fileSuffix; + } + + public void setFileSuffix(String fileSuffix) { + this.fileSuffix = fileSuffix; + } + + public String getFileName() { + return fileName; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + public String getPackageName() { return packageName; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/PackageInfo.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/PackageInfo.java index ad02883b2e..3403f28ab2 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/PackageInfo.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/PackageInfo.java @@ -21,7 +21,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.type; import com.datastax.driver.mapping.annotations.Column; -import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import org.openecomp.sdc.versioning.dao.types.Version; @@ -38,8 +37,7 @@ public class PackageInfo { private String vspId; @PartitionKey(value = 1) - @Frozen - private Version version; + private String version; @Column(name = "display_name") private String displayName; @@ -75,7 +73,7 @@ public class PackageInfo { public PackageInfo(String packageId, Version version) { this.vspId = packageId; - this.version = version; + this.version = version.getName(); } public String getDisplayName() { @@ -94,11 +92,11 @@ public class PackageInfo { this.vspDescription = vspDescription; } - public Version getVersion() { + public String getVersion() { return version; } - public void setVersion(Version version) { + public void setVersion(String version) { this.version = version; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/UploadData.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/UploadData.java deleted file mode 100644 index 071af919a4..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/UploadData.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.dao.type; - -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; - -import java.nio.ByteBuffer; - - -public class UploadData { - - private String id; - - private String packageName; - - private String packageVersion; - - private String validationData; - - private ByteBuffer contentData; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getPackageName() { - return packageName; - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } - - public String getPackageVersion() { - return packageVersion; - } - - public void setPackageVersion(String packageVersion) { - this.packageVersion = packageVersion; - } - - public String getValidationData() { - return validationData; - } - - public void setValidationData(String validationData) { - this.validationData = validationData; - } - - public ValidationStructureList getValidationDataStructure() { - return validationData == null ? null - : JsonUtil.json2Object(validationData, ValidationStructureList.class); - } - - public void setValidationDataStructure(ValidationStructureList validationData) { - this.validationData = validationData == null ? null - : JsonUtil.object2Json(validationData); - } - - public ByteBuffer getContentData() { - return contentData; - } - - public void setContentData(ByteBuffer contentData) { - this.contentData = contentData; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java index 3f9768b9d7..3ba77ad0ee 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/type/VspDetails.java @@ -20,13 +20,10 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.type; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.dao.types.VersionableEntity; import java.util.List; -import java.util.Objects; public class VspDetails implements VersionableEntity { @@ -55,18 +52,10 @@ public class VspDetails implements VersionableEntity { private List<String> featureGroups; - private String validationData; - - private String oldVersion; - private Long writetimeMicroSeconds; private String onboardingMethod; - private String onboardingOrigin; - - private String networkPackageName; - public VspDetails() { } @@ -183,24 +172,6 @@ public class VspDetails implements VersionableEntity { this.featureGroups = featureGroups; } - public String getValidationData() { - return validationData; - } - - public void setValidationData(String validationData) { - this.validationData = validationData; - } - - public ValidationStructureList getValidationDataStructure() { - return validationData == null ? null - : JsonUtil.json2Object(validationData, ValidationStructureList.class); - } - - public void setValidationDataStructure(ValidationStructureList validationData) { - this.validationData = validationData == null ? null - : JsonUtil.object2Json(validationData); - } - public Long getWritetimeMicroSeconds() { return this.writetimeMicroSeconds; } @@ -213,36 +184,14 @@ public class VspDetails implements VersionableEntity { return this.oldVersion; }*/ - public String getOldVersion(){ - return this.oldVersion; - } - - public void setOldVersion(String oldVersion) { - this.oldVersion = oldVersion; - } - - public String getOnboardingOrigin() { - return onboardingOrigin; - } - - public void setOnboardingOrigin(String onboardingOrigin) { - this.onboardingOrigin = onboardingOrigin; - } - public String getOnboardingMethod() { return onboardingMethod; } + public void setOnboardingMethod(String onboardingMethod) { this.onboardingMethod = onboardingMethod; } - public String getNetworkPackageName() { - return networkPackageName; - } - - public void setNetworkPackageName(String networkPackageName) { - this.networkPackageName = networkPackageName; - } @Override public String toString() { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/composition/CompositionEntityDataManager.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/composition/CompositionEntityDataManager.java index b77012e5cf..ff78fff689 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/composition/CompositionEntityDataManager.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/composition/CompositionEntityDataManager.java @@ -22,7 +22,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.services.composition; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; @@ -64,12 +63,10 @@ public interface CompositionEntityDataManager { void saveComponents(String vspId, Version version, CompositionData compositionData, Map<String, String> networkIdByName); - void saveNicsByComponent(String vspId, Version version, - Map<String, String> networkIdByName, Component component, - String componentId); + void saveNicsByComponent(String vspId, Version version, Map<String, String> networkIdByName, + Component component, String componentId); - Map<String, String> saveNetworks(String vspId, Version version, - CompositionData compositionData); + Map<String, String> saveNetworks(String vspId, Version version, CompositionData compositionData); NetworkEntity createNetwork(NetworkEntity network); @@ -77,15 +74,14 @@ public interface CompositionEntityDataManager { NicEntity createNic(NicEntity nic); - public ComputeEntity createCompute(ComputeEntity compute); + DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor); - public DeploymentFlavorEntity createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor); + ImageEntity createImage(ImageEntity image); - public ImageEntity createImage(ImageEntity image); + void saveComputesFlavorByComponent(String vspId, Version version, Component component, + String componentId); - public void saveComputesFlavorByComponent(String vspId, Version version, Component component, String - componentId); - public void saveImagesByComponent(String vspId, Version version, Component component, String - componentId); + void saveImagesByComponent(String vspId, Version version, Component component, + String componentId); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/CandidateService.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/CandidateService.java index 6cc639fac0..697dab27e9 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/CandidateService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/filedatastructuremodule/CandidateService.java @@ -45,19 +45,23 @@ public interface CandidateService { Optional<ErrorMessage> validateRawZipData(byte[] uploadedFileData); OrchestrationTemplateCandidateData createCandidateDataEntity( - CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, AnalyzedZipHeatFiles analyzedZipHeatFiles) throws Exception; + CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, + AnalyzedZipHeatFiles analyzedZipHeatFiles) throws Exception; - void updateCandidateUploadData(OrchestrationTemplateCandidateData uploadData, String - itemId); + void updateCandidateUploadData(String vspId, Version version, + OrchestrationTemplateCandidateData uploadData); Optional<FilesDataStructure> getOrchestrationTemplateCandidateFileDataStructure(String vspId, - Version activeVersion); + Version version); - void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version activeVersion, - FilesDataStructure fileDataStructure); + void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, + FilesDataStructure fileDataStructure); OrchestrationTemplateCandidateData getOrchestrationTemplateCandidate(String vspId, - Version activeVersion); + Version version); + + OrchestrationTemplateCandidateData getOrchestrationTemplateCandidateInfo(String vspId, + Version version); Optional<ByteArrayInputStream> fetchZipFileByteArrayInputStream(String vspId, OrchestrationTemplateCandidateData candidateDataEntity, @@ -66,11 +70,11 @@ public interface CandidateService { Map<String, List<ErrorMessage>> uploadErrors); byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, String vspId, - OnboardingTypesEnum type) - throws IOException; + OnboardingTypesEnum type) throws IOException; Optional<ManifestContent> createManifest(VspDetails vspDetails, - FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles); + FileContentHandler fileContentHandler, + AnalyzedZipHeatFiles analyzedZipHeatFiles); String createManifest(VspDetails vspDetails, FilesDataStructure structure); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java index dd303c7bb9..8ed51603aa 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/HeatFileAnalyzerRowDataImpl.java @@ -28,7 +28,11 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import java.util.regex.Pattern; public class HeatFileAnalyzerRowDataImpl implements HeatFileAnalyzer { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java index 41510ecc13..c34e6541e9 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/utils/CandidateEntityBuilder.java @@ -57,22 +57,22 @@ public class CandidateEntityBuilder { public OrchestrationTemplateCandidateData buildCandidateEntityFromZip( VspDetails vspDetails, byte[] uploadedFileData, FileContentHandler contentMap, - Map<String, List<ErrorMessage>> uploadErrors, String user) throws Exception { + Map<String, List<ErrorMessage>> uploadErrors) throws Exception { //mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); try (InputStream zipFileManifest = contentMap.getFileContent(SdcCommon.MANIFEST_NAME)) { HeatFileAnalyzer heatFileAnalyzer = new HeatFileAnalyzerRowDataImpl(); AnalyzedZipHeatFiles analyzedZipHeatFiles = - heatFileAnalyzer.analyzeFilesNotEligibleForModulesFromFileAnalyzer(contentMap.getFiles()); + heatFileAnalyzer.analyzeFilesNotEligibleForModulesFromFileAnalyzer(contentMap.getFiles()); HeatStructureTree tree = getHeatStructureTree(vspDetails, contentMap, analyzedZipHeatFiles); CandidateDataEntityTo candidateDataEntityTo = - new CandidateDataEntityTo(vspDetails.getId(), user, uploadedFileData, tree, contentMap, - vspDetails.getVersion()); + new CandidateDataEntityTo(vspDetails.getId(), vspDetails.getVersion(), uploadedFileData, + tree, contentMap); candidateDataEntityTo.setErrors(uploadErrors); OrchestrationTemplateCandidateData candidateDataEntity = - candidateService.createCandidateDataEntity(candidateDataEntityTo, zipFileManifest, - analyzedZipHeatFiles); + candidateService.createCandidateDataEntity(candidateDataEntityTo, zipFileManifest, + analyzedZipHeatFiles); MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP Id", vspDetails.getId()); return candidateDataEntity; @@ -81,7 +81,8 @@ public class CandidateEntityBuilder { private HeatStructureTree getHeatStructureTree(VspDetails vspDetails, FileContentHandler contentMap, - AnalyzedZipHeatFiles analyzedZipHeatFiles) throws IOException { + AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws IOException { addManifestToFileContentMapIfNotExist(vspDetails, contentMap, analyzedZipHeatFiles); HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(contentMap); heatTreeManager.createTree(); @@ -90,21 +91,22 @@ public class CandidateEntityBuilder { private void addManifestToFileContentMapIfNotExist(VspDetails vspDetails, FileContentHandler fileContentHandler, - AnalyzedZipHeatFiles analyzedZipHeatFiles) throws IOException { + AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws IOException { MDC_DATA_DEBUG_MESSAGE.debugEntryMessage("VSP Id", vspDetails.getId()); try (InputStream manifest = fileContentHandler.getFileContent(SdcCommon.MANIFEST_NAME)) { if (Objects.isNull(manifest)) { Optional<ManifestContent> manifestContentOptional = - candidateService.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); + candidateService.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); if (!manifestContentOptional.isPresent()) { throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); } ManifestContent manifestContent = manifestContentOptional.get(); fileContentHandler.addFile( - SdcCommon.MANIFEST_NAME, - String.valueOf(JsonUtil.sbObject2Json(manifestContent)).getBytes()); + SdcCommon.MANIFEST_NAME, + String.valueOf(JsonUtil.sbObject2Json(manifestContent)).getBytes()); } } finally { MDC_DATA_DEBUG_MESSAGE.debugExitMessage("VSP Id", vspDetails.getId()); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CandidateDataEntityTo.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CandidateDataEntityTo.java index 4ea0a02053..cf6e6f7181 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CandidateDataEntityTo.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/CandidateDataEntityTo.java @@ -31,32 +31,26 @@ import java.util.Map; public class CandidateDataEntityTo { private final String vspId; - private final String user; -// private final UploadFileResponse uploadFileResponse; - private Map<String, List<ErrorMessage>> errors = new HashMap<>(); + private final Version version; private final byte[] uploadedFileData; private final HeatStructureTree tree; - private final Version activeVersion; private final FileContentHandler contentMap; + private Map<String, List<ErrorMessage>> errors = new HashMap<>(); /** * Instantiates a new Candidate data entity to. - * @param vspId the vsp id - * @param user the user - * @param uploadedFileData the uploaded file data - * @param tree the tree - * @param contentMap the content map - * @param activeVersion the active version + * + * @param vspId the vsp id + * @param uploadedFileData the uploaded file data + * @param tree the tree + * @param contentMap the content map */ - public CandidateDataEntityTo(String vspId, String user, - byte[] uploadedFileData, HeatStructureTree tree, - FileContentHandler contentMap, Version activeVersion) { + public CandidateDataEntityTo(String vspId, Version version, byte[] uploadedFileData, + HeatStructureTree tree, FileContentHandler contentMap) { this.vspId = vspId; - this.user = user; - this.errors = errors; + this.version = version; this.uploadedFileData = uploadedFileData; this.tree = tree; - this.activeVersion = activeVersion; this.contentMap = contentMap; } @@ -64,10 +58,6 @@ public class CandidateDataEntityTo { return vspId; } - public String getUser() { - return user; - } - public byte[] getUploadedFileData() { return uploadedFileData; } @@ -76,15 +66,19 @@ public class CandidateDataEntityTo { return tree; } - public Version getActiveVersion() { - return activeVersion; + public Version getVersion() { + return version; } public FileContentHandler getContentMap() { return contentMap; } - public Map<String, List<ErrorMessage>> getErrors() {return errors;} + public Map<String, List<ErrorMessage>> getErrors() { + return errors; + } - public void setErrors(Map<String, List<ErrorMessage>> errors) {this.errors = errors;} + public void setErrors(Map<String, List<ErrorMessage>> errors) { + this.errors = errors; + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/GuestOS.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/GuestOS.java index db22b3a3ee..489557cf08 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/GuestOS.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/GuestOS.java @@ -26,7 +26,7 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.co public class GuestOS { private String name; private String tools; - private int bitSize; + private Number bitSize; public String getName() { return name; @@ -44,11 +44,11 @@ public class GuestOS { this.tools = tools; } - public int getBitSize() { + public Number getBitSize() { return bitSize; } - public void setBitSize(int bitSize) { + public void setBitSize(Number bitSize) { this.bitSize = bitSize; } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/VmSizing.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/VmSizing.java index fb4aaa61f1..a6a8b406cf 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/VmSizing.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/compute/VmSizing.java @@ -23,8 +23,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.co public class VmSizing { private int numOfCPUs; private String fileSystemSizeGB; - private int persistentStorageVolumeSize; - private int IOOperationsPerSec; + private Number persistentStorageVolumeSize; + private Number IOOperationsPerSec; private String cpuOverSubscriptionRatio; private String memoryRAM; @@ -44,19 +44,19 @@ public class VmSizing { this.fileSystemSizeGB = fileSystemSizeGB; } - public int getPersistentStorageVolumeSize() { + public Number getPersistentStorageVolumeSize() { return persistentStorageVolumeSize; } - public void setPersistentStorageVolumeSize(int persistentStorageVolumeSize) { + public void setPersistentStorageVolumeSize(Number persistentStorageVolumeSize) { this.persistentStorageVolumeSize = persistentStorageVolumeSize; } - public int getIOOperationsPerSec() { + public Number getIOOperationsPerSec() { return IOOperationsPerSec; } - public void setIOOperationsPerSec(int IOOperationsPerSec) { + public void setIOOperationsPerSec(Number IOOperationsPerSec) { this.IOOperationsPerSec = IOOperationsPerSec; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Image.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Image.java index 09e83b875f..e87c0fd2ce 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Image.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Image.java @@ -26,8 +26,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.ge public class Image { private String format; private String providedBy; - private int bootDiskSizePerVM; - private int ephemeralDiskSizePerVM; + private Number bootDiskSizePerVM; + private Number ephemeralDiskSizePerVM; public String getFormat() { return format; @@ -45,19 +45,19 @@ public class Image { this.providedBy = providedBy; } - public int getBootDiskSizePerVM() { + public Number getBootDiskSizePerVM() { return bootDiskSizePerVM; } - public void setBootDiskSizePerVM(int bootDiskSizePerVM) { + public void setBootDiskSizePerVM(Number bootDiskSizePerVM) { this.bootDiskSizePerVM = bootDiskSizePerVM; } - public int getEphemeralDiskSizePerVM() { + public Number getEphemeralDiskSizePerVM() { return ephemeralDiskSizePerVM; } - public void setEphemeralDiskSizePerVM(int ephemeralDiskSizePerVM) { + public void setEphemeralDiskSizePerVM(Number ephemeralDiskSizePerVM) { this.ephemeralDiskSizePerVM = ephemeralDiskSizePerVM; } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Recovery.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Recovery.java index 4a13829d71..f1f8017689 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Recovery.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/general/Recovery.java @@ -24,23 +24,23 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.ge * Created by TALIO on 11/22/2016. */ public class Recovery { - private int pointObjective; - private int timeObjective; + private Number pointObjective; + private Number timeObjective; private String vmProcessFailuresHandling; - public int getPointObjective() { + public Number getPointObjective() { return pointObjective; } - public void setPointObjective(int pointObjective) { + public void setPointObjective(Number pointObjective) { this.pointObjective = pointObjective; } - public int getTimeObjective() { + public Number getTimeObjective() { return timeObjective; } - public void setTimeObjective(int timeObjective) { + public void setTimeObjective(Number timeObjective) { this.timeObjective = timeObjective; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Backup.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Backup.java index df5bcb0a02..2357ddfaa1 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Backup.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/Backup.java @@ -27,7 +27,7 @@ public class Backup { private String backupType; private String backupSolution; private String backupNIC; - private int backupStorageSize; + private Number backupStorageSize; public String getBackupType() { return backupType; @@ -53,11 +53,11 @@ public class Backup { this.backupNIC = backupNIC; } - public int getBackupStorageSize() { + public Number getBackupStorageSize() { return backupStorageSize; } - public void setBackupStorageSize(int backupStorageSize) { + public void setBackupStorageSize(Number backupStorageSize) { this.backupStorageSize = backupStorageSize; } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/LogBackup.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/LogBackup.java index cbf1fbeb78..1b6453ac86 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/LogBackup.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/component/storage/LogBackup.java @@ -24,24 +24,24 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.st * Created by TALIO on 11/22/2016. */ public class LogBackup { - private int sizeOfLogFiles; - private int logBackupFrequency; + private Number sizeOfLogFiles; + private Number logBackupFrequency; private int logRetentionPeriod; private String logFileLocation; - public int getSizeOfLogFiles() { + public Number getSizeOfLogFiles() { return sizeOfLogFiles; } - public void setSizeOfLogFiles(int sizeOfLogFiles) { + public void setSizeOfLogFiles(Number sizeOfLogFiles) { this.sizeOfLogFiles = sizeOfLogFiles; } - public int getLogBackupFrequency() { + public Number getLogBackupFrequency() { return logBackupFrequency; } - public void setLogBackupFrequency(int logBackupFrequency) { + public void setLogBackupFrequency(Number logBackupFrequency) { this.logBackupFrequency = logBackupFrequency; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PeakAndAvg.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PeakAndAvg.java index 3d80224698..1e443277f4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PeakAndAvg.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/PeakAndAvg.java @@ -25,7 +25,7 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; */ public class PeakAndAvg { private int peak; - private int avg; + private Number avg; public int getPeak() { return peak; @@ -35,11 +35,11 @@ public class PeakAndAvg { this.peak = peak; } - public int getAvg() { + public Number getAvg() { return avg; } - public void setAvg(int avg) { + public void setAvg(Number avg) { this.avg = avg; } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Sizing.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Sizing.java index 32a9e5a186..4160cba554 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Sizing.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/nic/Sizing.java @@ -25,7 +25,7 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic; */ public class Sizing { private String describeQualityOfService; - private int acceptablePacketLoss; + private Number acceptablePacketLoss; private PacketsAndBytes inflowTrafficPerSecond; private PacketsAndBytes outflowTrafficPerSecond; private PacketsAndBytes flowLength; @@ -39,11 +39,11 @@ public class Sizing { this.describeQualityOfService = describeQualityOfService; } - public int getAcceptablePacketLoss() { + public Number getAcceptablePacketLoss() { return acceptablePacketLoss; } - public void setAcceptablePacketLoss(int acceptablePacketLoss) { + public void setAcceptablePacketLoss(Number acceptablePacketLoss) { this.acceptablePacketLoss = acceptablePacketLoss; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/StorageDataReplication.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/StorageDataReplication.java index 7c073af422..cf48703371 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/StorageDataReplication.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/types/questionnaire/vsp/general/StorageDataReplication.java @@ -25,8 +25,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general; */ public class StorageDataReplication { private boolean storageReplicationAcrossRegion; - private int storageReplicationSize; - private int storageReplicationFrequency; + private Number storageReplicationSize; + private Number storageReplicationFrequency; private String storageReplicationSource; private String storageReplicationDestination; @@ -38,19 +38,19 @@ public class StorageDataReplication { this.storageReplicationDestination = storageReplicationDestination; } - public int getStorageReplicationSize() { + public Number getStorageReplicationSize() { return storageReplicationSize; } - public void setStorageReplicationSize(int storageReplicationSize) { + public void setStorageReplicationSize(Number storageReplicationSize) { this.storageReplicationSize = storageReplicationSize; } - public int getStorageReplicationFrequency() { + public Number getStorageReplicationFrequency() { return storageReplicationFrequency; } - public void setStorageReplicationFrequency(int storageReplicationFrequency) { + public void setStorageReplicationFrequency(Number storageReplicationFrequency) { this.storageReplicationFrequency = storageReplicationFrequency; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/resources/factoryConfiguration.json index 52c6119ae6..90160c4b12 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/resources/factoryConfiguration.json +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-api/src/main/resources/factoryConfiguration.json @@ -1,8 +1,6 @@ { - "org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.VendorSoftwareProductDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.VspDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.VspDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.VendorSoftwareProductInfoDaoFactoryImpl", - "org.openecomp.sdc.vendorsoftwareproduct.dao.UploadDataDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.UploadDataDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.OrchestrationTemplateCandidateDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.OrchestrationTemplateDaoFactoryImpl", "org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.PackageInfoDaoFactoryImpl", diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDependencyModelDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDependencyModelDaoCassandraImpl.java index aa611c0bd2..2fcbc1aae8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDependencyModelDaoCassandraImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ComponentDependencyModelDaoCassandraImpl.java @@ -52,12 +52,6 @@ public class ComponentDependencyModelDaoCassandraImpl extends CassandraBaseDao } @Override - public void deleteAll(String vspId, Version version) { - accessor.deleteAll(vspId, versionMapper.toUDT(version)); - } - - - @Override public void registerVersioning(String versionableEntityType) { VersionableEntityMetadata metadata = new VersionableEntityMetadata( mapper.getTableMetadata().getName(), diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoImpl.java index 0b29fdab27..41ab1a35ae 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/PackageInfoDaoImpl.java @@ -20,10 +20,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; -import com.datastax.driver.core.UDTValue; import com.datastax.driver.mapping.Mapper; import com.datastax.driver.mapping.Result; -import com.datastax.driver.mapping.UDTMapper; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Query; import org.openecomp.core.dao.impl.CassandraBaseDao; @@ -32,9 +30,7 @@ import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.PackageInfo; -import org.openecomp.sdc.versioning.dao.types.Version; -import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -46,8 +42,6 @@ public class PackageInfoDaoImpl extends CassandraBaseDao<PackageInfo> implements noSqlDb.getMappingManager().mapper(PackageInfo.class); private static final PackageInfoAccessor accessor = noSqlDb.getMappingManager().createAccessor(PackageInfoAccessor.class); - private static final UDTMapper<Version> versionMapper = - noSqlDb.getMappingManager().udtMapper(Version.class); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @@ -58,7 +52,7 @@ public class PackageInfoDaoImpl extends CassandraBaseDao<PackageInfo> implements @Override protected Object[] getKeys(PackageInfo entity) { - return new Object[]{entity.getVspId(), versionMapper.toUDT(entity.getVersion())}; + return new Object[]{entity.getVspId(), entity.getVersion()}; } @Override @@ -68,8 +62,7 @@ public class PackageInfoDaoImpl extends CassandraBaseDao<PackageInfo> implements @Override public List<PackageInfo> listByCategory(String category, String subCategory) { - - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Result<PackageInfo> packages = accessor.listInfo(); List<PackageInfo> filteredPackages = new ArrayList<>(); @@ -86,20 +79,10 @@ public class PackageInfoDaoImpl extends CassandraBaseDao<PackageInfo> implements filteredPackages.add(packageInfo); } } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return filteredPackages; } - @Override - public void deleteRowTranslateContent(String vspId, Version version) { - accessor.deleteRowTranslateContent(vspId, version); - } - - @Override - public void updateTranslatedContent(String vspId, Version version, ByteBuffer translateContent){ - accessor.updateTranslateContent(translateContent, vspId, versionMapper.toUDT(version)); - } - @Accessor interface PackageInfoAccessor { @@ -107,13 +90,5 @@ public class PackageInfoDaoImpl extends CassandraBaseDao<PackageInfo> implements "SELECT vsp_id,version,display_name,vsp_name,vsp_description,vendor_name,category" + " ,sub_category, vendor_release,package_checksum,package_type FROM package_details") Result<PackageInfo> listInfo(); - - @Query("DELETE TRANSLATE_CONTENT FROM package_details WHERE vsp_id=? and version=?") - Result<PackageInfo> deleteRowTranslateContent(String vspId, Version version); - - @Query("UPDATE package_details set translate_content = ? where vsp_id = ? and version = ?") - Result<PackageInfo> updateTranslateContent(ByteBuffer translateContent, String vspId, - UDTValue version); - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ProcessDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ProcessDaoFactoryImpl.java index ada76e790a..0205446ae8 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ProcessDaoFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/ProcessDaoFactoryImpl.java @@ -21,8 +21,8 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ProcessDaoZusammenImpl; public class ProcessDaoFactoryImpl extends ProcessDaoFactory { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductDaoImpl.java deleted file mode 100644 index 832f36b3b9..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductDaoImpl.java +++ /dev/null @@ -1,323 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; - -import org.openecomp.core.model.dao.EnrichedServiceArtifactDao; -import org.openecomp.core.model.dao.EnrichedServiceArtifactDaoFactory; -import org.openecomp.core.model.dao.EnrichedServiceModelDao; -import org.openecomp.core.model.dao.EnrichedServiceModelDaoFactory; -import org.openecomp.core.model.dao.ServiceArtifactDaoFactory; -import org.openecomp.core.model.dao.ServiceArtifactDaoInter; -import org.openecomp.core.model.dao.ServiceModelDao; -import org.openecomp.core.model.dao.ServiceModelDaoFactory; -import org.openecomp.core.model.dao.ServiceTemplateDaoFactory; -import org.openecomp.core.model.dao.ServiceTemplateDaoInter; -import org.openecomp.core.utilities.CommonMethods; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.PackageInfoDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; -import org.openecomp.sdc.versioning.dao.types.Version; - -import java.nio.ByteBuffer; -import java.util.Collection; -import java.util.List; - -public class VendorSoftwareProductDaoImpl implements VendorSoftwareProductDao { - - private static final VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory - .getInstance().createInterface(); - private static final PackageInfoDao packageInfoDao = - PackageInfoDaoFactory.getInstance().createInterface(); - private static final OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDataDao = - OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface(); - private static final NetworkDao networkDao = NetworkDaoFactory.getInstance().createInterface(); - private static final ComponentDao componentDao = - ComponentDaoFactory.getInstance().createInterface(); - private static final NicDao nicDao = NicDaoFactory.getInstance().createInterface(); - private static final ProcessDao processDao = ProcessDaoFactory.getInstance().createInterface(); - private static final ServiceArtifactDaoInter - artifactDao = ServiceArtifactDaoFactory.getInstance().createInterface(); - public static final ServiceTemplateDaoInter - templateDao = ServiceTemplateDaoFactory.getInstance().createInterface(); - private static final EnrichedServiceArtifactDao enrichArtifactDao = - EnrichedServiceArtifactDaoFactory.getInstance().createInterface(); - private static final EnrichedServiceModelDao enrichedServiceModelDao = - EnrichedServiceModelDaoFactory.getInstance().createInterface(); - private static final ServiceModelDao serviceModelDao = - ServiceModelDaoFactory.getInstance().createInterface(); - private static final ComponentDependencyModelDao componentDependencyModelDao = - ComponentDependencyModelDaoFactory.getInstance().createInterface(); - private static final DeploymentFlavorDao - deploymentFlavorDao = DeploymentFlavorDaoFactory.getInstance().createInterface(); - private static final ImageDao imageDao = ImageDaoFactory.getInstance().createInterface(); - private static final ComputeDao computeDao = ComputeDaoFactory.getInstance().createInterface(); - - - @Override - public void registerVersioning(String versionableEntityType) { - vspInfoDao.registerVersioning(versionableEntityType); - networkDao.registerVersioning(versionableEntityType); - componentDao.registerVersioning(versionableEntityType); - nicDao.registerVersioning(versionableEntityType); - processDao.registerVersioning(versionableEntityType); - orchestrationTemplateCandidateDataDao.registerVersioning(versionableEntityType); - componentDependencyModelDao.registerVersioning(versionableEntityType); - computeDao.registerVersioning(versionableEntityType); - deploymentFlavorDao.registerVersioning(versionableEntityType); - imageDao.registerVersioning(versionableEntityType); - } - - @Override - public Collection<ComponentEntity> listComponents(String vspId, Version version) { - return componentDao.list(new ComponentEntity(vspId, version, null)); - } - - @Override - public Collection<ComponentEntity> listComponentsQuestionnaire(String vspId, Version version) { - return componentDao.listQuestionnaires(vspId, version); - } - - @Override - public Collection<ComponentEntity> listComponentsCompositionAndQuestionnaire(String vspId, - Version version) { - return componentDao.listCompositionAndQuestionnaire(vspId, version); - } - - @Override - public Collection<ProcessEntity> listProcesses(String vspId, Version version, - String componentId) { - return processDao.list(new ProcessEntity(vspId, version, componentId, null)); - } - - @Override - public void deleteProcesses(String vspId, Version version, String componentId) { - processDao.delete(new ProcessEntity(vspId, version, componentId, null)); - } - - @Override - public ProcessEntity getProcess(String vspId, Version version, String componentId, - String processId) { - return processDao.get(new ProcessEntity(vspId, version, componentId, processId)); - } - - @Override - public void createProcess(ProcessEntity processEntity) { - processDao.create(processEntity); - } - - @Override - public void updateProcess(ProcessEntity processEntity) { - ProcessEntity process = processDao.get(new ProcessEntity(processEntity.getVspId(), processEntity.getVersion(), - processEntity.getComponentId(), processEntity.getId())); - processEntity.setArtifact(process.getArtifact()); - processEntity.setArtifactName(process.getArtifactName()); - processDao.update(processEntity); - } - - @Override - public void deleteProcess(String vspId, Version version, String componentId, String processId) { - processDao.delete(new ProcessEntity(vspId, version, componentId, processId)); - } - - @Override - public void uploadProcessArtifact(String vspId, Version version, String componentId, - String processId, byte[] artifact, String artifactName) { - ProcessEntity - processArtifact = new ProcessEntity(vspId, version, componentId, processId); - processArtifact = processDao.get(processArtifact); - processArtifact.setArtifact(ByteBuffer.wrap(artifact)); - processArtifact.setArtifactName(artifactName); - processDao.update(processArtifact); - } - - @Override - public ProcessEntity getProcessArtifact(String vspId, Version version, String componentId, - String processId) { - return processDao - .get(new ProcessEntity(vspId, version, componentId, processId)); - } - - @Override - public void deleteProcessArtifact(String vspId, Version version, String componentId, - String processId) { - processDao.delete(new ProcessEntity(vspId, version, componentId, processId)); - } - - @Override - public Collection<NicEntity> listNicsByVsp(String vspId, Version version) { - return nicDao.listByVsp(vspId, version); - } - - @Override - public void deleteUploadData(String vspId, Version version) { - networkDao.deleteAll(vspId, version); - enrichedServiceModelDao.deleteAll(vspId, version); - serviceModelDao.deleteAll(vspId, version); - componentDao.deleteAll(vspId, version); - } - - @Override - public void createComponentDependencyModel(List<ComponentDependencyModelEntity> - componentDependencyModel, String vspId, - Version version) { - componentDependencyModelDao.deleteAll(vspId, version); - for (ComponentDependencyModelEntity entity : componentDependencyModel) { - entity.setId(CommonMethods.nextUuId()); - componentDependencyModelDao.create(entity); - } - } - - @Override - public Collection<ComponentDependencyModelEntity> listComponentDependencies(String vspId, - Version version) { - return componentDependencyModelDao.list(new ComponentDependencyModelEntity(vspId, version, - null)); - } - - @Override - public void createDeploymentFlavor(DeploymentFlavorEntity deploymentFlavor) { - deploymentFlavorDao.create(deploymentFlavor); - } - - @Override - public Collection<DeploymentFlavorEntity> listDeploymentFlavors(String vspId, Version version) { - return deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); - } - - @Override - public DeploymentFlavorEntity getDeploymentFlavor(String vspId, Version version, - String deploymentFlavorId) { - return deploymentFlavorDao.get(new DeploymentFlavorEntity(vspId, version, deploymentFlavorId)); - } - - @Override - public void deleteDeploymentFlavor(String vspId, Version version, String deploymentFlavorId) { - deploymentFlavorDao.delete(new DeploymentFlavorEntity(vspId,version, - deploymentFlavorId)); - } - - @Override - public void createImage(ImageEntity imageEntity) { - imageDao.create(imageEntity); - } - - @Override - public Collection<ImageEntity> listImages(String vspId, Version version, String componentId) { - return imageDao.list(new ImageEntity(vspId, version, componentId, null)); - } - - @Override - public ImageEntity getImage(String vspId, Version version, String componentId, String imageId) { - return imageDao.get(new ImageEntity(vspId, version, componentId, imageId)); - } - - @Override - public Collection<ImageEntity> listImagesByVsp(String vspId, Version version) { - return imageDao.listByVsp(vspId, version); - } - - @Override - public void createCompute(ComputeEntity computeEntity) { - computeDao.create(computeEntity); - } - - @Override - public Collection<ComputeEntity> listComputes(String vspId, Version version, String componentId) { - return computeDao.list(new ComputeEntity(vspId, version, componentId, null)); - } - - @Override - public Collection<ComputeEntity> listComputesByVsp(String vspId, Version version) { - return computeDao.listByVsp(vspId, version); - } - - @Override - public ComputeEntity getCompute(String vspId, Version version, String componentId, - String computeFlavorId) { - return computeDao.get(new ComputeEntity(vspId, version, componentId, computeFlavorId)); - } - - @Override - public void deleteImage(String vspId, Version version, String componentId, String imageId) { - ImageEntity imageEntity = new ImageEntity(vspId, version, componentId, imageId); - imageDao.delete(imageEntity); - } - - @Override - public void updateDeploymentFlavor(DeploymentFlavorEntity deploymentFlavorEntity) { - deploymentFlavorDao.update(deploymentFlavorEntity); - } - - @Override - public void updateImage(ImageEntity imageEntity) { - imageDao.update(imageEntity); - } - - @Override - public void updateImageQuestionnaire(String vspId, Version version, String componentId, - String imageId, String questionnaireData) { - imageDao.updateQuestionnaireData(vspId, version, componentId, imageId, questionnaireData); - } - - @Override - public void updateComputeQuestionnaire(String vspId, Version version, String componentId, - String computeId, String questionnaireData) { - computeDao.updateQuestionnaireData(vspId, version, componentId, computeId, questionnaireData); - } - - @Override - public void updateCompute(ComputeEntity compute) { - computeDao.update(compute); - } - - @Override - public void deleteCompute(String vspId, Version version, String componentId, String - computeFlavorId) { - computeDao.delete(new ComputeEntity(vspId, version, componentId, computeFlavorId)); - } -} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductInfoDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductInfoDaoImpl.java index d9b629cc60..fef49c8199 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductInfoDaoImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VendorSoftwareProductInfoDaoImpl.java @@ -73,32 +73,17 @@ public class VendorSoftwareProductInfoDaoImpl extends CassandraBaseDao<VspDetail } @Override - public void updateOldVersionIndication(VspDetails vspDetails) { - - } - - @Override public void updateQuestionnaireData(String vspId, Version version, String questionnaireData) { } @Override - public String getQuestionnaireData(String vspId, Version version) { - return null; - } - - @Override public VspQuestionnaireEntity getQuestionnaire(String vspId, Version version) { return null; } @Override - public void deleteAll(String vspId, Version version) { - - } - - @Override public boolean isManual(String vspId, Version version) { return false; } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoFactoryImpl.java new file mode 100644 index 0000000000..478681f193 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoFactoryImpl.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; + + +import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDaoFactory; + +public class VspMergeDaoFactoryImpl extends VspMergeDaoFactory { + + private static final VspMergeDao INSTANCE = new + VspMergeDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public VspMergeDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoImpl.java new file mode 100644 index 0000000000..2ccc47a651 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/VspMergeDaoImpl.java @@ -0,0 +1,158 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Action; +import com.amdocs.zusammen.datatypes.item.ElementContext; +import com.amdocs.zusammen.datatypes.item.Resolution; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.mapping.annotations.Accessor; +import com.datastax.driver.mapping.annotations.Query; +import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; +import org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.datatypes.model.ElementType; +import org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDao; +import org.openecomp.sdc.versioning.dao.types.Version; + +import java.util.List; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + +public class VspMergeDaoImpl implements VspMergeDao { + private static final String VSP_MODEL_NOT_EXIST = + "Vsp model does not exist for Vsp %s, version %s."; + + private static VspMergeHintAccessor accessor = + NoSqlDbFactory.getInstance().createInterface() + .getMappingManager().createAccessor(VspMergeHintAccessor.class); + + private ZusammenAdaptor zusammenAdaptor; + + public VspMergeDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } + + @Override + public boolean isVspModelConflicted(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(new Id(vspId), new Id(version.getId())); + + return listVspModels(context, elementContext).size() > 1; + } + + @Override + public void updateVspModelId(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(new Id(vspId), new Id(version.getId())); + + String vspModelId = zusammenAdaptor + .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()) + .orElseThrow(() -> new IllegalStateException( + String.format(VSP_MODEL_NOT_EXIST, vspId, version.getId()))) + .getId().getValue(); + + updateVspModelId(vspId, version, vspModelId); + } + + @Override + public void updateVspModelConflictResolution(String vspId, Version version, + Resolution resolution) { + accessor.updateModelResolution(resolution, getUser(), vspId, version.getId()); + } + + @Override + public void applyVspModelConflictResolution(String vspId, Version version) { + //called only when no conflicts + + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(new Id(vspId), new Id(version.getId())); + + List<ElementInfo> vspModels = listVspModels(context, elementContext); + if (vspModels.size() == 1) { + updateVspModelId(vspId, version, vspModels.iterator().next().getId().getValue()); + return; + } + + if (vspModels.size() != 2) { + return; + } + + String user = getUser(); + Row row = accessor.getModelMergeHint(user, vspId, version.getId()).one(); + if (row == null) { + throw new IllegalStateException( + "Vsp model id must exists if its conflict is being resolved"); + } + String resolutionValue = row.getString("model_resolution"); + if (resolutionValue == null) { + return; // model conflict is not resolved yet + } + + Resolution resolution = Resolution.valueOf(resolutionValue); + String localModelId = row.getString("model_id"); + + String chosenModelId = + keepOnlyChosenVspModel(context, elementContext, vspModels, resolution, localModelId); + + accessor.updateModelMergeHint(chosenModelId, null, user, vspId, version.getId()); + } + + private String keepOnlyChosenVspModel(SessionContext context, ElementContext elementContext, + List<ElementInfo> vspModels, Resolution resolution, + String localModelId) { + String newLocalModelId = null; + for (ElementInfo vspModel : vspModels) { + if (isRedundantModel(vspModel.getId().getValue(), localModelId, resolution)) { + zusammenAdaptor + .saveElement(context, elementContext, buildElement(vspModel.getId(), Action.DELETE), + "Delete Redundant Vsp Model"); + } else { + newLocalModelId = vspModel.getId().getValue(); + } + } + return newLocalModelId; + } + + private boolean isRedundantModel(String modelId, String localModelId, Resolution resolution) { + return resolution == Resolution.THEIRS && modelId.equals(localModelId) || + resolution == Resolution.YOURS && !modelId.equals(localModelId); + } + + private List<ElementInfo> listVspModels(SessionContext context, ElementContext elementContext) { + return zusammenAdaptor.listElements(context, elementContext, null).stream() + .filter(elementInfo -> ElementType.VspModel.name().equals(elementInfo.getInfo().getName())) + .collect(Collectors.toList()); + } + + private void updateVspModelId(String vspId, Version version, String vspModelId) { + accessor.updateModelMergeHint(vspModelId, null, getUser(), vspId, version.getId()); + } + + private String getUser() { + return SessionContextProviderFactory.getInstance().createInterface() + .get().getUser().getUserId(); + } + + @Accessor + interface VspMergeHintAccessor { + + @Query("UPDATE vsp_merge_hint SET model_id=?, model_resolution=? " + + "WHERE space=? AND item_id=? AND version_id=?") + void updateModelMergeHint(String vspModelId, Resolution modelResolution, String space, + String itemId, String versionId); + + @Query( + "UPDATE vsp_merge_hint SET model_resolution=? WHERE space=? AND item_id=? AND version_id=?") + void updateModelResolution(Resolution modelResolution, String space, String itemId, + String versionId); + + @Query("SELECT model_id, model_resolution FROM vsp_merge_hint " + + "WHERE space=? AND item_id=? AND version_id=?") + ResultSet getModelMergeHint(String space, String itemId, String versionId); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentArtifactDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentArtifactDaoZusammenImpl.java index 517f2fd19b..01be738b56 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentArtifactDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentArtifactDaoZusammenImpl.java @@ -1,7 +1,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; -import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; @@ -10,10 +9,10 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import org.openecomp.core.enrichment.types.MonitoringUploadType; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentMonitoringUploadConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; -import org.openecomp.sdc.versioning.dao.types.Version; import java.io.ByteArrayInputStream; import java.nio.ByteBuffer; @@ -21,13 +20,17 @@ import java.util.Collection; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + /** * @author Avrahamg. * @since March 21, 2017 */ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { - private static final String ARTIFACT_NAME = "name"; + private static final String ARTIFACT_NAME = "artifactName"; private ZusammenAdaptor zusammenAdaptor; @@ -43,28 +46,25 @@ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { @Override public Optional<ComponentMonitoringUploadEntity> getByType( ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(componentMonitoringUploadEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(componentMonitoringUploadEntity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(componentMonitoringUploadEntity.getVspId(), + componentMonitoringUploadEntity.getVersion().getId()); + Optional<Element> mibsElement = - zusammenAdaptor.getElementByName(context, elementContext, new Id( - componentMonitoringUploadEntity - .getComponentId()), StructureElement.Mibs.toString()); + zusammenAdaptor.getElementByName(context, elementContext, + new Id(componentMonitoringUploadEntity.getComponentId()), ElementType.Mibs.toString()); if (mibsElement.isPresent()) { Optional<Element> monitoringElement = zusammenAdaptor .getElementByName(context, elementContext, mibsElement.get().getElementId(), - getMonitoringStructuralElement(componentMonitoringUploadEntity.getType()) - .toString()); + getMonitoringStructuralElement(componentMonitoringUploadEntity.getType()).toString()); if (monitoringElement.isPresent()) { - componentMonitoringUploadEntity.setId(monitoringElement.get().getElementId().getValue()); - componentMonitoringUploadEntity - .setArtifactName( - (String) monitoringElement.get().getInfo().getProperties().get(ARTIFACT_NAME)); - componentMonitoringUploadEntity - .setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(monitoringElement.get().getData()))); - return Optional.of(componentMonitoringUploadEntity); + ComponentMonitoringUploadEntity entity = + new ElementToComponentMonitoringUploadConvertor().convert(monitoringElement.get()); + entity.setVspId(componentMonitoringUploadEntity.getVspId()); + entity.setVersion(componentMonitoringUploadEntity.getVersion()); + entity.setComponentId(componentMonitoringUploadEntity.getComponentId()); + return Optional.of(entity); } } @@ -75,93 +75,113 @@ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { public void create(ComponentMonitoringUploadEntity entity) { ZusammenElement mibElement = buildMibElement(entity); - ZusammenElement mibsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Mibs, null); + ZusammenElement mibsElement = buildStructuralElement(ElementType.Mibs, null); - ZusammenElement componentElement = buildComponentElement(entity); + ZusammenElement componentElement = buildElement(new Id(entity.getComponentId()), Action.IGNORE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(entity.getVspId(), entity.getVersion().getId()); - Optional<Element> savedElement = zusammenAdaptor.saveElement(context, elementContext, + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, VspZusammenUtil.aggregateElements(componentElement, mibsElement, mibElement), "Create monitoring upload"); - savedElement.ifPresent(element -> - entity.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + entity.setId(savedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public void delete(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - ZusammenElement mibElement = new ZusammenElement(); - mibElement.setElementId(new Id(componentMonitoringUploadEntity.getId())); - mibElement.setAction(Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(componentMonitoringUploadEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ZusammenElement mibElement = buildMibElementStructure(componentMonitoringUploadEntity); + mibElement.setElementId(new Id(componentMonitoringUploadEntity.getId())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(componentMonitoringUploadEntity.getVspId(), + componentMonitoringUploadEntity.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, mibElement, String.format("Delete mib with id %s", componentMonitoringUploadEntity.getId())); } + + @Override - public Collection<ComponentMonitoringUploadEntity> list(ComponentMonitoringUploadEntity mib) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(mib.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(mib.getVersion())); - - return zusammenAdaptor.listElementsByName(context, elementContext, new Id(mib.getComponentId()), - StructureElement.Mibs.toString()).stream() - .map(elementInfo -> - mapElementInfoToMib(mib.getVspId(), mib.getVersion(), mib.getComponentId(), - elementInfo)) + public Collection<ComponentMonitoringUploadEntity> list( + ComponentMonitoringUploadEntity mibEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(mibEntity.getVspId(), mibEntity.getVersion().getId()); + ElementToComponentMonitoringUploadConvertor + convertor = new ElementToComponentMonitoringUploadConvertor(); + return zusammenAdaptor + .listElementsByName(context, elementContext, new Id(mibEntity.getComponentId()), + ElementType.Mibs.toString()).stream() + .map(elementInfo -> convertor.convert(elementInfo)) + .map(mib -> { + mib.setVspId(mibEntity.getVspId()); + mib.setVersion(mibEntity.getVersion()); + mib.setComponentId(mibEntity.getComponentId()); + return mib; + }) .collect(Collectors.toList()); } @Override public void deleteAll(ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - ZusammenElement mibsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Mibs, Action.DELETE); + /*ZusammenElement mibsElement = + buildStructuralElement(ElementType.Mibs, Action.DELETE); ZusammenElement componentElement = buildComponentElement(componentMonitoringUploadEntity); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(componentMonitoringUploadEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(componentMonitoringUploadEntity.getVspId(), + componentMonitoringUploadEntity.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, - VspZusammenUtil.aggregateElements(componentElement, mibsElement), "Delete mibs"); + VspaggregateElements(componentElement, mibsElement), "Delete mibs"); + +*/ + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(componentMonitoringUploadEntity.getVspId(), + componentMonitoringUploadEntity.getVersion().getId()); + + Optional<Element> optionalElement = zusammenAdaptor.getElementByName(context, + elementContext, new Id(componentMonitoringUploadEntity.getComponentId()), ElementType.Mibs + .name()); + + if (optionalElement.isPresent()) { + Element mibsElement = optionalElement.get(); + Collection<Element> mibs = mibsElement.getSubElements(); + + mibs.forEach(mib -> { + ZusammenElement mibZusammenElement = buildElement(mib.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, mibZusammenElement, + "Delete mib with id " + mib.getElementId()); + }); + } } @Override public Collection<ComponentMonitoringUploadEntity> listArtifacts( ComponentMonitoringUploadEntity monitoringUploadEntity) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(monitoringUploadEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(monitoringUploadEntity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(monitoringUploadEntity.getVspId(), + monitoringUploadEntity.getVersion().getId()); final Optional<Element> elementByName = zusammenAdaptor.getElementByName(context, elementContext, - new Id(monitoringUploadEntity.getComponentId() - ), StructureElement.Mibs.name()); + new Id(monitoringUploadEntity.getComponentId()), ElementType.Mibs.name()); - if(!elementByName.isPresent()) + if (!elementByName.isPresent()) { return null; - else { + } else { final Id elementId = elementByName.get().getElementId(); return zusammenAdaptor.listElementData(context, elementContext, elementId).stream() - .map(element -> - buildMibEntity(element, monitoringUploadEntity) - ).collect(Collectors.toList()); + .map(element -> buildMibEntity(element, monitoringUploadEntity)) + .collect(Collectors.toList()); } } @@ -179,18 +199,10 @@ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { return createdMib; } - private ZusammenElement buildComponentElement( - ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(componentMonitoringUploadEntity.getComponentId())); - componentElement.setAction(Action.IGNORE); - return componentElement; - } + private ZusammenElement buildMibElement( + ComponentMonitoringUploadEntity monitoringUploadEntity) { - private ZusammenElement buildMibElement(ComponentMonitoringUploadEntity monitoringUploadEntity) { - ZusammenElement monitoringElement = VspZusammenUtil - .buildStructuralElement(getMonitoringStructuralElement(monitoringUploadEntity.getType()), - Action.UPDATE); + ZusammenElement monitoringElement = buildMibElementStructure(monitoringUploadEntity); monitoringElement.getInfo().getProperties() .put(ARTIFACT_NAME, monitoringUploadEntity.getArtifactName()); monitoringElement @@ -198,27 +210,23 @@ public class ComponentArtifactDaoZusammenImpl implements ComponentArtifactDao { return monitoringElement; } - private ComponentMonitoringUploadEntity mapElementInfoToMib(String vspId, Version version, - String componentId, - ElementInfo elementInfo) { - ComponentMonitoringUploadEntity - monitoringUploadEntity = new ComponentMonitoringUploadEntity(vspId, version, componentId, - elementInfo.getId().getValue()); - monitoringUploadEntity - .setArtifactName((String) elementInfo.getInfo().getProperties().get(ARTIFACT_NAME)); - monitoringUploadEntity.setType(MonitoringUploadType.valueOf(elementInfo.getInfo().getName())); - return monitoringUploadEntity; + private ZusammenElement buildMibElementStructure( + ComponentMonitoringUploadEntity componentMonitoringUploadEntity) { + ZusammenElement monitoringElement = + buildStructuralElement(getMonitoringStructuralElement(componentMonitoringUploadEntity.getType()), + Action.UPDATE); + return monitoringElement; } - private StructureElement getMonitoringStructuralElement(MonitoringUploadType type) + private ElementType getMonitoringStructuralElement(MonitoringUploadType type) throws IllegalArgumentException { switch (type) { case SNMP_POLL: - return StructureElement.SNMP_POLL; + return ElementType.SNMP_POLL; case SNMP_TRAP: - return StructureElement.SNMP_TRAP; + return ElementType.SNMP_TRAP; case VES_EVENTS: - return StructureElement.VES_EVENTS; + return ElementType.VES_EVENTS; default: throw new IllegalArgumentException(); } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDaoZusammenImpl.java index ed6a13d2a1..e658ea55ae 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDaoZusammenImpl.java @@ -8,20 +8,26 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; -import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentQuestionnnaireConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; -import java.util.Arrays; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class ComponentDaoZusammenImpl implements ComponentDao { private ZusammenAdaptor zusammenAdaptor; @@ -36,105 +42,97 @@ public class ComponentDaoZusammenImpl implements ComponentDao { @Override public Collection<ComponentEntity> list(ComponentEntity component) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(component.getVersion())); + SessionContext context = createSessionContext(); - return listComponents(zusammenAdaptor, context, elementContext, component.getVspId(), - component.getVersion()); + return listComponents(zusammenAdaptor, context, component.getVspId(), component.getVersion()); } static Collection<ComponentEntity> listComponents(ZusammenAdaptor zusammenAdaptor, SessionContext context, - ElementContext elementContext, String vspId, Version version) { - return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.Components.name()) - .stream().map(elementInfo -> mapElementInfoToComponent(vspId, version, elementInfo)) + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + Optional<ElementInfo> vspModel = zusammenAdaptor + .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return new ArrayList<>(); + } + + ElementToComponentConvertor convertor = new ElementToComponentConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), + ElementType.Components.name()).stream() + .map(elementInfo -> { + ComponentEntity entity = convertor.convert(elementInfo); + entity.setVspId(vspId); + entity.setVersion(version); + return entity; + }) .collect(Collectors.toList()); } - private static ComponentEntity mapElementInfoToComponent(String vspId, Version version, - ElementInfo elementInfo) { - ComponentEntity componentEntity = - new ComponentEntity(vspId, version, elementInfo.getId().getValue()); - componentEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return componentEntity; - } @Override public void create(ComponentEntity component) { ZusammenElement componentElement = componentToZusammen(component, Action.CREATE); + ZusammenElement componentsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Components, null); + buildStructuralElement(ElementType.Components, Action.IGNORE); componentsElement.getSubElements().add(componentElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); - Optional<Element> savedElement = zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - componentsElement, "Create component"); - savedElement.ifPresent(element -> - component.setId(element.getSubElements().iterator().next().getElementId().getValue())); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(componentsElement); + + SessionContext context = createSessionContext(); + Element savedVspModel = zusammenAdaptor.saveElement(context, + new ElementContext(component.getVspId(), component.getVersion().getId()), + vspModel, "Create component"); + component.setId(savedVspModel.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public void update(ComponentEntity component) { ZusammenElement componentElement = componentToZusammen(component, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); + SessionContext context = createSessionContext(); zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + new ElementContext(component.getVspId(), component.getVersion().getId()), componentElement, String.format("Update component with id %s", component.getId())); } @Override public ComponentEntity get(ComponentEntity component) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(component.getVersion())); + SessionContext context = createSessionContext(); Optional<Element> element = - zusammenAdaptor.getElement(context, elementContext, component.getId()); + zusammenAdaptor.getElement(context, + new ElementContext(component.getVspId(), component.getVersion().getId()), + component.getId()); if (element.isPresent()) { - component.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return component; + ComponentEntity entity = new ElementToComponentConvertor().convert(element.get()); + entity.setVspId(component.getVspId()); + entity.setVersion(component.getVersion()); + return entity; } return null; } @Override public void delete(ComponentEntity component) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(component.getId())); - componentElement.setAction(Action.DELETE); + ZusammenElement componentElement = buildElement(new Id(component.getId()), Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(component.getVspId()); + SessionContext context = createSessionContext(); zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + new ElementContext(component.getVspId(), component.getVersion().getId()), componentElement, String.format("Delete component with id %s", component.getId())); } @Override public ComponentEntity getQuestionnaireData(String vspId, Version version, String componentId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); - return getQuestionnaire(context, elementContext, + return getQuestionnaire(context, new ElementContext(vspId, version.getId()), new ComponentEntity(vspId, version, componentId)); } @@ -142,14 +140,12 @@ public class ComponentDaoZusammenImpl implements ComponentDao { ComponentEntity component) { Optional<Element> questionnaireElement = zusammenAdaptor .getElementByName(context, elementContext, new Id(component.getId()), - StructureElement.Questionnaire.name()); - return questionnaireElement.map( - element -> element.getData() == null - ? null - : new String(FileUtils.toByteArray(element.getData()))) - .map(questionnaireData -> { - component.setQuestionnaireData(questionnaireData); - return component; + ElementType.ComponentQuestionnaire.name()); + return questionnaireElement.map(new ElementToComponentQuestionnnaireConvertor()::convert) + .map(entity -> { + entity.setVspId(component.getVspId()); + entity.setVersion(component.getVersion()); + return entity; }) .orElse(null); } @@ -160,16 +156,11 @@ public class ComponentDaoZusammenImpl implements ComponentDao { ZusammenElement questionnaireElement = componentQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setAction(Action.IGNORE); - componentElement.setElementId(new Id(componentId)); + ZusammenElement componentElement = buildElement(new Id(componentId), Action.IGNORE); componentElement.setSubElements(Collections.singletonList(questionnaireElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), componentElement, "Update component questionnaire"); } @@ -181,45 +172,57 @@ public class ComponentDaoZusammenImpl implements ComponentDao { @Override public Collection<ComponentEntity> listCompositionAndQuestionnaire(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); Collection<ComponentEntity> components = - listComponents(zusammenAdaptor, context, elementContext, vspId, version); + listComponents(zusammenAdaptor, context, vspId, version); - components.forEach(component -> getQuestionnaire(context, elementContext, component)); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + components.forEach(component -> component.setQuestionnaireData( + getQuestionnaire(context, elementContext, component).getQuestionnaireData())); return components; } @Override public void deleteAll(String vspId, Version version) { - ZusammenElement componentsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Components, Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + Collection<ElementInfo> vspModelSubs = zusammenAdaptor + .listElementsByName(context, elementContext, null, ElementType.VspModel.name()); + + Optional<ElementInfo> componentsElement = vspModelSubs.stream() + .filter(elementInfo -> elementInfo.getInfo() != null + && ElementType.Components.name().equals(elementInfo.getInfo().getName())) + .findFirst(); + if (!componentsElement.isPresent()) { + return; + } - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - componentsElement, "Delete all components"); + ZusammenElement components = buildElement(componentsElement.get().getId(), Action.IGNORE); + components.setSubElements(componentsElement.get().getSubElements().stream() + .map(component -> buildElement(component.getId(), Action.DELETE)) + .collect(Collectors.toList())); + + zusammenAdaptor.saveElement(context, elementContext, components, "Delete all components"); } private ZusammenElement componentToZusammen(ComponentEntity component, Action action) { ZusammenElement componentElement = buildComponentElement(component, action); - if (action == Action.CREATE) { - componentElement - .setSubElements(Arrays.asList( - componentQuestionnaireToZusammen(component.getQuestionnaireData(), Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Nics, Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Processes, Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Mibs, Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Computes, Action.CREATE), - VspZusammenUtil.buildStructuralElement(StructureElement.Images, Action.CREATE))); - + if (action == Action.CREATE) { + ZusammenElement mibs = buildStructuralElement(ElementType.Mibs, Action.CREATE); + mibs.addSubElement(buildStructuralElement(ElementType.SNMP_TRAP, Action.CREATE)); + mibs.addSubElement(buildStructuralElement(ElementType.VES_EVENTS, Action.CREATE)); + mibs.addSubElement(buildStructuralElement(ElementType.SNMP_POLL, Action.CREATE)); + + componentElement.addSubElement(mibs); + componentElement.addSubElement( + componentQuestionnaireToZusammen(component.getQuestionnaireData(), Action.CREATE)); + componentElement.addSubElement(buildStructuralElement(ElementType.Nics, Action.CREATE)); + componentElement.addSubElement(buildStructuralElement(ElementType.Processes, Action.CREATE)); + componentElement.addSubElement(buildStructuralElement(ElementType.Computes, Action.CREATE)); + componentElement.addSubElement(buildStructuralElement(ElementType.Images, Action.CREATE)); } return componentElement; } @@ -227,22 +230,21 @@ public class ComponentDaoZusammenImpl implements ComponentDao { private ZusammenElement componentQuestionnaireToZusammen(String questionnaireData, Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + buildStructuralElement(ElementType.ComponentQuestionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } private ZusammenElement buildComponentElement(ComponentEntity component, Action action) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setAction(action); - if (component.getId() != null) { - componentElement.setElementId(new Id(component.getId())); - } + ZusammenElement componentElement = + buildElement(component.getId() == null ? null : new Id(component.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Component); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Component); info.addProperty(ElementPropertyName.compositionData.name(), component.getCompositionData()); componentElement.setInfo(info); componentElement.setData(new ByteArrayInputStream(component.getCompositionData().getBytes())); return componentElement; } + + } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelDaoZusammenImpl.java index e36b6c7743..6741d72bd2 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComponentDependencyModelDaoZusammenImpl.java @@ -9,17 +9,23 @@ import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDependencyModelDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComponentDependencyModelConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; -import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; +import java.util.ArrayList; import java.util.Collection; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + /** * Created by ayalaben on 5/16/2017. */ @@ -35,19 +41,22 @@ public class ComponentDependencyModelDaoZusammenImpl implements ComponentDepende } @Override - public ComponentDependencyModelEntity get(ComponentDependencyModelEntity entity) { + public ComponentDependencyModelEntity get(ComponentDependencyModelEntity dependency) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(entity.getVspId()); // entity.getId()? - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(entity.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); Optional<ElementInfo> componentDependencyElement = - zusammenAdaptor.getElementInfo(context, elementContext, new Id(entity.getId())); + zusammenAdaptor.getElementInfo(context, elementContext, new Id(dependency.getId())); if (componentDependencyElement.isPresent()) { - addComponentDependencyData(entity, componentDependencyElement.get()); + ElementToComponentDependencyModelConvertor convertor = new + ElementToComponentDependencyModelConvertor(); + + ComponentDependencyModelEntity entity = convertor.convert(componentDependencyElement.get()); + entity.setVspId(dependency.getVspId()); + entity.setVersion(dependency.getVersion()); return entity; } @@ -55,70 +64,52 @@ public class ComponentDependencyModelDaoZusammenImpl implements ComponentDepende } @Override - public void create(ComponentDependencyModelEntity entity) { + public void create(ComponentDependencyModelEntity dependency) { + ZusammenElement componentDependency = + buildComponentDependencyElement(dependency, Action.CREATE); ZusammenElement componentDependencies = - VspZusammenUtil.buildStructuralElement(StructureElement.ComponentDependencies, null); + buildStructuralElement(ElementType.ComponentDependencies, Action.IGNORE); + componentDependencies.addSubElement(componentDependency); - ZusammenElement componentDependency = buildComponentDependencyElement(entity); - componentDependency.setAction(Action.CREATE); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(componentDependencies); - Id itemId = new Id(entity.getVspId()); - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); - Optional<Element> savedElement = zusammenAdaptor.saveElement(context, elementContext, - VspZusammenUtil.aggregateElements(componentDependencies, componentDependency), - "Create component dependency model"); + Element compDepsSavedElement = zusammenAdaptor + .saveElement(context, elementContext, vspModel, "Create component dependency model"); - savedElement.ifPresent(element -> - entity.setId(element.getSubElements().iterator().next().getElementId().getValue())); - } - - @Override - public void update(ComponentDependencyModelEntity entity) { - ZusammenElement componentDependencyElement = buildComponentDependencyElement(entity); - componentDependencyElement.setAction(Action.UPDATE); - - Id itemId = new Id(entity.getVspId()); - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - - zusammenAdaptor.saveElement(context, elementContext, - componentDependencyElement, - String.format("Update component dependency model with id %s", entity.getId())); + dependency.setId(compDepsSavedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override - public void delete(ComponentDependencyModelEntity entity) { - ZusammenElement componentDependencyElement = new ZusammenElement(); - componentDependencyElement.setElementId(new Id(entity.getId())); - componentDependencyElement.setAction(Action.DELETE); + public void update(ComponentDependencyModelEntity dependency) { + ZusammenElement componentDependencyElement = + buildComponentDependencyElement(dependency, Action.UPDATE); - Id itemId = new Id(entity.getVspId()); - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); - - zusammenAdaptor.saveElement(context, elementContext, - componentDependencyElement, - String.format("Delete component dependency model with id %s", entity.getId())); + zusammenAdaptor.saveElement(context, elementContext, componentDependencyElement, + String.format("Update component dependency model with id %s", dependency.getId())); } @Override - public void deleteAll(String vspId, Version version) { - ZusammenElement componentDependenciesElement = - VspZusammenUtil - .buildStructuralElement(StructureElement.ComponentDependencies, Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - componentDependenciesElement, "Delete all component dependencies"); + public void delete(ComponentDependencyModelEntity dependency) { + ZusammenElement componentDependencyElement = + buildElement(new Id(dependency.getId()), Action.DELETE); + + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); + + zusammenAdaptor.saveElement(context, elementContext, componentDependencyElement, + String.format("Delete component dependency model with id %s", dependency.getId())); } @Override @@ -127,75 +118,55 @@ public class ComponentDependencyModelDaoZusammenImpl implements ComponentDepende } @Override - public Collection<ComponentDependencyModelEntity> list(ComponentDependencyModelEntity entity) { - - Id itemId = new Id(entity.getVspId()); - SessionContext context = ZusammenUtil.createSessionContext(); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(entity.getVersion())); - - return zusammenAdaptor.listElementsByName(context, elementContext, - null, StructureElement.ComponentDependencies.name()) - .stream().map(elementInfo -> mapElementInfoToComponentDependencyModel(entity.getVspId(), - entity.getVersion(), elementInfo)) - .collect(Collectors.toList()); - } + public Collection<ComponentDependencyModelEntity> list( + ComponentDependencyModelEntity dependency) { + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(dependency.getVspId(), dependency.getVersion().getId()); + + Optional<ElementInfo> vspModel = zusammenAdaptor + .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return new ArrayList<>(); + } - private static ComponentDependencyModelEntity mapElementInfoToComponentDependencyModel( - String vspId, Version version, - ElementInfo elementInfo) { - ComponentDependencyModelEntity componentDependencyModelEntity = - new ComponentDependencyModelEntity(vspId, version, elementInfo.getId().getValue()); - componentDependencyModelEntity.setSourceComponentId(elementInfo.getInfo() - .getProperty(ComponentDependencyModelPropertyName.sourcecomponent_id.name())); - componentDependencyModelEntity.setTargetComponentId(elementInfo.getInfo() - .getProperty(ComponentDependencyModelPropertyName.targetcomponent_id.name())); - componentDependencyModelEntity.setRelation(elementInfo.getInfo() - .getProperty(ComponentDependencyModelPropertyName.relation.name())); - - return componentDependencyModelEntity; + ElementToComponentDependencyModelConvertor convertor = + new ElementToComponentDependencyModelConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), + ElementType.ComponentDependencies.name()).stream() + .map(elementInfo -> { + ComponentDependencyModelEntity entity = convertor.convert(elementInfo); + entity.setVspId(dependency.getVspId()); + entity.setVersion(dependency.getVersion()); + entity.setId(elementInfo.getId().getValue()); + return entity; + }) + .collect(Collectors.toList()); } - - private ZusammenElement buildComponentDependencyElement(ComponentDependencyModelEntity entity) { - ZusammenElement componentDependencyElement = new ZusammenElement(); - - if (entity.getId() != null) { - componentDependencyElement.setElementId(new Id(entity.getId())); - } + private ZusammenElement buildComponentDependencyElement(ComponentDependencyModelEntity compDep, + Action action) { + ZusammenElement componentDependencyElement = + buildElement(compDep.getId() == null ? null : new Id(compDep.getId()), action); Info info = new Info(); - info.addProperty(ComponentDependencyModelPropertyName.id.name(), entity.getId()); - info.addProperty(ComponentDependencyModelPropertyName.relation.name(), entity.getRelation()); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.ComponentDependency); + //info.addProperty(ComponentDependencyModelPropertyName.id.name(), entity.getId()); + info.addProperty(ComponentDependencyModelPropertyName.relation.name(), compDep.getRelation()); info.addProperty(ComponentDependencyModelPropertyName.sourcecomponent_id.name(), - entity.getSourceComponentId()); + compDep.getSourceComponentId()); info.addProperty(ComponentDependencyModelPropertyName.targetcomponent_id.name(), - entity.getTargetComponentId()); + compDep.getTargetComponentId()); componentDependencyElement.setInfo(info); return componentDependencyElement; } - private void addComponentDependencyData(ComponentDependencyModelEntity componentDependency, - ElementInfo componentDependencyElement) { - componentDependency.setId(componentDependencyElement.getInfo() - .getProperty(ComponentDependencyModelPropertyName.id.name())); - componentDependency.setRelation(componentDependencyElement.getInfo() - .getProperty(ComponentDependencyModelPropertyName.id.name())); - componentDependency.setSourceComponentId(componentDependencyElement.getInfo() - .getProperty(ComponentDependencyModelPropertyName.sourcecomponent_id.name())); - componentDependency.setTargetComponentId(componentDependencyElement.getInfo() - .getProperty(ComponentDependencyModelPropertyName.targetcomponent_id.name())); - } - - private enum ComponentDependencyModelPropertyName { id, relation, sourcecomponent_id, targetcomponent_id, } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComputeDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComputeDaoZusammenImpl.java index aa4bab67df..0f92c95294 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComputeDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ComputeDaoZusammenImpl.java @@ -2,7 +2,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; -import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; @@ -11,11 +10,13 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToComputeConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; import java.util.Collection; @@ -23,6 +24,10 @@ import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class ComputeDaoZusammenImpl implements ComputeDao { private ZusammenAdaptor zusammenAdaptor; @@ -37,83 +42,78 @@ public class ComputeDaoZusammenImpl implements ComputeDao { @Override public Collection<ComputeEntity> list(ComputeEntity compute) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(compute.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(compute.getVspId(), compute.getVersion().getId()); return listComputes(context, elementContext, compute); } private Collection<ComputeEntity> listComputes(SessionContext context, - ElementContext elementContext, ComputeEntity compute) { + ElementContext elementContext, + ComputeEntity compute) { + ElementToComputeConvertor convertor = new ElementToComputeConvertor(); return zusammenAdaptor .listElementsByName(context, elementContext, new Id(compute.getComponentId()), - StructureElement.Computes.name()) - .stream().map(elementInfo -> mapElementInfoToCompute( - compute.getVspId(), compute.getVersion(), compute.getComponentId(), elementInfo)) + ElementType.Computes.name()) + .stream().map(elementInfo -> convertor.convert(elementInfo)) + .map(computeEntity -> { + computeEntity.setComponentId(compute.getComponentId()); + computeEntity.setVspId(compute.getVspId()); + computeEntity.setVersion(compute.getVersion()); + return computeEntity; + }) .collect(Collectors.toList()); } - private static ComputeEntity mapElementInfoToCompute(String vspId, Version version, - String componentId, ElementInfo elementInfo) { - ComputeEntity componentEntity = - new ComputeEntity(vspId, version, componentId, elementInfo.getId().getValue()); - componentEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return componentEntity; - } - @Override public void create(ComputeEntity compute) { ZusammenElement computeElement = computeToZusammen(compute, Action.CREATE); - ZusammenElement computesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Computes, null); + ZusammenElement computesElement = buildStructuralElement(ElementType.Computes, Action.IGNORE); computesElement.setSubElements(Collections.singletonList(computeElement)); - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(compute.getComponentId())); - componentElement.setAction(Action.IGNORE); + ZusammenElement componentElement = + buildElement(new Id(compute.getComponentId()), Action.IGNORE); componentElement.setSubElements(Collections.singletonList(computesElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(compute.getVspId(), compute.getVersion().getId()); - Optional<Element> savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create compute"); - savedElement.ifPresent(element -> - compute.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + compute.setId(savedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public void update(ComputeEntity compute) { ZusammenElement computeElement = computeToZusammen(compute, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(compute.getVspId(), compute.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, computeElement, String.format("Update compute with id %s", compute.getId())); } @Override public ComputeEntity get(ComputeEntity compute) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(compute.getVersion())); - Optional<Element> element = zusammenAdaptor.getElement(context, elementContext, compute.getId()); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(compute.getVspId(), compute.getVersion().getId()); + Optional<Element> element = + zusammenAdaptor.getElement(context, elementContext, compute.getId()); if (element.isPresent()) { - compute.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return compute; + + ElementToComputeConvertor convertor = new ElementToComputeConvertor(); + ComputeEntity entity = convertor.convert(element.get()); + entity.setVspId(compute.getVspId()); + entity.setVersion(compute.getVersion()); + entity.setComponentId(compute.getComponentId()); + return entity; } else { return null; } @@ -121,36 +121,30 @@ public class ComputeDaoZusammenImpl implements ComputeDao { @Override public void delete(ComputeEntity compute) { - ZusammenElement computeElement = new ZusammenElement(); - computeElement.setElementId(new Id(compute.getId())); - computeElement.setAction(Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(compute.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ZusammenElement computeElement = buildElement(new Id(compute.getId()), Action.DELETE); + + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(compute.getVspId(), compute.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, computeElement, String.format("Delete compute with id %s", compute.getId())); } @Override public ComputeEntity getQuestionnaireData(String vspId, Version version, String componentId, - String computeId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + String computeId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); return getQuestionnaire(context, elementContext, new ComputeEntity(vspId, version, componentId, computeId)); } private ComputeEntity getQuestionnaire(SessionContext context, ElementContext elementContext, - ComputeEntity compute) { + ComputeEntity compute) { Optional<Element> questionnaireElement = zusammenAdaptor .getElementByName(context, elementContext, new Id(compute.getId()), - StructureElement.Questionnaire.name()); + ElementType.ComputeQuestionnaire.name()); return questionnaireElement.map( element -> element.getData() == null ? null @@ -168,29 +162,22 @@ public class ComputeDaoZusammenImpl implements ComputeDao { ZusammenElement questionnaireElement = computeQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - ZusammenElement computeElement = new ZusammenElement(); - computeElement.setAction(Action.IGNORE); - computeElement.setElementId(new Id(computeId)); + ZusammenElement computeElement = buildElement(new Id(computeId), Action.IGNORE); computeElement.setSubElements(Collections.singletonList(questionnaireElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); zusammenAdaptor.saveElement(context, elementContext, computeElement, "Update compute " + "questionnaire"); } @Override public Collection<ComputeEntity> listByVsp(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); Collection<ComponentEntity> components = ComponentDaoZusammenImpl - .listComponents(zusammenAdaptor, context, elementContext, vspId, version); + .listComponents(zusammenAdaptor, context, vspId, version); return components.stream() .map(component -> @@ -204,15 +191,23 @@ public class ComputeDaoZusammenImpl implements ComputeDao { @Override public void deleteAll(String vspId, Version version) { - ZusammenElement computesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Computes, Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - computesElement, "Delete all computes"); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + Optional<Element> optionalElement = zusammenAdaptor.getElementByName(context, + elementContext, null, ElementType.Computes.name()); + + if (optionalElement.isPresent()) { + Element computesElement = optionalElement.get(); + Collection<Element> computes = computesElement.getSubElements(); + + computes.forEach(compute -> { + ZusammenElement computeElement = buildElement(compute.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, computeElement, + "Delete compute with id " + compute.getElementId()); + }); + } } private ZusammenElement computeToZusammen(ComputeEntity compute, Action action) { @@ -225,27 +220,21 @@ public class ComputeDaoZusammenImpl implements ComputeDao { } private ZusammenElement computeQuestionnaireToZusammen(String questionnaireData, - Action action) { + Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + buildStructuralElement(ElementType.ComputeQuestionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } private ZusammenElement buildComputeElement(ComputeEntity compute, Action action) { - ZusammenElement computeElement = new ZusammenElement(); - computeElement.setAction(action); - if (compute.getId() != null) { - computeElement.setElementId(new Id(compute.getId())); - } + ZusammenElement computeElement = + buildElement(compute.getId() == null ? null : new Id(compute.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Compute); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Compute); info.addProperty(ElementPropertyName.compositionData.name(), compute.getCompositionData()); computeElement.setInfo(info); computeElement.setData(new ByteArrayInputStream(compute.getCompositionData().getBytes())); return computeElement; } - - - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/DeploymentFlavorDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/DeploymentFlavorDaoZusammenImpl.java index 947bcc27e5..17580b293b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/DeploymentFlavorDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/DeploymentFlavorDaoZusammenImpl.java @@ -1,7 +1,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; -import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; @@ -10,16 +9,22 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToDeploymentFlavorConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; import java.util.Collection; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class DeploymentFlavorDaoZusammenImpl implements DeploymentFlavorDao { private ZusammenAdaptor zusammenAdaptor; @@ -34,52 +39,49 @@ public class DeploymentFlavorDaoZusammenImpl implements DeploymentFlavorDao { @Override public Collection<DeploymentFlavorEntity> list(DeploymentFlavorEntity deploymentFlavor) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(deploymentFlavor.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()); - return listDeploymentFlavor(zusammenAdaptor, context, elementContext, deploymentFlavor.getVspId(), + return listDeploymentFlavor(zusammenAdaptor, context, elementContext, + deploymentFlavor.getVspId(), deploymentFlavor.getVersion()); } - static Collection<DeploymentFlavorEntity> listDeploymentFlavor(ZusammenAdaptor zusammenAdaptor, - SessionContext context, - ElementContext elementContext, - String vspId, Version version) { + private static Collection<DeploymentFlavorEntity> listDeploymentFlavor( + ZusammenAdaptor zusammenAdaptor, + SessionContext context, + ElementContext elementContext, + String vspId, Version version) { + ElementToDeploymentFlavorConvertor convertor = new ElementToDeploymentFlavorConvertor(); return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.DeploymentFlavors.name()) - .stream().map(elementInfo -> mapElementInfoToComponent(vspId, version, elementInfo)) + .listElementsByName(context, elementContext, null, + ElementType.DeploymentFlavors.name()) + .stream().map(elementInfo -> { + DeploymentFlavorEntity entity = convertor.convert( + elementInfo); + entity.setVspId(vspId); + entity.setVersion(version); + return entity; + }) .collect(Collectors.toList()); } - private static DeploymentFlavorEntity mapElementInfoToComponent(String vspId, Version version, - ElementInfo elementInfo) { - DeploymentFlavorEntity deploymentFlavorEntity = - new DeploymentFlavorEntity(vspId, version, elementInfo.getId().getValue()); - deploymentFlavorEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return deploymentFlavorEntity; - } @Override public void create(DeploymentFlavorEntity deploymentFlavor) { ZusammenElement deploymentFlavorElement = deploymentFlavorToZusammen(deploymentFlavor, Action.CREATE); ZusammenElement deploymentFlavorElements = - VspZusammenUtil.buildStructuralElement(StructureElement.DeploymentFlavors, null); + buildStructuralElement(ElementType.DeploymentFlavors, Action.IGNORE); deploymentFlavorElements.getSubElements().add(deploymentFlavorElement); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); - Optional<Element> savedElement = zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + SessionContext context = createSessionContext(); + Element savedElement = zusammenAdaptor.saveElement(context, + new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), deploymentFlavorElements, "Create deloymentFlavor"); - savedElement.ifPresent(element -> - deploymentFlavor.setId(element.getSubElements().iterator().next().getElementId() - .getValue())); + deploymentFlavor.setId(savedElement.getSubElements().iterator().next().getElementId() + .getValue()); } @Override @@ -87,87 +89,83 @@ public class DeploymentFlavorDaoZusammenImpl implements DeploymentFlavorDao { ZusammenElement deploymentFlavorElement = deploymentFlavorToZusammen(deploymentFlavor, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); + SessionContext context = createSessionContext(); zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), deploymentFlavorElement, String.format("Update deloymentFlavor with id %s", deploymentFlavor.getId())); } @Override public DeploymentFlavorEntity get(DeploymentFlavorEntity deploymentFlavor) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(deploymentFlavor.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()); Optional<Element> element = zusammenAdaptor.getElement(context, elementContext, deploymentFlavor.getId()); if (element.isPresent()) { + ElementToDeploymentFlavorConvertor convertor = new ElementToDeploymentFlavorConvertor(); + DeploymentFlavorEntity entity = convertor.convert(element.get()); deploymentFlavor.setCompositionData(new String(FileUtils.toByteArray(element.get() .getData()))); - return deploymentFlavor; + entity.setVspId(deploymentFlavor.getVspId()); + entity.setVersion(deploymentFlavor.getVersion()); + return entity; } return null; } @Override public void delete(DeploymentFlavorEntity deploymentFlavor) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(deploymentFlavor.getId())); - componentElement.setAction(Action.DELETE); + ZusammenElement componentElement = + buildElement(new Id(deploymentFlavor.getId()), Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(deploymentFlavor.getVspId()); + SessionContext context = createSessionContext(); zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), + new ElementContext(deploymentFlavor.getVspId(), deploymentFlavor.getVersion().getId()), componentElement, String.format("Delete deloymentFlavor with id %s", deploymentFlavor.getId())); } @Override public void deleteAll(String vspId, Version version) { - ZusammenElement deploymentFlavorsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.DeploymentFlavors, Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - deploymentFlavorsElement, "Delete all deploymentFlavors"); - } - - private ZusammenElement deploymentFlavorToZusammen(DeploymentFlavorEntity deploymentFlavor, - Action action) { - ZusammenElement deploymentFlavorElement = buildDeploymentFlavorElement - (deploymentFlavor, action); - - return deploymentFlavorElement; + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + Optional<Element> optionalElement = zusammenAdaptor.getElementByName(context, + elementContext, null, ElementType.DeploymentFlavors.name()); + + if (optionalElement.isPresent()) { + Element deploymentFlavorsElement = optionalElement.get(); + Collection<Element> deploymentFlavors = deploymentFlavorsElement.getSubElements(); + + deploymentFlavors.forEach(deplymentFlavor -> { + ZusammenElement deplymentFlavorZusammenElement = + buildElement(deplymentFlavor.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, + elementContext, deplymentFlavorZusammenElement, " Delete Deplyment Flavor with id " + + deplymentFlavor.getElementId()); + }); + } } /*private ZusammenElement deplymentFlavorQuestionnaireToZusammen(String questionnaireData, Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + VspbuildStructuralElement(ElementType.Questionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; }*/ - private ZusammenElement buildDeploymentFlavorElement(DeploymentFlavorEntity deploymentFlavor, - Action action) { - ZusammenElement deploymentFlavorElement = new ZusammenElement(); - deploymentFlavorElement.setAction(action); - if (deploymentFlavor.getId() != null) { - deploymentFlavorElement.setElementId(new Id(deploymentFlavor.getId())); - } + private ZusammenElement deploymentFlavorToZusammen(DeploymentFlavorEntity deploymentFlavor, + Action action) { + ZusammenElement deploymentFlavorElement = + buildElement(deploymentFlavor.getId() == null ? null : new Id(deploymentFlavor.getId()), + action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.DeploymentFlavor); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.DeploymentFlavor); info.addProperty(ElementPropertyName.compositionData.name(), deploymentFlavor .getCompositionData()); deploymentFlavorElement.setInfo(info); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ElementPropertyName.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ElementPropertyName.java deleted file mode 100644 index 9ca0bf721a..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ElementPropertyName.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; - -public enum ElementPropertyName { - type, - compositionData -} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ElementType.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ElementType.java deleted file mode 100644 index 9da0780f73..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ElementType.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; - -public enum ElementType { - Network, - Component, - Nic, - Process, - Mib, - LKG, - Compute, - DeploymentFlavor, - Image -} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ImageDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ImageDaoZusammenImpl.java index d913b18956..24ca072b23 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ImageDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ImageDaoZusammenImpl.java @@ -2,7 +2,6 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; -import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; @@ -11,11 +10,13 @@ import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToImageConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; import java.util.Collection; @@ -23,6 +24,10 @@ import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class ImageDaoZusammenImpl implements ImageDao { private ZusammenAdaptor zusammenAdaptor; @@ -37,83 +42,76 @@ public class ImageDaoZusammenImpl implements ImageDao { @Override public Collection<ImageEntity> list(ImageEntity image) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(image.getVersion())); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(image.getVspId(), image.getVersion().getId()); return listImages(context, elementContext, image); } private Collection<ImageEntity> listImages(SessionContext context, - ElementContext elementContext, ImageEntity image) { + ElementContext elementContext, ImageEntity image) { + ElementToImageConvertor convertor = new ElementToImageConvertor(); return zusammenAdaptor .listElementsByName(context, elementContext, new Id(image.getComponentId()), - StructureElement.Images.name()) - .stream().map(elementInfo -> mapElementInfoToImage( - image.getVspId(), image.getVersion(), image.getComponentId(), elementInfo)) + ElementType.Images.name()) + .stream().map(convertor::convert) + .map(imageEntity -> { + imageEntity.setComponentId(image.getComponentId()); + imageEntity.setVspId(image.getVspId()); + imageEntity.setVersion(image.getVersion()); + return imageEntity; + }) .collect(Collectors.toList()); } - private static ImageEntity mapElementInfoToImage(String vspId, Version version, - String componentId, ElementInfo elementInfo) { - ImageEntity imageEntity = - new ImageEntity(vspId, version, componentId, elementInfo.getId().getValue()); - imageEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return imageEntity; - } - @Override public void create(ImageEntity image) { ZusammenElement imageElement = imageToZusammen(image, Action.CREATE); ZusammenElement imagesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Images, null); + buildStructuralElement(ElementType.Images, Action.IGNORE); imagesElement.setSubElements(Collections.singletonList(imageElement)); - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(image.getComponentId())); - componentElement.setAction(Action.IGNORE); + ZusammenElement componentElement = buildElement(new Id(image.getComponentId()), Action.IGNORE); componentElement.setSubElements(Collections.singletonList(imagesElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(image.getVspId(), image.getVersion().getId()); - Optional<Element> savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create image"); - savedElement.ifPresent(element -> - image.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + image.setId(savedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public void update(ImageEntity image) { ZusammenElement imageElement = imageToZusammen(image, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(image.getVspId(), image.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, imageElement, String.format("Update image with id %s", image.getId())); } @Override public ImageEntity get(ImageEntity image) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(image.getVersion())); + SessionContext context = createSessionContext(); + + ElementContext elementContext = + new ElementContext(image.getVspId(), image.getVersion().getId()); Optional<Element> element = zusammenAdaptor.getElement(context, elementContext, image.getId()); if (element.isPresent()) { - image.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return image; + ElementToImageConvertor convertor = new ElementToImageConvertor(); + ImageEntity entity = convertor.convert(element.get()); + entity.setComponentId(image.getComponentId()); + entity.setVspId(image.getVspId()); + entity.setVersion(image.getVersion()); + return entity; } else { return null; } @@ -121,41 +119,41 @@ public class ImageDaoZusammenImpl implements ImageDao { @Override public void delete(ImageEntity image) { - ZusammenElement imageElement = new ZusammenElement(); - imageElement.setElementId(new Id(image.getId())); - imageElement.setAction(Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(image.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ZusammenElement imageElement = buildElement(new Id(image.getId()), Action.DELETE); + + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(image.getVspId(), image.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, imageElement, String.format("Delete image with id %s", image.getId())); } @Override public void deleteByVspId(String vspId, Version version) { - ZusammenElement imagesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Images, Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - zusammenAdaptor.saveElement(context, - new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)), - imagesElement, String.format("Delete all images with vsp id %s", vspId)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + Optional<Element> elementOptional = zusammenAdaptor.getElementByName(context, elementContext, + null, ElementType.Images.name()); + + if (elementOptional.isPresent()) { + Element ImagesElement = elementOptional.get(); + Collection<Element> Images = ImagesElement.getSubElements(); + Images.forEach(image -> { + ZusammenElement imageZusammenElement = buildElement(image.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, imageZusammenElement, "Delete image " + + "with id " + image.getElementId()); + }); + } } @Override public Collection<ImageEntity> listByVsp(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); Collection<ComponentEntity> components = ComponentDaoZusammenImpl - .listComponents(zusammenAdaptor, context, elementContext, vspId, version); + .listComponents(zusammenAdaptor, context, vspId, version); return components.stream() .map(component -> @@ -169,12 +167,9 @@ public class ImageDaoZusammenImpl implements ImageDao { @Override public ImageEntity getQuestionnaireData(String vspId, Version version, String componentId, - String imageId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + String imageId) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); return getQuestionnaire(context, elementContext, new ImageEntity(vspId, version, componentId, imageId)); @@ -184,7 +179,7 @@ public class ImageDaoZusammenImpl implements ImageDao { ImageEntity image) { Optional<Element> questionnaireElement = zusammenAdaptor .getElementByName(context, elementContext, new Id(image.getId()), - StructureElement.Questionnaire.name()); + ElementType.ImageQuestionnaire.name()); return questionnaireElement.map( element -> element.getData() == null ? null @@ -202,21 +197,16 @@ public class ImageDaoZusammenImpl implements ImageDao { ZusammenElement questionnaireElement = imageQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - ZusammenElement imageElement = new ZusammenElement(); - imageElement.setAction(Action.IGNORE); - imageElement.setElementId(new Id(imageId)); + ZusammenElement imageElement = buildElement(new Id(imageId), Action.IGNORE); imageElement.setSubElements(Collections.singletonList(questionnaireElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); zusammenAdaptor.saveElement(context, elementContext, imageElement, "Update image " + "questionnaire"); } - private ZusammenElement imageToZusammen(ImageEntity image, Action action) { ZusammenElement imageElement = buildImageElement(image, action); if (action == Action.CREATE) { @@ -227,21 +217,18 @@ public class ImageDaoZusammenImpl implements ImageDao { } private ZusammenElement imageQuestionnaireToZusammen(String questionnaireData, - Action action) { + Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + buildStructuralElement(ElementType.ImageQuestionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } private ZusammenElement buildImageElement(ImageEntity image, Action action) { - ZusammenElement imageElement = new ZusammenElement(); - imageElement.setAction(action); - if (image.getId() != null) { - imageElement.setElementId(new Id(image.getId())); - } + ZusammenElement imageElement = + buildElement(image.getId() == null ? null : new Id(image.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Image); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Image); info.addProperty(ElementPropertyName.compositionData.name(), image.getCompositionData()); imageElement.setInfo(info); imageElement.setData(new ByteArrayInputStream(image.getCompositionData().getBytes())); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NetworkDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NetworkDaoZusammenImpl.java index b22c9f32ed..bccea3a85c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NetworkDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NetworkDaoZusammenImpl.java @@ -8,19 +8,25 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; -import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNetworkConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class NetworkDaoZusammenImpl implements NetworkDao { private ZusammenAdaptor zusammenAdaptor; @@ -36,71 +42,70 @@ public class NetworkDaoZusammenImpl implements NetworkDao { @Override public Collection<NetworkEntity> list(NetworkEntity network) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(network.getVersion())); - - return zusammenAdaptor - .listElementsByName(context, elementContext, null, StructureElement.Networks.name()) - .stream().map(elementInfo -> - mapElementInfoToNetwork(network.getVspId(), network.getVersion(), elementInfo)) - .collect(Collectors.toList()); - } + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(network.getVspId(), network.getVersion().getId()); + + Optional<ElementInfo> vspModel = zusammenAdaptor + .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return new ArrayList<>(); + } - private NetworkEntity mapElementInfoToNetwork(String vspId, Version version, - ElementInfo elementInfo) { - NetworkEntity networkEntity = - new NetworkEntity(vspId, version, elementInfo.getId().getValue()); - networkEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return networkEntity; + ElementToNetworkConvertor convertor = new ElementToNetworkConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, vspModel.get().getId(), + ElementType.Networks.name()).stream() + .map(convertor::convert) + .map(entity -> { + entity.setVspId(network.getVspId()); + entity.setVersion(network.getVersion()); + return entity; + }) + .collect(Collectors.toList()); } @Override public void create(NetworkEntity network) { ZusammenElement networkElement = buildNetworkElement(network, Action.CREATE); - ZusammenElement networksElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Networks, null); + + ZusammenElement networksElement = buildStructuralElement(ElementType.Networks, Action.IGNORE); networksElement.setSubElements(Collections.singletonList(networkElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - Optional<Element> savedElement = - zusammenAdaptor.saveElement(context, elementContext, networksElement, "Create network"); - savedElement.ifPresent(element -> - network.setId(element.getSubElements().iterator().next().getElementId().getValue())); + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(networksElement); + + SessionContext context = createSessionContext(); + Element savedElement = zusammenAdaptor + .saveElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), + vspModel, "Create network"); + network.setId(savedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public void update(NetworkEntity network) { ZusammenElement networkElement = buildNetworkElement(network, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, networkElement, - String.format("Update network with id %s", network.getId())); + SessionContext context = createSessionContext(); + zusammenAdaptor + .saveElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), + networkElement, String.format("Update network with id %s", network.getId())); } @Override public NetworkEntity get(NetworkEntity network) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(network.getVersion())); + SessionContext context = createSessionContext(); Optional<Element> element = - zusammenAdaptor.getElement(context, elementContext, network.getId()); + zusammenAdaptor.getElement(context, + new ElementContext(network.getVspId(), network.getVersion().getId()), network.getId()); if (element.isPresent()) { - network.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return network; + ElementToNetworkConvertor convertor = new ElementToNetworkConvertor(); + NetworkEntity entity = convertor.convert(element.get()); + entity.setVspId(network.getVspId()); + entity.setVersion(network.getVersion()); + return entity; } else { return null; } @@ -108,39 +113,44 @@ public class NetworkDaoZusammenImpl implements NetworkDao { @Override public void delete(NetworkEntity network) { - ZusammenElement networkElement = new ZusammenElement(); - networkElement.setElementId(new Id(network.getId())); - networkElement.setAction(Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(network.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, - networkElement, String.format("Delete network with id %s", network.getId())); + ZusammenElement networkElement = buildElement(new Id(network.getId()), Action.DELETE); + + SessionContext context = createSessionContext(); + zusammenAdaptor + .saveElement(context, new ElementContext(network.getVspId(), network.getVersion().getId()), + networkElement, String.format("Delete network with id %s", network.getId())); } @Override public void deleteAll(String vspId, Version version) { - ZusammenElement networksElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Networks, Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, networksElement, "Delete all networks"); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + Collection<ElementInfo> vspModelSubs = zusammenAdaptor + .listElementsByName(context, elementContext, null, ElementType.VspModel.name()); + + Optional<ElementInfo> networksElement = vspModelSubs.stream() + .filter(elementInfo -> elementInfo.getInfo() != null + && ElementType.Networks.name().equals(elementInfo.getInfo().getName())) + .findFirst(); + if (!networksElement.isPresent()) { + return; + } + + ZusammenElement networks = buildElement(networksElement.get().getId(), Action.IGNORE); + networks.setSubElements(networksElement.get().getSubElements().stream() + .map(network -> buildElement(network.getId(), Action.DELETE)) + .collect(Collectors.toList())); + + zusammenAdaptor.saveElement(context, elementContext, networks, "Delete all networks"); } private ZusammenElement buildNetworkElement(NetworkEntity network, Action action) { - ZusammenElement networkElement = new ZusammenElement(); - networkElement.setAction(action); - if (network.getId() != null) { - networkElement.setElementId(new Id(network.getId())); - } + ZusammenElement networkElement = + buildElement(network.getId() == null ? null : new Id(network.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Network); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Network); info.addProperty(ElementPropertyName.compositionData.name(), network.getCompositionData()); networkElement.setInfo(info); networkElement.setData(new ByteArrayInputStream(network.getCompositionData().getBytes())); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NicDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NicDaoZusammenImpl.java index e597068d87..268e2546ed 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NicDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/NicDaoZusammenImpl.java @@ -1,20 +1,21 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; -import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; -import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNicConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToNicQuestionnaireConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; import java.util.Collection; @@ -22,6 +23,10 @@ import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class NicDaoZusammenImpl implements NicDao { private ZusammenAdaptor zusammenAdaptor; @@ -37,82 +42,70 @@ public class NicDaoZusammenImpl implements NicDao { @Override public Collection<NicEntity> list(NicEntity nic) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(nic.getVersion())); - - return listNics(context, elementContext, nic); + SessionContext context = createSessionContext(); + return listNics(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), nic); } private Collection<NicEntity> listNics(SessionContext context, ElementContext elementContext, NicEntity nic) { - return zusammenAdaptor - .listElementsByName(context, elementContext, new Id(nic.getComponentId()), - StructureElement.Nics.name()) - .stream().map(elementInfo -> mapElementInfoToNic( - nic.getVspId(), nic.getVersion(), nic.getComponentId(), elementInfo)) + ElementToNicConvertor convertor = new ElementToNicConvertor(); + return zusammenAdaptor.listElementsByName(context, elementContext, new Id(nic.getComponentId()), + ElementType.Nics.name()) + .stream().map(convertor::convert) + .map(nicEntity -> { + nicEntity.setComponentId(nicEntity.getComponentId()); + nicEntity.setVspId(nic.getVspId()); + nicEntity.setVersion(nic.getVersion()); + return nicEntity; + }) .collect(Collectors.toList()); } - private NicEntity mapElementInfoToNic(String vspId, Version version, - String componentId, ElementInfo elementInfo) { - NicEntity nicEntity = - new NicEntity(vspId, version, componentId, elementInfo.getId().getValue()); - nicEntity.setCompositionData( - elementInfo.getInfo().getProperty(ElementPropertyName.compositionData.name())); - return nicEntity; - } @Override public void create(NicEntity nic) { ZusammenElement nicElement = nicToZusammen(nic, Action.CREATE); - ZusammenElement nicsElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Nics, null); + ZusammenElement nicsElement = buildStructuralElement(ElementType.Nics, Action.IGNORE); nicsElement.setSubElements(Collections.singletonList(nicElement)); - ZusammenElement componentElement = - buildZusammenElement(new Id(nic.getComponentId()), Action.IGNORE); + ZusammenElement componentElement = buildElement(new Id(nic.getComponentId()), Action.IGNORE); componentElement.setSubElements(Collections.singletonList(nicsElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(nic.getVspId(), nic.getVersion().getId()); - Optional<Element> savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, componentElement, "Create nic"); - savedElement.ifPresent(element -> - nic.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue())); + nic.setId(savedElement.getSubElements().iterator().next() + .getSubElements().iterator().next().getElementId().getValue()); } @Override public void update(NicEntity nic) { ZusammenElement nicElement = nicToZusammen(nic, Action.UPDATE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, nicElement, - String.format("Update nic with id %s", nic.getId())); + SessionContext context = createSessionContext(); + zusammenAdaptor + .saveElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), + nicElement, String.format("Update nic with id %s", nic.getId())); } @Override public NicEntity get(NicEntity nic) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(nic.getVersion())); - Optional<Element> element = zusammenAdaptor.getElement(context, elementContext, nic.getId()); + SessionContext context = createSessionContext(); + ElementToNicConvertor convertor = new ElementToNicConvertor(); + Optional<Element> element = zusammenAdaptor + .getElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), + nic.getId()); if (element.isPresent()) { - nic.setCompositionData(new String(FileUtils.toByteArray(element.get().getData()))); - return nic; + NicEntity entity = convertor.convert(element.get()); + entity.setVspId(nic.getVspId()); + entity.setVersion(nic.getVersion()); + entity.setComponentId(nic.getComponentId()); + + return entity; } else { return null; } @@ -120,26 +113,20 @@ public class NicDaoZusammenImpl implements NicDao { @Override public void delete(NicEntity nic) { - ZusammenElement nicElement = buildZusammenElement(new Id(nic.getId()), Action.DELETE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(nic.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, nicElement, - String.format("Delete nic with id %s", nic.getId())); + ZusammenElement nicElement = buildElement(new Id(nic.getId()), Action.DELETE); + + SessionContext context = createSessionContext(); + zusammenAdaptor + .saveElement(context, new ElementContext(nic.getVspId(), nic.getVersion().getId()), + nicElement, String.format("Delete nic with id %s", nic.getId())); } @Override public NicEntity getQuestionnaireData(String vspId, Version version, String componentId, String nicId) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); - return getQuestionnaire(context, elementContext, + return getQuestionnaire(context, new ElementContext(vspId, version.getId()), new NicEntity(vspId, version, componentId, nicId)); } @@ -147,14 +134,13 @@ public class NicDaoZusammenImpl implements NicDao { NicEntity nic) { Optional<Element> questionnaireElement = zusammenAdaptor .getElementByName(context, elementContext, new Id(nic.getId()), - StructureElement.Questionnaire.name()); - return questionnaireElement.map( - element -> element.getData() == null - ? null - : new String(FileUtils.toByteArray(element.getData()))) - .map(questionnaireData -> { - nic.setQuestionnaireData(questionnaireData); - return nic; + ElementType.NicQuestionnaire.name()); + return questionnaireElement.map(new ElementToNicQuestionnaireConvertor()::convert) + .map(entity -> { + entity.setVspId(nic.getVspId()); + entity.setVersion(nic.getVersion()); + entity.setComponentId(nic.getComponentId()); + return entity; }) .orElse(null); } @@ -165,29 +151,22 @@ public class NicDaoZusammenImpl implements NicDao { ZusammenElement questionnaireElement = nicQuestionnaireToZusammen(questionnaireData, Action.UPDATE); - ZusammenElement nicElement = new ZusammenElement(); - nicElement.setAction(Action.IGNORE); - nicElement.setElementId(new Id(nicId)); + ZusammenElement nicElement = buildElement(new Id(nicId), Action.IGNORE); nicElement.setSubElements(Collections.singletonList(questionnaireElement)); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, nicElement, "Update nic questionnaire"); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), nicElement, + "Update nic questionnaire"); } @Override public Collection<NicEntity> listByVsp(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); Collection<ComponentEntity> components = ComponentDaoZusammenImpl - .listComponents(zusammenAdaptor, context, elementContext, vspId, version); + .listComponents(zusammenAdaptor, context, vspId, version); + ElementContext elementContext = new ElementContext(vspId, version.getId()); return components.stream() .map(component -> listNics(context, elementContext, @@ -200,16 +179,22 @@ public class NicDaoZusammenImpl implements NicDao { @Override public void deleteByComponentId(String vspId, Version version, String componentId) { - ZusammenElement componentElement = buildZusammenElement(new Id(componentId), Action.IGNORE); - componentElement.setSubElements(Collections.singletonList( - VspZusammenUtil.buildStructuralElement(StructureElement.Nics, Action.DELETE))); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, componentElement, - String.format("Delete all nics of component %s", componentId)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + Optional<Element> optionalElement = zusammenAdaptor.getElementByName(context, + elementContext, new Id(componentId), ElementType.Nics.name()); + + if (optionalElement.isPresent()) { + Element nicsElement = optionalElement.get(); + Collection<Element> nics = nicsElement.getSubElements(); + + nics.forEach(nic -> { + ZusammenElement nicZusammenElement = buildElement(nic.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, nicZusammenElement, + "Delete nic with id " + nic.getElementId()); + }); + } } @Override @@ -229,26 +214,16 @@ public class NicDaoZusammenImpl implements NicDao { private ZusammenElement nicQuestionnaireToZusammen(String questionnaireData, Action action) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, action); + buildStructuralElement(ElementType.NicQuestionnaire, action); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } - private ZusammenElement buildZusammenElement(Id elementId, Action action) { - ZusammenElement element = new ZusammenElement(); - element.setElementId(elementId); - element.setAction(action); - return element; - } - private ZusammenElement buildNicElement(NicEntity nic, Action action) { - ZusammenElement nicElement = new ZusammenElement(); - nicElement.setAction(action); - if (nic.getId() != null) { - nicElement.setElementId(new Id(nic.getId())); - } + ZusammenElement nicElement = + buildElement(nic.getId() == null ? null : new Id(nic.getId()), action); Info info = new Info(); - info.addProperty(ElementPropertyName.type.name(), ElementType.Nic); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Nic); info.addProperty(ElementPropertyName.compositionData.name(), nic.getCompositionData()); nicElement.setInfo(info); nicElement.setData(new ByteArrayInputStream(nic.getCompositionData().getBytes())); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateCandidateDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateCandidateDaoZusammenImpl.java index ea51b770bf..5d1ef125fd 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateCandidateDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateCandidateDaoZusammenImpl.java @@ -1,15 +1,16 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; -import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.utils.fileutils.FileUtils; +import org.apache.commons.io.IOUtils; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateCandidateDao; @@ -18,11 +19,18 @@ import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStru import org.openecomp.sdc.versioning.dao.types.Version; import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; import java.nio.ByteBuffer; +import java.util.Arrays; import java.util.Optional; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class OrchestrationTemplateCandidateDaoZusammenImpl implements OrchestrationTemplateCandidateDao { + private static final Logger logger = LoggerFactory.getLogger(OrchestrationTemplateCandidateDaoZusammenImpl.class); @@ -39,95 +47,163 @@ public class OrchestrationTemplateCandidateDaoZusammenImpl @Override public OrchestrationTemplateCandidateData get(String vspId, Version version) { - logger.info("Getting orchestration template for vsp id -> " + vspId); + logger.info("Getting orchestration template for VendorSoftwareProduct id -> " + vspId); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, versionId, - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); Optional<Element> candidateElement = zusammenAdaptor.getElementByName(context, elementContext, null, - StructureElement.OrchestrationTemplateCandidate.name()); + ElementType.OrchestrationTemplateCandidate.name()); if (candidateElement.isPresent()) { + if (hasEmptyData(candidateElement.get().getData())) { + return null; + } OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); candidateData.setFilesDataStructure( new String(FileUtils.toByteArray(candidateElement.get().getData()))); - zusammenAdaptor + Optional<Element> candidateContentElement = zusammenAdaptor .getElementByName(context, elementContext, candidateElement.get().getElementId(), - StructureElement.OrchestrationTemplateCandidateContent.name()) - .ifPresent(candidateContentElement -> candidateData.setContentData( - ByteBuffer.wrap(FileUtils.toByteArray(candidateContentElement.getData())))); - logger.info("Finished getting orchestration template for vsp id -> " + vspId); + ElementType.OrchestrationTemplateCandidateContent.name()); + + if (candidateContentElement.isPresent()) { + candidateData.setContentData( + ByteBuffer.wrap(FileUtils.toByteArray(candidateContentElement.get().getData()))); + candidateData.setFileSuffix(candidateContentElement.get().getInfo() + .getProperty(InfoPropertyName.fileSuffix.name())); + candidateData.setFileName(candidateContentElement.get().getInfo() + .getProperty(InfoPropertyName.fileName.name())); + } + logger + .info("Finished getting orchestration template for VendorSoftwareProduct id -> " + vspId); return candidateData; } - logger.info(String.format("Orchestration template for vsp id %s does not exist", vspId)); + logger.info(String + .format("Orchestration template for VendorSoftwareProduct id %s does not exist", vspId)); return null; } @Override - public void update(String vspId, OrchestrationTemplateCandidateData candidateData) { - logger.info("Uploading candidate data entity for vsp id -> " + vspId); + public OrchestrationTemplateCandidateData getInfo(String vspId, Version version) { + logger.info("Getting orchestration template info for VendorSoftwareProduct id -> " + vspId); + + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, versionId); + Optional<ElementInfo> candidateElement = + zusammenAdaptor.getElementInfoByName(context, elementContext, null, + ElementType.OrchestrationTemplateCandidate.name()); + if (candidateElement.isPresent()) { + OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); - ZusammenElement candidateElement = VspZusammenUtil - .buildStructuralElement(StructureElement.OrchestrationTemplateCandidate, Action.UPDATE); + Optional<Element> candidateContentElement = zusammenAdaptor + .getElementByName(context, elementContext, candidateElement.get().getId(), + ElementType.OrchestrationTemplateCandidateContent.name()); + + if (candidateContentElement.isPresent()) { + candidateData.setFileSuffix(candidateContentElement.get().getInfo() + .getProperty(InfoPropertyName.fileSuffix.name())); + candidateData.setFileName(candidateContentElement.get().getInfo() + .getProperty(InfoPropertyName.fileName.name())); + } + logger.info( + "Finished getting orchestration template info for VendorSoftwareProduct id -> " + vspId); + return candidateData; + } + logger.info(String + .format("Orchestration template info for VendorSoftwareProduct id %s does not exist", + vspId)); + return null; + } + + @Override + public void update(String vspId, Version version, + OrchestrationTemplateCandidateData candidateData) { + logger.info("Uploading candidate data entity for VendorSoftwareProduct id -> " + vspId); + + ZusammenElement candidateElement = + buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.UPDATE); candidateElement .setData(new ByteArrayInputStream(candidateData.getFilesDataStructure().getBytes())); - ZusammenElement candidateContentElement = VspZusammenUtil - .buildStructuralElement(StructureElement.OrchestrationTemplateCandidateContent, Action.UPDATE); + + ZusammenElement candidateContentElement = + buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.UPDATE); candidateContentElement .setData(new ByteArrayInputStream(candidateData.getContentData().array())); + candidateContentElement.getInfo() + .addProperty(InfoPropertyName.fileSuffix.name(), candidateData.getFileSuffix()); + candidateContentElement.getInfo() + .addProperty(InfoPropertyName.fileName.name(), candidateData.getFileName()); candidateElement.addSubElement(candidateContentElement); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); zusammenAdaptor.saveElement(context, elementContext, candidateElement, "Update Orchestration Template Candidate"); - logger.info("Finished uploading candidate data entity for vsp id -> " + vspId); + logger + .info("Finished uploading candidate data entity for VendorSoftwareProduct id -> " + vspId); } + @Override public void updateStructure(String vspId, Version version, FilesDataStructure fileDataStructure) { logger.info("Updating orchestration template for VSP id -> " + vspId); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, versionId); - - ZusammenElement candidateElement = VspZusammenUtil - .buildStructuralElement(StructureElement.OrchestrationTemplateCandidate, Action.UPDATE); + ZusammenElement candidateElement = + buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.UPDATE); candidateElement .setData(new ByteArrayInputStream(JsonUtil.object2Json(fileDataStructure).getBytes())); + + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); zusammenAdaptor.saveElement(context, elementContext, candidateElement, "Update Orchestration Template Candidate structure"); - logger.info("Finished uploading candidate data entity for vsp id -> " + vspId); + logger + .info("Finished uploading candidate data entity for VendorSoftwareProduct id -> " + vspId); } @Override public Optional<String> getStructure(String vspId, Version version) { - logger.info("Getting orchestration template structure for vsp id -> " + vspId); + logger + .info("Getting orchestration template structure for VendorSoftwareProduct id -> " + vspId); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, versionId, - VspZusammenUtil.getVersionTag(version)); + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); - logger.info("Finished getting orchestration template structure for vsp id -> " + vspId); + logger.info( + "Finished getting orchestration template structure for VendorSoftwareProduct id -> " + + vspId); Optional<Element> element = zusammenAdaptor.getElementByName(context, elementContext, null, - StructureElement.OrchestrationTemplateCandidate.name()); + ElementType.OrchestrationTemplateCandidate.name()); if (element.isPresent()) { + if (hasEmptyData(element.get().getData())) { + return Optional.empty(); + } return Optional.of(new String(FileUtils.toByteArray(element.get().getData()))); } else { return Optional.empty(); } + } + + private boolean hasEmptyData(InputStream elementData) { + String emptyData = "{}"; + byte[] byteElementData; + try { + byteElementData = IOUtils.toByteArray(elementData); + } catch (IOException ex) { + ex.printStackTrace(); + return false; + } + if (Arrays.equals(emptyData.getBytes(), byteElementData)) { + return true; + } + return false; + } + public enum InfoPropertyName { + fileSuffix, + fileName } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java index 2b6d52a38a..d02e8541f4 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/OrchestrationTemplateDaoZusammenImpl.java @@ -3,22 +3,27 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; -import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.utils.fileutils.FileUtils; +import org.apache.commons.io.IOUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadData; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.UploadDataEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.types.Version; import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; import java.nio.ByteBuffer; +import java.util.Arrays; import java.util.Optional; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class OrchestrationTemplateDaoZusammenImpl implements OrchestrationTemplateDao { private ZusammenAdaptor zusammenAdaptor; @@ -33,79 +38,128 @@ public class OrchestrationTemplateDaoZusammenImpl implements OrchestrationTempla } @Override - public String getValidationData(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + public OrchestrationTemplateEntity getInfo(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + Optional<ElementInfo> vspModel = zusammenAdaptor + .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return null; + } Optional<ElementInfo> elementInfo = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, - StructureElement.OrchestrationTemplate.name()); - if (elementInfo.isPresent()) { - Optional<Element> element = - zusammenAdaptor.getElementByName(context, elementContext, elementInfo.get().getId(), - StructureElement.OrchestrationTemplateValidationData.name()); - if (element.isPresent()) { - return new String(FileUtils.toByteArray(element.get().getData())); - } + .getElementInfoByName(context, elementContext, vspModel.get().getId(), + ElementType.OrchestrationTemplate.name()); + if (!elementInfo.isPresent()) { + return null; } - return null; + Optional<Element> element = + zusammenAdaptor.getElementByName(context, elementContext, elementInfo.get().getId(), + ElementType.OrchestrationTemplateValidationData.name()); + + OrchestrationTemplateEntity orchestrationTemplate = new OrchestrationTemplateEntity(); + if (!element.isPresent()) { + return orchestrationTemplate; + } + orchestrationTemplate + .setFileSuffix(element.get().getInfo().getProperty(InfoPropertyName.fileSuffix.name())); + orchestrationTemplate + .setFileName(element.get().getInfo().getProperty(InfoPropertyName.fileName.name())); + if (!hasEmptyData(element.get().getData())) { + orchestrationTemplate + .setValidationData(new String(FileUtils.toByteArray(element.get().getData()))); + } + return orchestrationTemplate; } @Override - public UploadDataEntity getOrchestrationTemplate(String vspId, Version version) { + public OrchestrationTemplateEntity get(String vspId, Version version) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); - UploadDataEntity uploadData = new UploadDataEntity(); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(version)); + OrchestrationTemplateEntity orchestrationTemplate = new OrchestrationTemplateEntity(); - Optional<ElementInfo> elementInfo = zusammenAdaptor - .getElementInfoByName(context, elementContext, null, - StructureElement.OrchestrationTemplate.name()); - if (elementInfo.isPresent()) { - Optional<Element> element = - zusammenAdaptor.getElementByName(context, elementContext, elementInfo.get().getId(), - StructureElement.OrchestrationTemplateValidationData.name()); - element.ifPresent(element1 -> uploadData - .setValidationData(new String(FileUtils.toByteArray(element1.getData())))); - element = - zusammenAdaptor.getElementByName(context, elementContext, elementInfo.get().getId(), - StructureElement.OrchestrationTemplateContent.name()); - element.ifPresent(element1 -> uploadData - .setContentData(ByteBuffer.wrap(FileUtils.toByteArray(element1.getData())))); + Optional<ElementInfo> vspModel = zusammenAdaptor + .getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()); + if (!vspModel.isPresent()) { + return orchestrationTemplate; + } + + Optional<Element> orchestrationTemplateElement = zusammenAdaptor + .getElementByName(context, elementContext, vspModel.get().getId(), + ElementType.OrchestrationTemplate.name()); + if (!orchestrationTemplateElement.isPresent()) { + return orchestrationTemplate; + } + + if (!hasEmptyData(orchestrationTemplateElement.get().getData())) { + orchestrationTemplate.setContentData( + ByteBuffer.wrap(FileUtils.toByteArray(orchestrationTemplateElement.get().getData()))); } - return uploadData; + + Optional<Element> validationDataElement = + zusammenAdaptor.getElementByName(context, elementContext, + orchestrationTemplateElement.get().getElementId(), + ElementType.OrchestrationTemplateValidationData.name()); + if (validationDataElement.isPresent()) { + orchestrationTemplate.setFileSuffix(validationDataElement.get().getInfo() + .getProperty(InfoPropertyName.fileSuffix.name())); + orchestrationTemplate.setFileName(validationDataElement.get().getInfo() + .getProperty(InfoPropertyName.fileName.name())); + if (!hasEmptyData(validationDataElement.get().getData())) { + orchestrationTemplate.setValidationData( + new String(FileUtils.toByteArray(validationDataElement.get().getData()))); + } + } + return orchestrationTemplate; } @Override - public void updateOrchestrationTemplateData(String vspId, UploadData uploadData) { + public void update(String vspId, Version version, + OrchestrationTemplateEntity orchestrationTemplate) { + SessionContext context = createSessionContext(); + ElementContext elementContext = new ElementContext(vspId, version.getId()); + + ZusammenElement validationData = + buildStructuralElement(ElementType.OrchestrationTemplateValidationData, Action.UPDATE); + validationData + .setData(new ByteArrayInputStream(orchestrationTemplate.getValidationData().getBytes())); + validationData.getInfo() + .addProperty(InfoPropertyName.fileSuffix.name(), orchestrationTemplate.getFileSuffix()); + validationData.getInfo() + .addProperty(InfoPropertyName.fileName.name(), orchestrationTemplate.getFileName()); + ZusammenElement orchestrationTemplateElement = - VspZusammenUtil.buildStructuralElement(StructureElement.OrchestrationTemplate, null); - ZusammenElement orchestrationTemplateValidationDataElement = - VspZusammenUtil - .buildStructuralElement(StructureElement.OrchestrationTemplateValidationData, Action.UPDATE); - orchestrationTemplateValidationDataElement.setData(new ByteArrayInputStream(uploadData - .getValidationData().getBytes())); - ZusammenElement orchestrationTemplateContent = - VspZusammenUtil.buildStructuralElement(StructureElement.OrchestrationTemplateContent, Action.UPDATE); - orchestrationTemplateContent - .setData(new ByteArrayInputStream(uploadData.getContentData().array())); - orchestrationTemplateElement.addSubElement(orchestrationTemplateValidationDataElement); - orchestrationTemplateElement.addSubElement(orchestrationTemplateContent); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - - zusammenAdaptor.saveElement(context, elementContext, orchestrationTemplateElement, "Update " + - "Orchestration Template"); + buildStructuralElement(ElementType.OrchestrationTemplate, Action.UPDATE); + orchestrationTemplateElement + .setData(new ByteArrayInputStream(orchestrationTemplate.getContentData().array())); + orchestrationTemplateElement.addSubElement(validationData); + + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.IGNORE); + vspModel.addSubElement(orchestrationTemplateElement); + + zusammenAdaptor.saveElement(context, elementContext, vspModel, "Update Orchestration Template"); } + private boolean hasEmptyData(InputStream elementData) { + String emptyData = "{}"; + byte[] byteElementData; + try { + byteElementData = IOUtils.toByteArray(elementData); + } catch (IOException ex) { + ex.printStackTrace(); + return false; + } + if (Arrays.equals(emptyData.getBytes(), byteElementData)) { + return true; + } + return false; + } + + private enum InfoPropertyName { + fileSuffix, + fileName + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java index b0cff4371e..d74900bdf6 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/ProcessDaoZusammenImpl.java @@ -8,34 +8,35 @@ import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; -import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.ProcessDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessType; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.types.ElementPropertyName; import java.io.ByteArrayInputStream; -import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.ARTIFACT_NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.DESCRIPTION; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.NAME; +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.PROCESS_TYPE; + /** * @author Avrahamg. * @since March 23, 2017 */ public class ProcessDaoZusammenImpl implements ProcessDao { - private static final String NAME = "name"; - private static final String ELEMENT_TYPE = "type"; - private static final String ARTIFACT_NAME = "artifactName"; - private static final String DESCRIPTION = "description"; - private static final String PROCESS_TYPE = "processType"; - private ZusammenAdaptor zusammenAdaptor; public ProcessDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { @@ -52,85 +53,59 @@ public class ProcessDaoZusammenImpl implements ProcessDao { ZusammenElement processElement = buildProcessElement(processEntity, Action.CREATE); ZusammenElement processesElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Processes, null); + buildStructuralElement(ElementType.Processes, Action.IGNORE); ZusammenElement aggregatedElement = VspZusammenUtil.aggregateElements(processesElement, processElement); ZusammenElement componentElement; if (processEntity.getComponentId() != null) { - componentElement = createParentElement(processEntity); + componentElement = buildElement(new Id(processEntity.getComponentId()), Action.IGNORE); aggregatedElement = VspZusammenUtil.aggregateElements(componentElement, aggregatedElement); } - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(processEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); - Optional<Element> savedElement = + Element savedElement = zusammenAdaptor.saveElement(context, elementContext, aggregatedElement, "Create process"); - savedElement.ifPresent(element -> { - if (processEntity.getComponentId() == null) { - processEntity.setId(element.getSubElements().iterator().next() - .getElementId().getValue()); - } else { - processEntity.setId(element.getSubElements().iterator().next() - .getSubElements().iterator().next().getElementId().getValue()); - } - }); + processEntity + .setId(processEntity.getComponentId() == null + ? savedElement.getSubElements().iterator().next().getElementId().getValue() + : savedElement.getSubElements().iterator().next().getSubElements() + .iterator().next().getElementId().getValue()); } @Override - public ProcessEntity get(ProcessEntity process) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(process.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(process.getVersion())); - - Optional<Element> elementOptional = - zusammenAdaptor.getElement(context, elementContext, process.getId()); - - if (elementOptional.isPresent()) { - Element element = elementOptional.get(); - process.setName(element.getInfo().getProperty(NAME)); - process.setArtifactName(element.getInfo().getProperty(ARTIFACT_NAME)); - process.setDescription(element.getInfo().getProperty(DESCRIPTION)); - process.setType(element.getInfo().getProperty - (PROCESS_TYPE) != null ? ProcessType.valueOf(element.getInfo().getProperty - (PROCESS_TYPE)) : null); - - process.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); - return process; - } else { - return null; - } + public ProcessEntity get(ProcessEntity processEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + + return zusammenAdaptor.getElementInfo(context, elementContext, new Id(processEntity.getId())) + .map(elementInfo -> convertToProcessEntity(elementInfo, new ElementToProcessConvertor(), + processEntity)) + .orElse(null); } @Override public void update(ProcessEntity processEntity) { - ZusammenElement processElement = buildProcessElement(processEntity, Action.UPDATE); - - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(processEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + ProcessEntity retrieved = getArtifact(processEntity); + if (retrieved != null && retrieved.getArtifact() != null) { + processEntity.setArtifactName(retrieved.getArtifactName()); + processEntity.setArtifact(retrieved.getArtifact()); + } - Optional<Element> element = - zusammenAdaptor.saveElement(context, elementContext, processElement, "Create process"); - System.out.println(element.get().getElementId()); + update(processEntity, "Update process"); } @Override public void delete(ProcessEntity processEntity) { - ZusammenElement processElement = new ZusammenElement(); - processElement.setElementId(new Id(processEntity.getId())); - processElement.setAction(Action.DELETE); + ZusammenElement processElement = buildElement(new Id(processEntity.getId()), Action.DELETE); - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(processEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); zusammenAdaptor.saveElement(context, elementContext, processElement, String.format("Delete process with id %s", processEntity.getId())); @@ -138,69 +113,145 @@ public class ProcessDaoZusammenImpl implements ProcessDao { @Override public void deleteAll(ProcessEntity processEntity) { - ZusammenElement aggregatedElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Processes, Action.DELETE); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + + Optional<Element> optionalElement = zusammenAdaptor.getElementByName(context, + elementContext, new Id(processEntity.getComponentId()), ElementType.Processes.name()); + + /* ZusammenElement aggregatedElement = + buildStructuralElement(ElementType.Processes, Action.DELETE); if (processEntity.getComponentId() != null) { ZusammenElement componentElement = createParentElement(processEntity); - aggregatedElement = VspZusammenUtil.aggregateElements(componentElement, + aggregatedElement = VspaggregateElements(componentElement, aggregatedElement); } - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(processEntity.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor)); - zusammenAdaptor.saveElement(context, elementContext, aggregatedElement, "Delete All processes"); + zusammenAdaptor.saveElement(context, elementContext, aggregatedElement, "Delete All + processes");*/ + + if (optionalElement.isPresent()) { + Element processesElement = optionalElement.get(); + Collection<Element> processes = processesElement.getSubElements(); + + processes.forEach(process -> { + ZusammenElement processZusammenElement = + buildElement(process.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, processZusammenElement, + "Delete Process with id " + process.getElementId()); + }); + } } @Override public void deleteVspAll(String vspId, Version version) { - ProcessEntity processEntity = new ProcessEntity(); + /* ProcessEntity processEntity = new ProcessEntity(); processEntity.setVersion(version); processEntity.setVspId(vspId); - deleteAll(processEntity); + deleteAll(processEntity); */ + + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(vspId, version.getId()); + + Optional<Element> optionalElement = zusammenAdaptor.getElementByName(context, + elementContext, null, ElementType.Processes.name()); + + if (optionalElement.isPresent()) { + Element processesElement = optionalElement.get(); + Collection<Element> processes = processesElement.getSubElements(); + + processes.forEach(process -> { + ZusammenElement processZusammenElement = + buildElement(process.getElementId(), Action.DELETE); + zusammenAdaptor.saveElement(context, elementContext, processZusammenElement, + "Delete Process with id " + process.getElementId()); + }); + } } @Override - public Collection<ProcessEntity> list(ProcessEntity process) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(process.getVspId()); - ElementContext elementContext = new ElementContext(itemId, - VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor), - VspZusammenUtil.getVersionTag(process.getVersion())); + public ProcessEntity getArtifact(ProcessEntity processEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + + return zusammenAdaptor.getElement(context, elementContext, processEntity.getId()) + .map(element -> { + ProcessEntity process = new ElementToProcessConvertor().convert(element); + process.setVspId(processEntity.getVspId()); + process.setVersion(processEntity.getVersion()); + process.setComponentId(processEntity.getComponentId()); + return process; + }) + .orElse(null); + } + + @Override + public void uploadArtifact(ProcessEntity processEntity) { + ProcessEntity retrieved = get(processEntity); + if (retrieved != null) { + retrieved.setArtifactName(processEntity.getArtifactName()); + retrieved.setArtifact(processEntity.getArtifact()); + + update(retrieved, "Upload process artifact"); + } + } + + @Override + public void deleteArtifact(ProcessEntity processEntity) { + ProcessEntity retrieved = get(processEntity); + if (retrieved != null) { + retrieved.setArtifactName(null); + retrieved.setArtifact(null); + + update(retrieved, "Delete process artifact"); + } + } + + @Override + public Collection<ProcessEntity> list(ProcessEntity processEntity) { + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); Optional<ElementInfo> processesOptional = zusammenAdaptor.getElementInfoByName(context, elementContext, - extractParentElementId(process), StructureElement.Processes.name()); + extractParentElementId(processEntity), ElementType.Processes.name()); if (!processesOptional.isPresent()) { return new ArrayList<>(); } + ElementToProcessConvertor convertor = new ElementToProcessConvertor(); return zusammenAdaptor.listElements(context, elementContext, processesOptional.get().getId()) .stream() - .map(elementInfo -> mapElementInfoToProcess( - process.getVspId(), process.getVersion(), process.getComponentId(), - elementInfo)) + .map(elementInfo -> convertToProcessEntity(elementInfo, convertor, processEntity)) .collect(Collectors.toList()); } - private Id extractParentElementId(ProcessEntity processEntity) { - return processEntity.getComponentId() == null ? null : new Id(processEntity.getComponentId()); + private ProcessEntity convertToProcessEntity(ElementInfo elementInfo, + ElementToProcessConvertor convertor, + ProcessEntity inputProcess) { + ProcessEntity process = convertor.convert(elementInfo); + process.setVspId(inputProcess.getVspId()); + process.setVersion(inputProcess.getVersion()); + process.setComponentId(inputProcess.getComponentId()); + return process; } - private ProcessEntity mapElementInfoToProcess(String vspId, Version version, - String componentId, - ElementInfo elementInfo) { - ProcessEntity processEntity = new ProcessEntity(vspId, version, componentId, elementInfo - .getId().getValue()); - processEntity.setName((String) elementInfo.getInfo().getProperties().get(NAME)); - processEntity - .setArtifactName((String) elementInfo.getInfo().getProperties().get(ARTIFACT_NAME)); - processEntity.setDescription((String) elementInfo.getInfo().getProperties().get(DESCRIPTION)); - processEntity.setType( elementInfo.getInfo().getProperties().get(PROCESS_TYPE) != null ? - ProcessType.valueOf((String) elementInfo.getInfo().getProperties().get(PROCESS_TYPE)) : - null); - return processEntity; + private void update(ProcessEntity processEntity, String message) { + ZusammenElement processElement = buildProcessElement(processEntity, Action.UPDATE); + + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(processEntity.getVspId(), processEntity.getVersion().getId()); + + zusammenAdaptor.saveElement(context, elementContext, processElement, message); + } + + private Id extractParentElementId(ProcessEntity processEntity) { + return processEntity.getComponentId() == null ? null : new Id(processEntity.getComponentId()); } private ZusammenElement buildProcessElement(ProcessEntity process, Action action) { @@ -208,14 +259,12 @@ public class ProcessDaoZusammenImpl implements ProcessDao { Info info = new Info(); info.setName(process.getName()); info.addProperty(NAME, process.getName()); - info.addProperty(ELEMENT_TYPE, ElementType.Process); + info.addProperty(ElementPropertyName.elementType.name(), ElementType.Process); info.addProperty(ARTIFACT_NAME, process.getArtifactName()); info.addProperty(DESCRIPTION, process.getDescription()); info.addProperty(PROCESS_TYPE, process.getType() != null ? process.getType().name() : null); - ZusammenElement processElement = new ZusammenElement(); - processElement.setElementId(new Id(process.getId())); - processElement.setAction(action); + ZusammenElement processElement = buildElement(new Id(process.getId()), action); processElement.setInfo(info); if (Objects.nonNull(process.getArtifact())) { processElement.setData(new ByteArrayInputStream(process.getArtifact().array())); @@ -223,10 +272,4 @@ public class ProcessDaoZusammenImpl implements ProcessDao { return processElement; } - private ZusammenElement createParentElement(ProcessEntity entity) { - ZusammenElement componentElement = new ZusammenElement(); - componentElement.setElementId(new Id(entity.getComponentId())); - componentElement.setAction(Action.IGNORE); - return componentElement; - } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/StructureElement.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/StructureElement.java deleted file mode 100644 index 6f15f5cdee..0000000000 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/StructureElement.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; - -public enum StructureElement { - General, - OrchestrationTemplateCandidate, - OrchestrationTemplate, - OrchestrationTemplateValidationData, - OrchestrationTemplateContent, - OrchestrationTemplateCandidateValidationData, - OrchestrationTemplateCandidateContent, - Networks, - Components, - Nics, - Processes, - Mibs, - SNMP_TRAP, - SNMP_POLL, - VES_EVENTS, - Questionnaire, - ComponentDependencies, - Computes, - Images, - DeploymentFlavors -} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VendorSoftwareProductInfoDaoZusammenImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VendorSoftwareProductInfoDaoZusammenImpl.java index 517a01e58d..aa192ede17 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VendorSoftwareProductInfoDaoZusammenImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VendorSoftwareProductInfoDaoZusammenImpl.java @@ -1,16 +1,15 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; -import com.amdocs.zusammen.datatypes.Id; import com.amdocs.zusammen.datatypes.SessionContext; import com.amdocs.zusammen.datatypes.item.Action; import com.amdocs.zusammen.datatypes.item.ElementContext; import com.amdocs.zusammen.datatypes.item.Info; -import com.amdocs.zusammen.datatypes.item.ItemVersion; -import com.amdocs.zusammen.utils.fileutils.FileUtils; import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToVSPGeneralConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToVSPQuestionnaireConvertor; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; import org.openecomp.sdc.versioning.VersioningManagerFactory; @@ -20,10 +19,14 @@ import org.openecomp.sdc.versioning.types.VersionableEntityStoreType; import java.io.ByteArrayInputStream; import java.util.Collection; -import java.util.Date; import java.util.stream.Collectors; +import static org.openecomp.core.zusammen.api.ZusammenUtil.buildStructuralElement; +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareProductInfoDao { + private static final String EMPTY_DATA = "{}"; + private ZusammenAdaptor zusammenAdaptor; public VendorSoftwareProductInfoDaoZusammenImpl(ZusammenAdaptor zusammenAdaptor) { @@ -33,7 +36,8 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP @Override public void registerVersioning(String versionableEntityType) { VersionableEntityMetadata metadata = - new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "vsp", null, null); + new VersionableEntityMetadata(VersionableEntityStoreType.Zusammen, "VendorSoftwareProduct", + null, null); VersioningManagerFactory.getInstance().createInterface() .register(versionableEntityType, metadata); @@ -41,114 +45,174 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP @Override public Collection<VspDetails> list(VspDetails entity) { - return zusammenAdaptor.listItems(ZusammenUtil.createSessionContext()).stream().filter - (vspEntity-> "vsp".equals(vspEntity.getInfo().getProperty("type"))) - .map(item -> mapInfoToVspDetails( - item.getId().getValue(), null, item.getInfo(), - item.getModificationTime(), item.getCreationTime())) + ElementToVSPGeneralConvertor convertor = new ElementToVSPGeneralConvertor(); + + + return zusammenAdaptor.listItems(createSessionContext()).stream() + .filter(item -> "VendorSoftwareProduct".equals(item.getInfo().getProperty("item_type"))) + .map(item -> convertor.convert(item)) .collect(Collectors.toList()); } + @Override public void create(VspDetails vspDetails) { - SessionContext context = ZusammenUtil.createSessionContext(); + ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.CREATE); - Id itemId = zusammenAdaptor.createItem(context, mapVspDetailsToZusammenItemInfo(vspDetails)); - Id versionId = - zusammenAdaptor.createVersion(context, itemId, null, ZusammenUtil.createFirstVersionData()); + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); + zusammenAdaptor.saveElement(context, elementContext, generalElement, + "Create VSP General Info Element"); - ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.CREATE); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), - generalElement, "Create VSP General Info Element"); + createVspStructure(context, elementContext); + } + + private void createVspStructure(SessionContext context, ElementContext elementContext) { + createOrchestrationTemplateCandidateStructure(context, elementContext); + createVspModelStructure(context, elementContext); - vspDetails.setId(itemId.getValue());//set id for caller + zusammenAdaptor.saveElement(context, elementContext, + buildStructuralElement(ElementType.DeploymentFlavors, Action.CREATE), + "Create VSP Deployment Flavors Element"); + + zusammenAdaptor.saveElement(context, elementContext, + buildStructuralElement(ElementType.Processes, Action.CREATE), + "Create VSP Processes Element"); } - @Override - public void update(VspDetails vspDetails) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspDetails.getId()); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); + private void createOrchestrationTemplateCandidateStructure(SessionContext context, + ElementContext elementContext) { + ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); - zusammenAdaptor.updateItem(context, itemId, mapVspDetailsToZusammenItemInfo(vspDetails)); + ZusammenElement candidateContentElement = + buildStructuralElement(ElementType.OrchestrationTemplateCandidateContent, Action.CREATE); + candidateContentElement.setData(emptyData); - ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.UPDATE); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), - generalElement, "Update VSP General Info Element"); + ZusammenElement candidateElement = + buildStructuralElement(ElementType.OrchestrationTemplateCandidate, Action.CREATE); + candidateElement.setData(emptyData); + candidateElement.addSubElement(candidateContentElement); + + zusammenAdaptor.saveElement(context, elementContext, candidateElement, + "Create Orchestration Template Candidate Elements"); } - @Override - public VspDetails get(VspDetails vspDetails) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspDetails.getId()); - ItemVersion itemVersion = VspZusammenUtil.getFirstVersion(context, itemId, zusammenAdaptor); - ElementContext elementContext = new ElementContext(itemId, itemVersion.getId(), - VspZusammenUtil.getVersionTag(vspDetails.getVersion())); + private void createVspModelStructure(SessionContext context, ElementContext elementContext) { + ZusammenElement vspModel = buildStructuralElement(ElementType.VspModel, Action.CREATE); + vspModel.addSubElement(buildOrchestrationTemplateStructure()); + vspModel.addSubElement(buildStructuralElement(ElementType.Networks, Action.CREATE)); + vspModel.addSubElement(buildStructuralElement(ElementType.Components, Action.CREATE)); + vspModel + .addSubElement(buildStructuralElement(ElementType.ComponentDependencies, Action.CREATE)); + + ZusammenElement templates = buildStructuralElement(ElementType.Templates, Action.CREATE); + ZusammenElement artifacts = buildStructuralElement(ElementType.Artifacts, Action.CREATE); + vspModel.addSubElement( + buildServiceModelStructure(ElementType.ServiceModel, templates, artifacts)); + vspModel.addSubElement( + buildServiceModelStructure(ElementType.EnrichedServiceModel, templates, artifacts)); + + zusammenAdaptor.saveElement(context, elementContext, vspModel, "Create VSP Model Elements"); + } - return zusammenAdaptor - .getElementInfoByName(context, elementContext, null, StructureElement.General.name()) - .map(generalElementInfo -> mapInfoToVspDetails( - vspDetails.getId(), vspDetails.getVersion(), generalElementInfo.getInfo(), - itemVersion.getModificationTime(), itemVersion.getCreationTime())) - .orElse(null); + private ZusammenElement buildOrchestrationTemplateStructure() { + ByteArrayInputStream emptyData = new ByteArrayInputStream(EMPTY_DATA.getBytes()); + + ZusammenElement validationData = + buildStructuralElement(ElementType.OrchestrationTemplateValidationData, Action.CREATE); + validationData.setData(emptyData); + + ZusammenElement orchestrationTemplate = + buildStructuralElement(ElementType.OrchestrationTemplate, Action.CREATE); + orchestrationTemplate.setData(emptyData); + orchestrationTemplate.addSubElement(validationData); + + return orchestrationTemplate; } + private ZusammenElement buildServiceModelStructure(ElementType serviceModelElementType, + ZusammenElement templates, + ZusammenElement artifacts) { + ZusammenElement serviceModel = buildStructuralElement(serviceModelElementType, Action.CREATE); + serviceModel.addSubElement(templates); + serviceModel.addSubElement(artifacts); + return serviceModel; + } @Override - public void delete(VspDetails entity) { + public void update(VspDetails vspDetails) { + ZusammenElement generalElement = mapVspDetailsToZusammenElement(vspDetails, Action.UPDATE); + SessionContext context = createSessionContext(); + zusammenAdaptor.saveElement(context, + new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()), generalElement, + "Update VSP General Info Element"); } @Override - public void updateOldVersionIndication(VspDetails vspDetails) { - VspDetails retrieved = get(vspDetails); - if (retrieved != null) { - retrieved.setOldVersion(vspDetails.getOldVersion()); - update(retrieved); - } + public VspDetails get(VspDetails vspDetails) { + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); + VspDetails vsp = zusammenAdaptor.getElementInfoByName(context, elementContext, null, + ElementType.VendorSoftwareProduct.name()) + .map(new ElementToVSPGeneralConvertor()::convert) + .orElse(null); + vsp.setId(vspDetails.getId()); + vsp.setVersion(vspDetails.getVersion()); + return vsp; + } + + @Override + public void delete(VspDetails vspDetails) { + SessionContext context = createSessionContext(); + ElementContext elementContext = + new ElementContext(vspDetails.getId(), vspDetails.getVersion().getId()); + + zusammenAdaptor.saveElement(context, elementContext, + buildStructuralElement(ElementType.VspModel, Action.DELETE), + "Delete VSP Model Elements"); + + createVspModelStructure(context, elementContext); } @Override public void updateQuestionnaireData(String vspId, Version version, String questionnaireData) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); + SessionContext context = createSessionContext(); ZusammenElement questionnaireElement = mapQuestionnaireToZusammenElement(questionnaireData); - zusammenAdaptor.saveElement(context, new ElementContext(itemId, versionId), + zusammenAdaptor.saveElement(context, new ElementContext(vspId, version.getId()), questionnaireElement, "Update VSP Questionnaire"); } - @Override + /* @Override public String getQuestionnaireData(String vspId, Version version) { - SessionContext context = ZusammenUtil.createSessionContext(); - Id itemId = new Id(vspId); - Id versionId = VspZusammenUtil.getFirstVersionId(context, itemId, zusammenAdaptor); + SessionContext context = createSessionContext(); - return zusammenAdaptor.getElementByName(context, - new ElementContext(itemId, versionId, VspZusammenUtil.getVersionTag(version)), null, - StructureElement.Questionnaire.name()) + return zusammenAdaptor + .getElementByName(context, new ElementContext(vspId, version.getId()), null, + ElementType.Questionnaire.name()) .map(questionnaireElement -> new String(FileUtils.toByteArray(questionnaireElement.getData()))) .orElse(null); - } + }*/ @Override public VspQuestionnaireEntity getQuestionnaire(String vspId, Version version) { - VspQuestionnaireEntity entity = new VspQuestionnaireEntity(); + + SessionContext context = createSessionContext(); + ElementToVSPQuestionnaireConvertor convertor = new ElementToVSPQuestionnaireConvertor(); + VspQuestionnaireEntity entity = convertor.convert(zusammenAdaptor + .getElementByName(context, new ElementContext(vspId, version.getId()), null, + ElementType.VSPQuestionnaire.name()).map(element -> element).orElse(null)); entity.setId(vspId); entity.setVersion(version); - entity.setQuestionnaireData(getQuestionnaireData(vspId, version)); return entity; } @Override - public void deleteAll(String vspId, Version version) { - - } - - @Override public boolean isManual(String vspId, Version version) { final VspDetails vspDetails = get(new VspDetails(vspId, version)); if (vspDetails != null) { @@ -159,29 +223,27 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP return false; } - private Info mapVspDetailsToZusammenItemInfo(VspDetails vspDetails) { - Info info = new Info(); - info.setName(vspDetails.getName()); - info.setDescription(vspDetails.getDescription()); - info.addProperty("type", "vsp"); - addVspDetailsToInfo(info, vspDetails); - return info; - } - private ZusammenElement mapVspDetailsToZusammenElement(VspDetails vspDetails, Action action) { ZusammenElement generalElement = - VspZusammenUtil.buildStructuralElement(StructureElement.General, action); + buildStructuralElement(ElementType.VendorSoftwareProduct, action); addVspDetailsToInfo(generalElement.getInfo(), vspDetails); return generalElement; } private ZusammenElement mapQuestionnaireToZusammenElement(String questionnaireData) { ZusammenElement questionnaireElement = - VspZusammenUtil.buildStructuralElement(StructureElement.Questionnaire, Action.UPDATE); + buildStructuralElement(ElementType.VSPQuestionnaire, Action.UPDATE); questionnaireElement.setData(new ByteArrayInputStream(questionnaireData.getBytes())); return questionnaireElement; } + private ZusammenElement mapTestElementToZusammenElement(String elementData) { + ZusammenElement testElement = + buildStructuralElement(ElementType.test, Action.UPDATE); + testElement.setData(new ByteArrayInputStream(elementData.getBytes())); + return testElement; + } + private void addVspDetailsToInfo(Info info, VspDetails vspDetails) { info.addProperty(InfoPropertyName.name.name(), vspDetails.getName()); info.addProperty(InfoPropertyName.description.name(), vspDetails.getDescription()); @@ -191,45 +253,14 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP info.addProperty(InfoPropertyName.vendorId.name(), vspDetails.getVendorId()); info.addProperty(InfoPropertyName.vendorName.name(), vspDetails.getVendorName()); if (vspDetails.getVlmVersion() != null) { - info.addProperty( - InfoPropertyName.vendorVersion.name(), vspDetails.getVlmVersion().toString()); + info.addProperty(InfoPropertyName.vendorVersion.name(), vspDetails.getVlmVersion().getId()); } info.addProperty(InfoPropertyName.licenseAgreement.name(), vspDetails.getLicenseAgreement()); info.addProperty(InfoPropertyName.featureGroups.name(), vspDetails.getFeatureGroups()); - info.addProperty(InfoPropertyName.oldVersion.name(), vspDetails.getOldVersion()); info.addProperty(InfoPropertyName.onboardingMethod.name(), vspDetails.getOnboardingMethod()); - info.addProperty(InfoPropertyName.obBoardingOrigin.name(), vspDetails.getOnboardingOrigin()); - info.addProperty(InfoPropertyName.networkPackageName.name(), vspDetails.getNetworkPackageName()); - } - - private VspDetails mapInfoToVspDetails(String vspId, Version version, Info info, - Date modificationTime, Date creationTime) { - VspDetails vspDetails = new VspDetails(vspId, version); - vspDetails.setName(info.getProperty(InfoPropertyName.name.name())); - vspDetails.setDescription(info.getProperty(InfoPropertyName.description.name())); - vspDetails.setCategory(info.getProperty(InfoPropertyName.category.name())); - vspDetails.setSubCategory(info.getProperty(InfoPropertyName.subCategory.name())); - vspDetails.setVendorId(info.getProperty(InfoPropertyName.vendorId.name())); - vspDetails.setVendorName(info.getProperty(InfoPropertyName.vendorName.name())); - vspDetails.setVlmVersion( - Version.valueOf(info.getProperty(InfoPropertyName.vendorVersion.name()))); - vspDetails.setLicenseAgreement(info.getProperty(InfoPropertyName.licenseAgreement.name())); - vspDetails.setFeatureGroups(info.getProperty(InfoPropertyName.featureGroups.name())); - - vspDetails.setWritetimeMicroSeconds( - modificationTime == null ? creationTime.getTime() : modificationTime.getTime()); - vspDetails.setVersion(version); - String oldVersion = info.getProperty(InfoPropertyName.oldVersion.name()); - - //Boolean oldVersion = ind == null || "true".equals( ind.toLowerCase()); - vspDetails.setOldVersion(oldVersion); - vspDetails.setOnboardingMethod(info.getProperty(InfoPropertyName.onboardingMethod.name())); - vspDetails.setOnboardingOrigin(info.getProperty(InfoPropertyName.obBoardingOrigin.name())); - vspDetails.setNetworkPackageName(info.getProperty(InfoPropertyName.networkPackageName.name())); - return vspDetails; - } - - private enum InfoPropertyName { + } + + public enum InfoPropertyName { name, description, icon, @@ -240,10 +271,7 @@ public class VendorSoftwareProductInfoDaoZusammenImpl implements VendorSoftwareP vendorVersion, licenseAgreement, featureGroups, - oldVersion, - onboardingMethod, - obBoardingOrigin, - networkPackageName + onboardingMethod } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VspZusammenUtil.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VspZusammenUtil.java index 5e80d4c355..d4dc7e0c4b 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VspZusammenUtil.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/VspZusammenUtil.java @@ -1,49 +1,11 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; -import com.amdocs.zusammen.datatypes.Id; -import com.amdocs.zusammen.datatypes.SessionContext; -import com.amdocs.zusammen.datatypes.item.Action; -import com.amdocs.zusammen.datatypes.item.ItemVersion; -import org.openecomp.core.zusammen.api.ZusammenAdaptor; -import org.openecomp.core.zusammen.api.ZusammenUtil; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.vendorsoftwareproduct.dao.errors.VendorSoftwareProductNotFoundErrorBuilder; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionStatus; import java.util.Objects; -import java.util.Optional; class VspZusammenUtil { - static ItemVersion getFirstVersion(SessionContext context, Id itemId, ZusammenAdaptor - zusammenAdaptor) { - - Optional<ItemVersion> itemVersion = zusammenAdaptor.getFirstVersion(context, itemId); - - if (!itemVersion.isPresent()) { - throw new CoreException( - new VendorSoftwareProductNotFoundErrorBuilder(itemId.getValue()).build()); - } - return itemVersion.get(); - } - - static Id getFirstVersionId(SessionContext context, Id itemId, ZusammenAdaptor zusammenAdaptor) { - return getFirstVersion(context, itemId, zusammenAdaptor).getId(); - } - - // TODO: 4/25/2017 remove upon working with more than one single version - static String getVersionTag(Version version) { - return version.getStatus() == VersionStatus.Locked - ? null - : version.toString(); - } - - static ZusammenElement buildStructuralElement(StructureElement structureElement, Action action) { - return ZusammenUtil.buildStructuralElement(structureElement.name(), action); - } - static ZusammenElement aggregateElements(ZusammenElement... elements) { ZusammenElement head = null; ZusammenElement father = null; diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentConvertor.java new file mode 100644 index 0000000000..ae88a7e6b0 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentConvertor.java @@ -0,0 +1,38 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; +import org.openecomp.types.ElementPropertyName; + +public class ElementToComponentConvertor extends ElementConvertor<ComponentEntity> { + + @Override + public ComponentEntity convert(Element element) { + ComponentEntity componentEntity = new ComponentEntity(); + componentEntity.setId(element.getElementId().getValue()); + componentEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToComponentEntity(componentEntity,element.getInfo()); + return componentEntity; + } + + @Override + public ComponentEntity convert( ElementInfo elementInfo) { + ComponentEntity componentEntity = new ComponentEntity(); + componentEntity.setId(elementInfo.getId().getValue()); + mapInfoToComponentEntity(componentEntity,elementInfo.getInfo()); + return componentEntity; + } + + + public void mapInfoToComponentEntity(ComponentEntity componentEntity,Info info){ + + + componentEntity.setCompositionData( + info.getProperty(ElementPropertyName.compositionData.name())); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentDependencyModelConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentDependencyModelConvertor.java new file mode 100644 index 0000000000..0864ad3482 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentDependencyModelConvertor.java @@ -0,0 +1,41 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.ComponentDependencyModelPropertyName; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentDependencyModelEntity; + +public class ElementToComponentDependencyModelConvertor extends ElementConvertor <ComponentDependencyModelEntity>{ + + @Override + public ComponentDependencyModelEntity convert( Element element) { + ComponentDependencyModelEntity componentDependencyModelEntity = new ComponentDependencyModelEntity(); + componentDependencyModelEntity.setId(element.getElementId().getValue()); + mapInfoToComponentDependencyModelEntity(componentDependencyModelEntity,element.getInfo()); + return componentDependencyModelEntity; + } + + @Override + public ComponentDependencyModelEntity convert(ElementInfo elementInfo) { + ComponentDependencyModelEntity componentDependencyModelEntity = new ComponentDependencyModelEntity(); + + componentDependencyModelEntity.setId(elementInfo.getId().getValue()); + mapInfoToComponentDependencyModelEntity(componentDependencyModelEntity,elementInfo.getInfo()); + return componentDependencyModelEntity; + } + + + public void mapInfoToComponentDependencyModelEntity(ComponentDependencyModelEntity componentDependencyModelEntity,Info info){ + + componentDependencyModelEntity.setSourceComponentId(info + .getProperty(ComponentDependencyModelPropertyName.sourcecomponent_id.name())); + componentDependencyModelEntity.setTargetComponentId(info + .getProperty(ComponentDependencyModelPropertyName.targetcomponent_id.name())); + componentDependencyModelEntity.setRelation(info + .getProperty(ComponentDependencyModelPropertyName.relation.name())); + + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentMonitoringUploadConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentMonitoringUploadConvertor.java new file mode 100644 index 0000000000..dd3d122560 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentMonitoringUploadConvertor.java @@ -0,0 +1,45 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.enrichment.types.MonitoringUploadType; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity; + +import java.nio.ByteBuffer; + +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.ARTIFACT_NAME; + +public class ElementToComponentMonitoringUploadConvertor extends ElementConvertor<ComponentMonitoringUploadEntity> { + + @Override + public ComponentMonitoringUploadEntity convert(Element element) { + ComponentMonitoringUploadEntity mibEntity = new ComponentMonitoringUploadEntity(); + + mibEntity.setId(element.getElementId().getValue()); + mibEntity.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); + mapInfoToComponentMonitoringUploadEntity(mibEntity, element.getInfo()); + return mibEntity; + } + + @Override + public ComponentMonitoringUploadEntity convert(ElementInfo elementInfo) { + ComponentMonitoringUploadEntity mibEntity = new ComponentMonitoringUploadEntity(); + + mibEntity.setId(elementInfo.getId().getValue()); + mapInfoToComponentMonitoringUploadEntity(mibEntity, elementInfo.getInfo()); + return mibEntity; + } + + + public void mapInfoToComponentMonitoringUploadEntity(ComponentMonitoringUploadEntity mibEntity, + Info info) { + + mibEntity.setArtifactName((String) info.getProperties().get(ARTIFACT_NAME)); + mibEntity.setType(MonitoringUploadType.valueOf(info.getName())); + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentQuestionnnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentQuestionnnaireConvertor.java new file mode 100644 index 0000000000..1554a1cc10 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComponentQuestionnnaireConvertor.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; + + +/** + * Created by ayalaben on 9/27/2017 + */ +public class ElementToComponentQuestionnnaireConvertor extends ElementConvertor<ComponentEntity> { + @Override + public ComponentEntity convert( Element element) { + ComponentEntity componentEntity = new ComponentEntity(); + + componentEntity.setId(element.getElementId().getValue()); + componentEntity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); + return componentEntity; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToCompositionEntityConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToCompositionEntityConvertor.java new file mode 100644 index 0000000000..f73da6af01 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToCompositionEntityConvertor.java @@ -0,0 +1,45 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; + +public class ElementToCompositionEntityConvertor extends ElementConvertor <CompositionEntity>{ + + @Override + public CompositionEntity convert(Element element) { + + CompositionEntity compositionEntity = null; + switch (getElementType(element)) { + case ComponentQuestionnaire: + compositionEntity = new ComponentEntity(); + break; + case VSPQuestionnaire: + compositionEntity = new VspQuestionnaireEntity(); + break; + case ImageQuestionnaire: + compositionEntity = new ImageEntity(); + break; + case ComputeQuestionnaire: + compositionEntity = new ComponentEntity(); + break; + case NicQuestionnaire: + compositionEntity = new NicEntity(); + } + if (compositionEntity != null) { + compositionEntity.setId(element.getElementId().getValue()); + compositionEntity.setQuestionnaireData(element.getData() == null + ? null + : new String(FileUtils.toByteArray(element.getData()))); + return compositionEntity; + } else { + return null; + } + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeConvertor.java new file mode 100644 index 0000000000..0412e03690 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeConvertor.java @@ -0,0 +1,40 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; +import org.openecomp.types.ElementPropertyName; + +public class ElementToComputeConvertor extends ElementConvertor <ComputeEntity>{ + + @Override + public ComputeEntity convert( Element element) { + ComputeEntity computeEntity = new ComputeEntity(); + + computeEntity.setId(element.getElementId().getValue()); + computeEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToComputeEntity(computeEntity,element.getInfo()); + return computeEntity; + } + + @Override + public ComputeEntity convert( ElementInfo elementInfo) { + ComputeEntity computeEntity = new ComputeEntity(); + + computeEntity.setId(elementInfo.getId().getValue()); + mapInfoToComputeEntity(computeEntity,elementInfo.getInfo()); + return computeEntity; + } + + + public void mapInfoToComputeEntity(ComputeEntity computeEntity,Info info){ + + + computeEntity.setCompositionData( + info.getProperty(ElementPropertyName.compositionData.name())); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeQuestionnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeQuestionnaireConvertor.java new file mode 100644 index 0000000000..7ac25762b0 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToComputeQuestionnaireConvertor.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComputeEntity; + +public class ElementToComputeQuestionnaireConvertor extends ElementConvertor <ComputeEntity>{ + + @Override + public ComputeEntity convert( Element element) { + ComputeEntity computeEntity = new ComputeEntity(); + + computeEntity.setId(element.getElementId().getValue()); + computeEntity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); + return computeEntity; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToDeploymentFlavorConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToDeploymentFlavorConvertor.java new file mode 100644 index 0000000000..48265bf765 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToDeploymentFlavorConvertor.java @@ -0,0 +1,40 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.DeploymentFlavorEntity; +import org.openecomp.types.ElementPropertyName; + +public class ElementToDeploymentFlavorConvertor extends ElementConvertor <DeploymentFlavorEntity>{ + + @Override + public DeploymentFlavorEntity convert( Element element) { + DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(); + + deploymentFlavorEntity.setId(element.getElementId().getValue()); + deploymentFlavorEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToDeploymentFlavorEntity(deploymentFlavorEntity,element.getInfo()); + return deploymentFlavorEntity; + } + + @Override + public DeploymentFlavorEntity convert( ElementInfo elementInfo) { + DeploymentFlavorEntity deploymentFlavorEntity = new DeploymentFlavorEntity(); + + deploymentFlavorEntity.setId(elementInfo.getId().getValue()); + mapInfoToDeploymentFlavorEntity(deploymentFlavorEntity,elementInfo.getInfo()); + return deploymentFlavorEntity; + } + + + public void mapInfoToDeploymentFlavorEntity(DeploymentFlavorEntity deploymentFlavorEntity,Info info){ + + + deploymentFlavorEntity.setCompositionData( + info.getProperty(ElementPropertyName.compositionData.name())); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageConvertor.java new file mode 100644 index 0000000000..8aa59c52f5 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageConvertor.java @@ -0,0 +1,40 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; +import org.openecomp.types.ElementPropertyName; + +public class ElementToImageConvertor extends ElementConvertor <ImageEntity>{ + + @Override + public ImageEntity convert( Element element) { + ImageEntity imageEntity = new ImageEntity(); + + imageEntity.setId(element.getElementId().getValue()); + imageEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToImageEntity(imageEntity,element.getInfo()); + return imageEntity; + } + + @Override + public ImageEntity convert( ElementInfo elementInfo) { + ImageEntity imageEntity = new ImageEntity(); + + imageEntity.setId(elementInfo.getId().getValue()); + mapInfoToImageEntity(imageEntity,elementInfo.getInfo()); + return imageEntity; + } + + + public void mapInfoToImageEntity(ImageEntity imageEntity,Info info){ + + + imageEntity.setCompositionData( + info.getProperty(ElementPropertyName.compositionData.name())); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageQuestionnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageQuestionnaireConvertor.java new file mode 100644 index 0000000000..2e9cfa0396 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToImageQuestionnaireConvertor.java @@ -0,0 +1,19 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ImageEntity; + +public class ElementToImageQuestionnaireConvertor extends ElementConvertor <ImageEntity>{ + + @Override + public ImageEntity convert( Element element) { + ImageEntity imageEntity = new ImageEntity(); + + imageEntity.setId(element.getElementId().getValue()); + imageEntity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); + return imageEntity; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToMonitoringUploadMapConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToMonitoringUploadMapConvertor.java new file mode 100644 index 0000000000..5da9dc4271 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToMonitoringUploadMapConvertor.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; + +import java.util.HashMap; +import java.util.Map; + +import static org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor.ElementToProcessConvertor.ARTIFACT_NAME; + +/** + * Created by ayalaben on 9/5/2017. + */ + +public class ElementToMonitoringUploadMapConvertor extends ElementConvertor<Map<String ,String>> { + + @Override + public Map<String ,String> convert(Element element) { + HashMap<String,String> map = new HashMap<>(); + map.put("File Name",element.getInfo().getProperty(ARTIFACT_NAME)); + return map; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNetworkConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNetworkConvertor.java new file mode 100644 index 0000000000..6ce24163e6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNetworkConvertor.java @@ -0,0 +1,38 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NetworkEntity; +import org.openecomp.types.ElementPropertyName; + +public class ElementToNetworkConvertor extends ElementConvertor <NetworkEntity>{ + + @Override + public NetworkEntity convert( Element element) { + NetworkEntity networkEntity = new NetworkEntity(); + + networkEntity.setId(element.getElementId().getValue()); + networkEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToNetworkEntity(networkEntity,element.getInfo()); + return networkEntity; + } + + @Override + public NetworkEntity convert( ElementInfo elementInfo) { + NetworkEntity networkEntity = new NetworkEntity(); + + networkEntity.setId(elementInfo.getId().getValue()); + mapInfoToNetworkEntity(networkEntity,elementInfo.getInfo()); + return networkEntity; + } + + + public void mapInfoToNetworkEntity(NetworkEntity networkEntity,Info info){ + networkEntity.setCompositionData( + info.getProperty(ElementPropertyName.compositionData.name())); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicConvertor.java new file mode 100644 index 0000000000..33788af4e1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicConvertor.java @@ -0,0 +1,39 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; +import org.openecomp.types.ElementPropertyName; + +public class ElementToNicConvertor extends ElementConvertor <NicEntity>{ + + @Override + public NicEntity convert( Element element) { + NicEntity nicEntity = new NicEntity(); + + nicEntity.setId(element.getElementId().getValue()); + nicEntity.setCompositionData(new String(FileUtils.toByteArray(element.getData()))); + mapInfoToNicEntity(nicEntity,element.getInfo()); + return nicEntity; + } + + @Override + public NicEntity convert( ElementInfo elementInfo) { + NicEntity nicEntity = new NicEntity(); + + nicEntity.setId(elementInfo.getId().getValue()); + mapInfoToNicEntity(nicEntity,elementInfo.getInfo()); + return nicEntity; + } + + + public void mapInfoToNicEntity(NicEntity nicEntity,Info info){ + + nicEntity.setCompositionData( + info.getProperty(ElementPropertyName.compositionData.name())); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicQuestionnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicQuestionnaireConvertor.java new file mode 100644 index 0000000000..ff53153269 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToNicQuestionnaireConvertor.java @@ -0,0 +1,21 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.NicEntity; + +public class ElementToNicQuestionnaireConvertor extends ElementConvertor <NicEntity>{ + + @Override + public NicEntity convert( Element element) { + NicEntity nicEntity = new NicEntity(); + + nicEntity.setId(element.getElementId().getValue()); + nicEntity.setQuestionnaireData( element.getData() == null + ? null + : new String(FileUtils.toByteArray(element.getData()))); + return nicEntity; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToOrchestrationTemplateCandidateMapConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToOrchestrationTemplateCandidateMapConvertor.java new file mode 100644 index 0000000000..b07df95ecc --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToOrchestrationTemplateCandidateMapConvertor.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure; + +/** + * Created by ayalaben on 9/6/2017 + */ +public class ElementToOrchestrationTemplateCandidateMapConvertor + extends ElementConvertor<FilesDataStructure> { + + @Override + public FilesDataStructure convert(Element element) { + return JsonUtil.json2Object(new String(FileUtils.toByteArray(element.getData())), + FilesDataStructure.class); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToProcessConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToProcessConvertor.java new file mode 100644 index 0000000000..5d3ebc32ad --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToProcessConvertor.java @@ -0,0 +1,53 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessEntity; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ProcessType; + +import java.nio.ByteBuffer; + +public class ElementToProcessConvertor extends ElementConvertor<ProcessEntity> { + + @Override + public ProcessEntity convert(Element element) { + if (element == null) { + return null; + } + ProcessEntity processEntity = new ProcessEntity(); + processEntity.setId(element.getElementId().getValue()); + processEntity.setArtifact(ByteBuffer.wrap(FileUtils.toByteArray(element.getData()))); + mapInfoToProcessEntity(processEntity, element.getInfo()); + return processEntity; + } + + @Override + public ProcessEntity convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + ProcessEntity processEntity = new ProcessEntity(); + processEntity.setId(elementInfo.getId().getValue()); + mapInfoToProcessEntity(processEntity, elementInfo.getInfo()); + return processEntity; + } + + + public void mapInfoToProcessEntity(ProcessEntity processEntity, Info info) { + processEntity.setName(info.getProperty(NAME)); + processEntity.setArtifactName(info.getProperty(ARTIFACT_NAME)); + processEntity.setDescription(info.getProperty(DESCRIPTION)); + processEntity.setType(info.getProperty + (PROCESS_TYPE) != null ? ProcessType.valueOf(info.getProperty + (PROCESS_TYPE)) : null); + } + + + public static final String NAME = "name"; + public static final String ARTIFACT_NAME = "artifactName"; + public static final String DESCRIPTION = "description"; + public static final String PROCESS_TYPE = "processType"; +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToServiceModelMapConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToServiceModelMapConvertor.java new file mode 100644 index 0000000000..bb7e8bb3e8 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToServiceModelMapConvertor.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import org.openecomp.convertor.ElementConvertor; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created by ayalaben on 9/11/2017 + */ +public class ElementToServiceModelMapConvertor extends ElementConvertor<Map<String ,String>> { + @Override + public Map<String ,String> convert(Element element) { + //TODO : after merge with 1802 change to heat fle name/TOSCA file name + HashMap<String,String> map = new HashMap<>(); + map.put("Service Model Definition Entry", element.getInfo().getProperty("base")); + return map; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPGeneralConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPGeneralConvertor.java new file mode 100644 index 0000000000..c5c2f91595 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPGeneralConvertor.java @@ -0,0 +1,78 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.Item; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.VendorSoftwareProductInfoDaoZusammenImpl; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; +import org.openecomp.sdc.versioning.dao.types.Version; + + +public class ElementToVSPGeneralConvertor extends ElementConvertor { + @Override + public VspDetails convert(Element element) { + if (element == null) { + return null; + } + return mapInfoToVspDetails(element.getInfo()); + + } + + @Override + public VspDetails convert(Item item) { + if (item == null) { + return null; + } + VspDetails vspDetails = mapInfoToVspDetails(item.getInfo()); + vspDetails.setId(item.getId().getValue()); + return vspDetails; + } + + @Override + public VspDetails convert(ElementInfo elementInfo) { + if (elementInfo == null) { + return null; + } + return mapInfoToVspDetails(elementInfo.getInfo()); + + } + + + private VspDetails mapInfoToVspDetails(Info info) { + + VspDetails vspDetails = new VspDetails(); + + vspDetails.setName(info.getProperty(VendorSoftwareProductInfoDaoZusammenImpl + .InfoPropertyName.name.name())); + vspDetails.setDescription(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.description.name())); + vspDetails.setIcon(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.icon.name())); + vspDetails.setCategory(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.category.name())); + vspDetails.setSubCategory(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.subCategory.name())); + vspDetails.setVendorId(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.vendorId.name())); + vspDetails.setVendorName(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.vendorName.name())); + if (info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.vendorVersion.name()) != null) { + vspDetails.setVlmVersion(new Version(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.vendorVersion.name()))); + } + + vspDetails.setLicenseAgreement(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.licenseAgreement.name())); + vspDetails.setFeatureGroups(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.featureGroups.name())); + vspDetails.setOnboardingMethod(info.getProperty( + VendorSoftwareProductInfoDaoZusammenImpl.InfoPropertyName.onboardingMethod.name())); + + return vspDetails; + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPQuestionnaireConvertor.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPQuestionnaireConvertor.java new file mode 100644 index 0000000000..d51b8b23b3 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/dao/impl/zusammen/convertor/ElementToVSPQuestionnaireConvertor.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.vendorsoftwareproduct.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.utils.fileutils.FileUtils; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspQuestionnaireEntity; + +public class ElementToVSPQuestionnaireConvertor extends ElementConvertor { + @Override + public VspQuestionnaireEntity convert( Element element) { + if(element == null) return null; + VspQuestionnaireEntity entity = new VspQuestionnaireEntity(); + entity.setQuestionnaireData(new String(FileUtils.toByteArray(element.getData()))); + return entity; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java index d3c2a22fff..b4c0d29f74 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/errors/VendorSoftwareProductErrorCodes.java @@ -60,9 +60,6 @@ public class VendorSoftwareProductErrorCodes { public static final String SAME_SOURCE_TARGET_COMPONENT = "SAME_SOURCE_TARGET_COMPONENT"; - public static final String VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED = - "VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED"; - public static final String DUPLICATE_NIC_NAME_NOT_ALLOWED = "DUPLICATE_NIC_NAME_NOT_ALLOWED"; public static final String NIC_NAME_FORMAT_NOT_ALLOWED = "NIC_NAME_FORMAT_NOT_ALLOWED"; @@ -129,4 +126,7 @@ public class VendorSoftwareProductErrorCodes { public static final String INVALID_EXTENSION = "INVALID_EXTENSION"; + public static final String VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED = + "VSP_ONBOARD_METHOD_UPDATE_NOT_ALLOWED"; + } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CompositionEntityDataManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CompositionEntityDataManagerFactoryImpl.java index a7e55bd290..08d911b686 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CompositionEntityDataManagerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/factory/impl/CompositionEntityDataManagerFactoryImpl.java @@ -26,7 +26,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.factory.CompositionEntityDataManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionEntityDataManager; @@ -42,9 +41,8 @@ public class CompositionEntityDataManagerFactoryImpl extends CompositionEntityDa ComponentDaoFactory.getInstance().createInterface(), NicDaoFactory.getInstance().createInterface(), NetworkDaoFactory.getInstance().createInterface(), - ImageDaoFactory.getInstance().createInterface() , + ImageDaoFactory.getInstance().createInterface(), ComputeDaoFactory.getInstance().createInterface(), - DeploymentFlavorDaoFactory.getInstance().createInterface(), - VendorSoftwareProductDaoFactory.getInstance().createInterface()); + DeploymentFlavorDaoFactory.getInstance().createInterface()); } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/quiestionnaire/QuestionnaireDataServiceImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/quiestionnaire/QuestionnaireDataServiceImpl.java index de29d5b8f0..78914aa0e5 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/quiestionnaire/QuestionnaireDataServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/quiestionnaire/QuestionnaireDataServiceImpl.java @@ -23,8 +23,10 @@ package org.openecomp.sdc.vendorsoftwareproduct.quiestionnaire; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; @@ -47,8 +49,9 @@ import java.util.List; * Created by TALIO on 11/22/2016 */ public class QuestionnaireDataServiceImpl implements QuestionnaireDataService { - private static final VendorSoftwareProductDao vendorSoftwareProductDao = - VendorSoftwareProductDaoFactory.getInstance().createInterface(); + private static final ComponentDao componentDao = + ComponentDaoFactory.getInstance().createInterface(); + private static final NicDao nicDao = NicDaoFactory.getInstance().createInterface(); private static final VendorSoftwareProductInfoDao vspInfoDao = VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); @@ -56,15 +59,11 @@ public class QuestionnaireDataServiceImpl implements QuestionnaireDataService { public InformationArtifactData generateQuestionnaireDataForInformationArtifact(String vspId, Version version) { - - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); - VspDetails vspDetails = - vspInfoDao.get(new VspDetails(vspId, version)); - Collection<ComponentEntity> componentEntities = - vendorSoftwareProductDao.listComponentsQuestionnaire(vspId, version); - Collection<NicEntity> nicEntities = vendorSoftwareProductDao.listNicsByVsp(vspId, version); + VspDetails vspDetails = vspInfoDao.get(new VspDetails(vspId, version)); + Collection<ComponentEntity> componentEntities = componentDao.listQuestionnaires(vspId, version); + Collection<NicEntity> nicEntities = nicDao.listByVsp(vspId, version); VspQuestionnaire vspQuestionnaire = getVspQuestionnaireFromJson(vspId, version); List<ComponentQuestionnaire> componentQuestionnaireList = @@ -100,7 +99,6 @@ public class QuestionnaireDataServiceImpl implements QuestionnaireDataService { return componentQuestionnaireList; } - private List<NicQuestionnaire> getListOfNicQuestionnaireFromJson(Collection<NicEntity> entities) { List<NicQuestionnaire> nicQuestionnaireList = new ArrayList<>(); @@ -112,5 +110,4 @@ public class QuestionnaireDataServiceImpl implements QuestionnaireDataService { return nicQuestionnaireList; } - } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/ManualVspDataCollectionService.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/ManualVspDataCollectionService.java index 100425858f..73b9491e73 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/ManualVspDataCollectionService.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/ManualVspDataCollectionService.java @@ -23,12 +23,12 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComputeDaoFactory; +import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; +import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDaoFactory; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; @@ -57,10 +57,10 @@ import java.util.Optional; public class ManualVspDataCollectionService { - private static final VendorSoftwareProductDao vendorSoftwareProductDao = - VendorSoftwareProductDaoFactory.getInstance().createInterface(); private static final VendorSoftwareProductInfoDao vendorSoftwareProductInfoDao = VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(); + private static final DeploymentFlavorDao deploymentFlavorDao = + DeploymentFlavorDaoFactory.getInstance().createInterface(); private static final ComputeDao computeDao = ComputeDaoFactory.getInstance().createInterface(); private static final ImageDao imageDao = @@ -75,16 +75,14 @@ public class ManualVspDataCollectionService { private final Logger log = (Logger) LoggerFactory.getLogger(this.getClass().getName()); - /** * Gets vendor name for the vsp. * * @param vspId the vsp id * @param version the version - * @param user the user * @return the release vendor name */ - public Optional<String> getReleaseVendor(String vspId, Version version, String user) { + public Optional<String> getReleaseVendor(String vspId, Version version) { String vendorName = null; VspDetails vspDetails = vendorSoftwareProductInfoDao.get(new VspDetails(vspId, version)); if (Objects.nonNull(vspDetails)) { @@ -98,14 +96,12 @@ public class ManualVspDataCollectionService { * * @param vspId the vsp id * @param version the version - * @param user the user * @return the allowed flavors */ - public Map<String, DeploymentFlavorModel> getAllowedFlavors(String vspId, Version version, - String user) { + public Map<String, DeploymentFlavorModel> getAllowedFlavors(String vspId, Version version) { Map<String, DeploymentFlavorModel> allowedFlavors = new HashMap<>(); Collection<DeploymentFlavorEntity> deploymentFlavorEntities = - vendorSoftwareProductDao.listDeploymentFlavors(vspId, version); + deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); if (CollectionUtils.isNotEmpty(deploymentFlavorEntities)) { for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { DeploymentFlavor deploymentFlavorCompositionData = @@ -129,13 +125,12 @@ public class ManualVspDataCollectionService { LicenseFlavor licenseFlavor = getLicenseFlavor(featureGroupId); deploymentFlavorModel.setLicense_flavor(licenseFlavor); //Get sp_part_number - Optional<String> partNumber = getPartNumber(vspVlmId, vlmVersion, featureGroupId, - user); + Optional<String> partNumber = getPartNumber(vspVlmId, vlmVersion, featureGroupId); partNumber.ifPresent(deploymentFlavorModel::setSp_part_number); //Gather and set Vendor Info String vendorModel = deploymentFlavorCompositionData.getModel(); Optional<VendorInfo> vendorInfo = getVendorInfo(vspVlmId, vendorModel, vlmVersion, - featureGroupId, user); + featureGroupId); vendorInfo.ifPresent(deploymentFlavorModel::setVendor_info); //Gather and set Compute info List<ComponentComputeAssociation> componentComputeAssociations = @@ -146,7 +141,7 @@ public class ManualVspDataCollectionService { String componentId = componentComputeAssociation.getComponentId(); String computeFlavorId = componentComputeAssociation.getComputeFlavorId(); Optional<ComputeFlavor> computeFlavor = - getComputeFlavor(vspId, version, componentId, computeFlavorId, user); + getComputeFlavor(vspId, version, componentId, computeFlavorId); computeFlavor.ifPresent(deploymentFlavorModel::setCompute_flavor); } } @@ -164,15 +159,13 @@ public class ManualVspDataCollectionService { * * @param vspId the vsp id * @param version the version - * @param user the user * @return the vsp component images */ public Map<String, List<MultiFlavorVfcImage>> getVspComponentImages(String vspId, - Version version, - String user) { + Version version) { Map<String, List<MultiFlavorVfcImage>> vspComponentImages = new HashMap<>(); Collection<DeploymentFlavorEntity> deploymentFlavorEntities = - vendorSoftwareProductDao.listDeploymentFlavors(vspId, version); + deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { DeploymentFlavor deploymentFlavorCompositionData = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); @@ -184,7 +177,7 @@ public class ManualVspDataCollectionService { componentComputeAssociations) { String componentId = componentComputeAssociation.getComponentId(); List<MultiFlavorVfcImage> componentImages = - getComponentImages(vspId, version, componentId, user); + getComponentImages(vspId, version, componentId); if (CollectionUtils.isNotEmpty(componentImages)) { vspComponentImages.put(componentId, componentImages); } @@ -199,13 +192,12 @@ public class ManualVspDataCollectionService { * * @param vspId the vsp id * @param version the version - * @param user the user * @return the vsp components */ - public Map<String, String> getVspComponents(String vspId, Version version, String user) { + public Map<String, String> getVspComponents(String vspId, Version version) { Map<String, String> componentIdNameMap = new HashMap<>(); Collection<DeploymentFlavorEntity> deploymentFlavorEntities = - vendorSoftwareProductDao.listDeploymentFlavors(vspId, version); + deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { DeploymentFlavor deploymentFlavorCompositionData = deploymentFlavorEntity.getDeploymentFlavorCompositionData(); @@ -216,7 +208,7 @@ public class ManualVspDataCollectionService { for (ComponentComputeAssociation componentComputeAssociation : componentComputeAssociations) { String componentId = componentComputeAssociation.getComponentId(); - Optional<String> componentName = getComponentName(vspId, version, componentId, user); + Optional<String> componentName = getComponentName(vspId, version, componentId); componentName.ifPresent(name -> componentIdNameMap.put(componentId, name)); } } @@ -229,13 +221,12 @@ public class ManualVspDataCollectionService { * * @param vspId the vsp id * @param version the version - * @param user the user * @return the vsp component nics */ - public Map<String, List<Nic>> getVspComponentNics(String vspId, Version version, String user) { + public Map<String, List<Nic>> getVspComponentNics(String vspId, Version version) { Map<String, List<Nic>> vspComponentNics = new HashMap<>(); Collection<DeploymentFlavorEntity> deploymentFlavorEntities = - vendorSoftwareProductDao.listDeploymentFlavors(vspId, version); + deploymentFlavorDao.list(new DeploymentFlavorEntity(vspId, version, null)); if (CollectionUtils.isNotEmpty(deploymentFlavorEntities)) { for (DeploymentFlavorEntity deploymentFlavorEntity : deploymentFlavorEntities) { DeploymentFlavor deploymentFlavorCompositionData = @@ -247,7 +238,7 @@ public class ManualVspDataCollectionService { for (ComponentComputeAssociation componentComputeAssociation : componentComputeAssociations) { String componentId = componentComputeAssociation.getComponentId(); - List<Nic> componentNics = getComponentNics(vspId, version, componentId, user); + List<Nic> componentNics = getComponentNics(vspId, version, componentId); if (CollectionUtils.isNotEmpty(componentNics)) { vspComponentNics.put(componentId, componentNics); } @@ -259,8 +250,7 @@ public class ManualVspDataCollectionService { return vspComponentNics; } - private List<Nic> getComponentNics(String vspId, Version version, String componentId, - String user) { + private List<Nic> getComponentNics(String vspId, Version version, String componentId) { List<Nic> componentNics = new ArrayList<>(); Collection<NicEntity> nics = nicDao.list(new NicEntity(vspId, version, componentId, null)); if (Objects.nonNull(nics)) { @@ -283,8 +273,8 @@ public class ManualVspDataCollectionService { } private Optional<String> getPartNumber(String vlmId, Version version, - String featureGroupId, String user) { - FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId, user); + String featureGroupId) { + FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId); if (Objects.nonNull(featureGroup)) { return Optional.ofNullable(featureGroup.getFeatureGroup().getPartNumber()); } @@ -292,9 +282,9 @@ public class ManualVspDataCollectionService { } private Optional<VendorInfo> getVendorInfo(String vlmId, String vendorModel, Version version, - String featureGroupId, String user) { + String featureGroupId) { VendorInfo vendorInfo = null; - FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId, user); + FeatureGroupModel featureGroup = getFeatureGroup(vlmId, version, featureGroupId); if (Objects.nonNull(featureGroup)) { //Process Feature group to get Manufacturer ref no. String manufacturerReferenceNumber = featureGroup.getEntityManufacturerReferenceNumber(); @@ -308,29 +298,28 @@ public class ManualVspDataCollectionService { } private Optional<ComputeFlavor> getComputeFlavor(String vspId, Version version, - String componentId, String computeFlavorId, - String user) { + String componentId, String computeFlavorId) { ComputeFlavor computeFlavor = null; ComputeEntity computeQuestionnaire = null; try { computeQuestionnaire = computeDao.getQuestionnaireData(vspId, version, componentId, computeFlavorId); } catch (Exception ex) { - log.debug("",ex); + log.debug("", ex); computeQuestionnaire = null; MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Failed to get compute questionnaire : " + ex.getMessage()); } - if (computeQuestionnaire != null && Objects.nonNull(computeQuestionnaire)) { + if (Objects.nonNull(computeQuestionnaire)) { String computeQuestionnaireData = computeQuestionnaire.getQuestionnaireData(); if (Objects.nonNull(computeQuestionnaireData)) { Compute compute; try { compute = JsonUtil.json2Object(computeQuestionnaireData, Compute.class); } catch (Exception ex) { - log.debug("",ex); + log.debug("", ex); compute = null; MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), @@ -354,17 +343,15 @@ public class ManualVspDataCollectionService { return Optional.ofNullable(computeFlavor); } - private FeatureGroupModel getFeatureGroup(String vlmId, Version version, String featureGroupId, - String user) { + private FeatureGroupModel getFeatureGroup(String vlmId, Version version, String featureGroupId) { FeatureGroupEntity fgInput = new FeatureGroupEntity(); fgInput.setVendorLicenseModelId(vlmId); fgInput.setVersion(version); fgInput.setId(featureGroupId); - return vendorLicenseFacade.getFeatureGroupModel(fgInput, user); + return vendorLicenseFacade.getFeatureGroupModel(fgInput); } - private Optional<String> getComponentName(String vspId, Version version, String componentId, - String user) { + private Optional<String> getComponentName(String vspId, Version version, String componentId) { ComponentEntity componentEntity = componentDao.get(new ComponentEntity(vspId, version, componentId)); @@ -377,18 +364,16 @@ public class ManualVspDataCollectionService { } private List<MultiFlavorVfcImage> getComponentImages(String vspId, Version version, - String componentId, String user) { + String componentId) { List<MultiFlavorVfcImage> multiFlavorVfcImages = new ArrayList<>(); - MultiFlavorVfcImage multiFlavorVfcImage = null; + MultiFlavorVfcImage multiFlavorVfcImage; Collection<ImageEntity> componentImages = - vendorSoftwareProductDao.listImages(vspId, version, componentId); + imageDao.list(new ImageEntity(vspId, version, componentId, null)); if (Objects.nonNull(componentImages)) { for (ImageEntity componentImage : componentImages) { - String imageId = componentImage.getId(); - ImageEntity imageEntity = vendorSoftwareProductDao.getImage(vspId, version, componentId, - imageId); + ImageEntity imageEntity = imageDao.get(componentImage); ImageEntity imageQuestionnaireDataEntity = imageDao.getQuestionnaireData(vspId, version, - componentId, imageId); + componentId, componentImage.getId()); Image imageCompositionData = imageEntity.getImageCompositionData(); if (Objects.nonNull(imageEntity) && Objects.nonNull(imageQuestionnaireDataEntity) @@ -398,14 +383,14 @@ public class ManualVspDataCollectionService { imageDetails = JsonUtil.json2Object(imageQuestionnaireDataEntity .getQuestionnaireData(), ImageDetails.class); } catch (Exception ex) { - log.debug("",ex); + log.debug("", ex); imageDetails = null; MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, LoggerTragetServiceName.COLLECT_MANUAL_VSP_TOSCA_DATA, ErrorLevel.INFO.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Unable to parse image questionnaire : " + ex.getMessage()); } - if (imageDetails != null && Objects.nonNull(imageDetails) + if (Objects.nonNull(imageDetails) && Objects.nonNull(imageDetails.getVersion())) { //Image version is used as a key for the image block //So excluding the population if questionnaire data is absent or invalid diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImpl.java index 19e48eceaa..6b57649308 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionDataExtractorImpl.java @@ -47,8 +47,8 @@ import org.openecomp.sdc.tosca.errors.ToscaInvalidSubstituteNodeTemplateErrorBui import org.openecomp.sdc.tosca.errors.ToscaMissingSubstitutionMappingForReqCapErrorBuilder; import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; import org.openecomp.sdc.vendorsoftwareproduct.services.composition.CompositionDataExtractor; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.Component; import org.openecomp.sdc.vendorsoftwareproduct.types.composition.ComponentData; diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionEntityDataManagerImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionEntityDataManagerImpl.java index 39534cf9b7..ab5ee6c64c 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionEntityDataManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/composition/CompositionEntityDataManagerImpl.java @@ -37,7 +37,6 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.DeploymentFlavorDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.ImageDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NetworkDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.NicDao; -import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.VendorSoftwareProductInfoDao; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.CompositionEntity; @@ -78,14 +77,14 @@ import java.util.Set; public class CompositionEntityDataManagerImpl implements CompositionEntityDataManager { private static final String COMPOSITION_ENTITY_DATA_MANAGER_ERR = - "COMPOSITION_ENTITY_DATA_MANAGER_ERR"; + "COMPOSITION_ENTITY_DATA_MANAGER_ERR"; private static final String COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG = - "Invalid input: %s may not be null"; + "Invalid input: %s may not be null"; private static final String MISSING_OR_INVALID_QUESTIONNAIRE_MSG = "Data is missing/invalid for this %s. Please refill and resubmit."; private static final Logger logger = - LoggerFactory.getLogger(CompositionEntityDataManagerImpl.class); + LoggerFactory.getLogger(CompositionEntityDataManagerImpl.class); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private Map<CompositionEntityId, CompositionEntityData> entities = new HashMap<>(); @@ -99,14 +98,12 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa private ImageDao imageDao; private ComputeDao computeDao; private DeploymentFlavorDao deploymentFlavorDao; - private VendorSoftwareProductDao vendorSoftwareProductDao; public CompositionEntityDataManagerImpl(VendorSoftwareProductInfoDao vspInfoDao, ComponentDao componentDao, NicDao nicDao, NetworkDao networkDao, ImageDao imageDao, ComputeDao computeDao, - DeploymentFlavorDao deploymentFlavorDao, - VendorSoftwareProductDao vendorSoftwareProductDao) { + DeploymentFlavorDao deploymentFlavorDao) { this.vspInfoDao = vspInfoDao; this.componentDao = componentDao; this.nicDao = nicDao; @@ -114,7 +111,6 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa this.imageDao = imageDao; this.computeDao = computeDao; this.deploymentFlavorDao = deploymentFlavorDao; - this.vendorSoftwareProductDao = vendorSoftwareProductDao; } /** @@ -133,27 +129,27 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa if (entity == null) { throw new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) - .withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR).withMessage( - String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "composition entity")) - .build()); + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) + .withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR).withMessage( + String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "composition entity")) + .build()); } if (schemaTemplateContext == null) { throw new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) - .withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR).withMessage( - String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "schema template context")) - .build()); + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) + .withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR).withMessage( + String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "schema template context")) + .build()); } CompositionEntityValidationData validationData = - new CompositionEntityValidationData(entity.getType(), entity.getId()); + new CompositionEntityValidationData(entity.getType(), entity.getId()); String json = - schemaTemplateContext == SchemaTemplateContext.composition ? entity.getCompositionData() - : entity.getQuestionnaireData(); + schemaTemplateContext == SchemaTemplateContext.composition ? entity.getCompositionData() + : entity.getQuestionnaireData(); validationData.setErrors(JsonUtil.validate( - json == null ? JsonUtil.object2Json(new Object()) : json, - generateSchema(schemaTemplateContext, entity.getType(), schemaTemplateInput))); + json == null ? JsonUtil.object2Json(new Object()) : json, + generateSchema(schemaTemplateContext, entity.getType(), schemaTemplateInput))); mdcDataDebugMessage.debugExitMessage(null); return validationData; @@ -169,13 +165,13 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa public void addEntity(CompositionEntity entity, SchemaTemplateInput schemaTemplateInput) { if (entity == null) { throw new CoreException( - new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) - .withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR).withMessage( - String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "composition entity")) - .build()); + new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) + .withId(COMPOSITION_ENTITY_DATA_MANAGER_ERR).withMessage( + String.format(COMPOSITION_ENTITY_DATA_MANAGER_ERR_MSG, "composition entity")) + .build()); } entities.put(entity.getCompositionEntityId(), - new CompositionEntityData(entity, schemaTemplateInput)); + new CompositionEntityData(entity, schemaTemplateInput)); } /** @@ -205,10 +201,10 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa @Override public void buildTrees() { Map<CompositionEntityId, CompositionEntityValidationData> entitiesValidationData = - new HashMap<>(); + new HashMap<>(); entities.entrySet().forEach( - entry -> addValidationDataEntity(entitiesValidationData, entry.getKey(), - entry.getValue().entity)); + entry -> addValidationDataEntity(entitiesValidationData, entry.getKey(), + entry.getValue().entity)); } public Collection<CompositionEntityValidationData> getTrees() { @@ -259,14 +255,14 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa } Collection<CompositionEntityValidationData> subEntitiesValidationData = - entity.getSubEntitiesValidationData(); + entity.getSubEntitiesValidationData(); return !CollectionUtils.isEmpty(subEntitiesValidationData) && - checkForErrorsInChildren(subEntitiesValidationData); + checkForErrorsInChildren(subEntitiesValidationData); } private boolean checkForErrorsInChildren( - Collection<CompositionEntityValidationData> subEntitiesValidationData) { + Collection<CompositionEntityValidationData> subEntitiesValidationData) { boolean result = false; for (CompositionEntityValidationData subEntity : subEntitiesValidationData) { if (CollectionUtils.isNotEmpty(subEntity.getErrors())) { @@ -360,10 +356,10 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa //component.setId(CommonMethods.nextUuId()); will be set by the dao component.setQuestionnaireData( - new JsonSchemaDataGenerator( - generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.component, - null)) - .generateData()); + new JsonSchemaDataGenerator( + generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.component, + null)) + .generateData()); componentDao.create(component); @@ -377,9 +373,9 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa //nic.setId(CommonMethods.nextUuId()); will be set by the dao nic.setQuestionnaireData( - new JsonSchemaDataGenerator( - generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null)) - .generateData()); + new JsonSchemaDataGenerator( + generateSchema(SchemaTemplateContext.questionnaire, CompositionEntityType.nic, null)) + .generateData()); nicDao.create(nic); @@ -412,28 +408,26 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa return treeAsList; } - public void getEntityListWithErrors(CompositionEntityValidationData entity, + private void getEntityListWithErrors(CompositionEntityValidationData entity, Set<CompositionEntityValidationData> compositionSet) { - Collection<CompositionEntityValidationData> childNodes = - entity.getSubEntitiesValidationData(); + if(CollectionUtils.isNotEmpty(entity.getErrors())){ + addNodeWithErrors(entity, compositionSet); + } - if (CollectionUtils.isEmpty(childNodes)) { + if (CollectionUtils.isEmpty(entity.getSubEntitiesValidationData())) { return; } - for (CompositionEntityValidationData child : childNodes) { - if (CollectionUtils.isNotEmpty(child.getErrors())) { - addNodeWithErrors(child, compositionSet); - } + for (CompositionEntityValidationData child : entity.getSubEntitiesValidationData()) { getEntityListWithErrors(child, compositionSet); } } - public void addNodeWithErrors(CompositionEntityValidationData node, + private void addNodeWithErrors(CompositionEntityValidationData node, Set<CompositionEntityValidationData> entitiesWithErrors) { CompositionEntityValidationData compositionNodeToAdd = new CompositionEntityValidationData(node - .getEntityType(), node.getEntityId()); + .getEntityType(), node.getEntityId()); compositionNodeToAdd.setErrors(node.getErrors()); compositionNodeToAdd.setSubEntitiesValidationData(null); @@ -446,9 +440,9 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa private CompositionEntityData getCompositionEntityDataById(CompositionEntityValidationData - entity) { + entity) { for (Map.Entry<CompositionEntityId, CompositionEntityData> entityEntry : entities - .entrySet()) { + .entrySet()) { if (entityEntry.getKey().getId().equals(entity.getEntityId())) { return entityEntry.getValue(); } @@ -458,11 +452,11 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa private void updateValidationCompositionEntityName(Set<CompositionEntityValidationData> - compositionSet) { + compositionSet) { for (CompositionEntityValidationData entity : compositionSet) { String compositionData = getCompositionDataAsString(entity); if (entity.getEntityType().equals(CompositionEntityType.vsp) || - Objects.nonNull(compositionData)) { + Objects.nonNull(compositionData)) { entity.setEntityName(getEntityNameByEntityType(compositionData, entity)); } } @@ -497,8 +491,8 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa CompositionEntityData vspEntity = getCompositionEntityDataById(entity); VspQuestionnaireEntity vspQuestionnaireEntity = (VspQuestionnaireEntity) vspEntity.entity; VspDetails vspDetails = - vspInfoDao.get(new VspDetails(vspQuestionnaireEntity.getId(), - vspQuestionnaireEntity.getVersion())); + vspInfoDao.get(new VspDetails(vspQuestionnaireEntity.getId(), + vspQuestionnaireEntity.getVersion())); return vspDetails.getName(); } @@ -514,7 +508,7 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa if (hasChildren(node)) { Collection<CompositionEntityValidationData> subNodes = - new ArrayList<>(node.getSubEntitiesValidationData()); + new ArrayList<>(node.getSubEntitiesValidationData()); subNodes.forEach(subNode -> removeNodesWithoutErrors(subNode, node)); node.setSubEntitiesValidationData(subNodes); @@ -543,14 +537,14 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa private void addValidationDataEntity( - Map<CompositionEntityId, CompositionEntityValidationData> entitiesValidationData, - CompositionEntityId entityId, CompositionEntity entity) { + Map<CompositionEntityId, CompositionEntityValidationData> entitiesValidationData, + CompositionEntityId entityId, CompositionEntity entity) { if (entitiesValidationData.containsKey(entityId)) { return; } CompositionEntityValidationData validationData = - new CompositionEntityValidationData(entity.getType(), entity.getId()); + new CompositionEntityValidationData(entity.getType(), entity.getId()); entitiesValidationData.put(entityId, validationData); CompositionEntityId parentEntityId = entityId.getParentId(); @@ -578,16 +572,16 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa if (node.getSubEntitiesValidationData() != null) { node.getSubEntitiesValidationData() - .forEach(subNode -> addErrorsToTree(subNode, nodeId, errors)); + .forEach(subNode -> addErrorsToTree(subNode, nodeId, errors)); } } private Collection<String> validateQuestionnaire(CompositionEntityData compositionEntityData) { logger.debug(String.format("validateQuestionnaire start: " + - "[entity.type]=%s, [entity.id]=%s, [entity.questionnaireString]=%s", - compositionEntityData.entity.getType().name(), - compositionEntityData.entity.getCompositionEntityId().toString(), - compositionEntityData.entity.getQuestionnaireData())); + "[entity.type]=%s, [entity.id]=%s, [entity.questionnaireString]=%s", + compositionEntityData.entity.getType().name(), + compositionEntityData.entity.getCompositionEntityId().toString(), + compositionEntityData.entity.getQuestionnaireData())); if (Objects.isNull(compositionEntityData.entity.getQuestionnaireData()) || !JsonUtil.isValidJson(compositionEntityData.entity.getQuestionnaireData())) { @@ -596,20 +590,20 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa } return JsonUtil.validate( - compositionEntityData.entity.getQuestionnaireData() == null - ? JsonUtil.object2Json(new Object()) - : compositionEntityData.entity.getQuestionnaireData(), - getSchema(compositionEntityData.entity.getType(), SchemaTemplateContext.questionnaire, - compositionEntityData.schemaTemplateInput)); + compositionEntityData.entity.getQuestionnaireData() == null + ? JsonUtil.object2Json(new Object()) + : compositionEntityData.entity.getQuestionnaireData(), + getSchema(compositionEntityData.entity.getType(), SchemaTemplateContext.questionnaire, + compositionEntityData.schemaTemplateInput)); } private String getSchema(CompositionEntityType compositionEntityType, SchemaTemplateContext schemaTemplateContext, SchemaTemplateInput schemaTemplateInput) { return schemaTemplateInput == null - ? nonDynamicSchemas.computeIfAbsent(compositionEntityType, - k -> generateSchema(schemaTemplateContext, compositionEntityType, null)) - : generateSchema(schemaTemplateContext, compositionEntityType, schemaTemplateInput); + ? nonDynamicSchemas.computeIfAbsent(compositionEntityType, + k -> generateSchema(schemaTemplateContext, compositionEntityType, null)) + : generateSchema(schemaTemplateContext, compositionEntityType, schemaTemplateInput); } private static class CompositionEntityData { @@ -630,7 +624,7 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa CompositionEntityType compositionEntityType, SchemaTemplateInput schemaTemplateInput) { return SchemaGenerator - .generate(schemaTemplateContext, compositionEntityType, schemaTemplateInput); + .generate(schemaTemplateContext, compositionEntityType, schemaTemplateInput); } @Override @@ -649,46 +643,33 @@ public class CompositionEntityDataManagerImpl implements CompositionEntityDataMa image.setId(CommonMethods.nextUuId()); image.setQuestionnaireData( - new JsonSchemaDataGenerator(SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.image, null)) - .generateData()); + new JsonSchemaDataGenerator(SchemaGenerator + .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.image, null)) + .generateData()); imageDao.create(image); mdcDataDebugMessage.debugExitMessage(null, null); return image; } - @Override - public ComputeEntity createCompute(ComputeEntity compute) { - mdcDataDebugMessage.debugEntryMessage("VSP id, component id", compute.getVspId(), - compute.getComponentId()); - - compute.setId(CommonMethods.nextUuId()); - compute.setQuestionnaireData( - new JsonSchemaDataGenerator(SchemaGenerator - .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.compute, - null)).generateData()); - - computeDao.create(compute); - - mdcDataDebugMessage.debugExitMessage("VSP id, component id", compute.getVspId(), - compute.getComponentId()); - return compute; - } - public void saveComputesFlavorByComponent(String vspId, Version version, Component component, String componentId) { if (CollectionUtils.isNotEmpty(component.getCompute())) { for (ComputeData flavor : component.getCompute()) { ComputeEntity computeEntity = new ComputeEntity(vspId, version, componentId, null); computeEntity.setComputeCompositionData(flavor); - createCompute(computeEntity); + computeEntity.setQuestionnaireData( + new JsonSchemaDataGenerator(SchemaGenerator + .generate(SchemaTemplateContext.questionnaire, CompositionEntityType.compute, + null)).generateData()); + + computeDao.create(computeEntity); } } } public void saveImagesByComponent(String vspId, Version version, Component component, String - componentId) { + componentId) { if (CollectionUtils.isNotEmpty(component.getImages())) { for (Image img : component.getImages()) { ImageEntity imageEntity = new ImageEntity(vspId, version, componentId, null); diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/CandidateServiceImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/CandidateServiceImpl.java index 640777e993..45746ed84e 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/CandidateServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/CandidateServiceImpl.java @@ -72,577 +72,591 @@ import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class CandidateServiceImpl implements CandidateService { - protected static final Logger logger = LoggerFactory.getLogger(CandidateServiceImpl.class); - private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + protected static final Logger logger = LoggerFactory.getLogger(CandidateServiceImpl.class); + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); - private CandidateServiceValidator candidateServiceValidator = new CandidateServiceValidator(); - private ManifestCreator manifestCreator; - private OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDataDao; + private CandidateServiceValidator candidateServiceValidator = new CandidateServiceValidator(); + private ManifestCreator manifestCreator; + private OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao; - public CandidateServiceImpl(ManifestCreator manifestCreator, - OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDataDao) { - this.manifestCreator = manifestCreator; - this.orchestrationTemplateCandidateDataDao = orchestrationTemplateCandidateDataDao; + public CandidateServiceImpl(ManifestCreator manifestCreator, + OrchestrationTemplateCandidateDao orchestrationTemplateCandidateDao) { + this.manifestCreator = manifestCreator; + this.orchestrationTemplateCandidateDao = orchestrationTemplateCandidateDao; - } + } - public CandidateServiceImpl() { - } + public CandidateServiceImpl() { + } - @Override - public Optional<ErrorMessage> validateNonEmptyFileToUpload(InputStream fileToUpload) { + @Override + public Optional<ErrorMessage> validateNonEmptyFileToUpload(InputStream fileToUpload) { - mdcDataDebugMessage.debugEntryMessage(null); + mdcDataDebugMessage.debugEntryMessage(null); - if (Objects.isNull(fileToUpload)) { - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); - } else { - try { - int available = fileToUpload.available(); - if (available == 0) { - mdcDataDebugMessage.debugExitMessage(null); - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); - } - } catch (IOException e) { - logger.debug(e.getMessage(), e); - mdcDataDebugMessage.debugExitMessage(null); - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); - } + if (Objects.isNull(fileToUpload)) { + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, + Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); + } else { + try { + int available = fileToUpload.available(); + if (available == 0) { + mdcDataDebugMessage.debugExitMessage(null); + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, + Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); } - + } catch (IOException e) { + logger.debug(e.getMessage(), e); mdcDataDebugMessage.debugExitMessage(null); - return Optional.empty(); + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, + Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); + } } - @Override - public Optional<ErrorMessage> validateRawZipData(byte[] uploadedFileData) { - if (Objects.isNull(uploadedFileData)) { - return Optional.of(new ErrorMessage(ErrorLevel.ERROR, - Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); - } - return Optional.empty(); - } - - private String heatStructureTreeToFileDataStructure(HeatStructureTree tree, - FileContentHandler zipContentMap, - Map<String, List<ErrorMessage>> uploadErrors, - AnalyzedZipHeatFiles analyzedZipHeatFiles) - throws Exception { - FilesDataStructure structure = new FilesDataStructure(); - Set<String> usedEnvFiles = new HashSet<>(); - addHeatsToFileDataStructure(tree, usedEnvFiles, structure, uploadErrors, - analyzedZipHeatFiles); - handleOtherResources(tree, usedEnvFiles, structure); - FilesDataStructure fileDataStructureFromManifest = - createFileDataStructureFromManifest(zipContentMap.getFileContent - (SdcCommon.MANIFEST_NAME)); - List<String> structureArtifacts = structure.getArtifacts(); - structureArtifacts.addAll(fileDataStructureFromManifest.getArtifacts().stream().filter - (artifact -> isNotStrctureArtifact(structureArtifacts, artifact)).collect((Collectors.toList()))); - handleArtifactsFromTree(tree, structure); - - return JsonUtil.object2Json(structure); - } - - private boolean isNotStrctureArtifact(List<String> structureArtifacts, String artifact) { - return !structureArtifacts.contains(artifact); - } - - @Override - public OrchestrationTemplateCandidateData createCandidateDataEntity( - CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, - AnalyzedZipHeatFiles analyzedZipHeatFiles) throws Exception { - - - mdcDataDebugMessage.debugEntryMessage(null); - - FileContentHandler zipContentMap = candidateDataEntityTo.getContentMap(); - FilesDataStructure filesDataStructure; - String dataStructureJson; - - if (zipFileManifest != null) { - // create data structure from manifest - filesDataStructure = createFileDataStructureFromManifest(zipFileManifest); - Set<String> zipFileList = zipContentMap.getFileList(); - balanceManifestFilesWithZipFiles(filesDataStructure, - zipContentMap, analyzedZipHeatFiles); - Set<String> filesDataStructureFiles = getFlatFileNames(filesDataStructure); - filesDataStructure.getUnassigned().addAll(zipFileList.stream() - .filter(fileName -> (!filesDataStructureFiles.contains(fileName) && - !filesDataStructure.getNested().contains(fileName) && - !fileName.equals(SdcCommon.MANIFEST_NAME))) - .collect(Collectors.toList())); - dataStructureJson = JsonUtil.object2Json(filesDataStructure); - } else { - // create data structure from based on naming convention - dataStructureJson = - heatStructureTreeToFileDataStructure(candidateDataEntityTo.getTree(), zipContentMap, - candidateDataEntityTo.getErrors(), analyzedZipHeatFiles); - } + mdcDataDebugMessage.debugExitMessage(null); + return Optional.empty(); + } - mdcDataDebugMessage.debugExitMessage(null); - return new OrchestrationTemplateCandidateData( - ByteBuffer.wrap(candidateDataEntityTo.getUploadedFileData()), dataStructureJson); - } - - private void balanceManifestFilesWithZipFiles( - FilesDataStructure filesDataStructure, - FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles) - throws Exception { - Set<String> zipFileList = fileContentHandler.getFileList(); - filesDataStructure.getNested().addAll(analyzedZipHeatFiles.getNestedFiles()); - List<Module> modules = filesDataStructure.getModules(); - if (CollectionUtils.isEmpty(modules)) { - return; - } + @Override + public Optional<ErrorMessage> validateRawZipData(byte[] uploadedFileData) { + if (Objects.isNull(uploadedFileData)) { + return Optional.of(new ErrorMessage(ErrorLevel.ERROR, + Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage())); + } + return Optional.empty(); + } + + private String heatStructureTreeToFileDataStructure(HeatStructureTree tree, + FileContentHandler zipContentMap, + Map<String, List<ErrorMessage>> uploadErrors, + AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws Exception { + FilesDataStructure structure = new FilesDataStructure(); + Set<String> usedEnvFiles = new HashSet<>(); + addHeatsToFileDataStructure(tree, usedEnvFiles, structure, uploadErrors, + analyzedZipHeatFiles); + handleOtherResources(tree, usedEnvFiles, structure); + FilesDataStructure fileDataStructureFromManifest = + createFileDataStructureFromManifest(zipContentMap.getFileContent + (SdcCommon.MANIFEST_NAME)); + List<String> structureArtifacts = structure.getArtifacts(); + structureArtifacts.addAll(fileDataStructureFromManifest.getArtifacts().stream().filter + (artifact -> isNotStrctureArtifact(structureArtifacts, artifact)) + .collect((Collectors.toList()))); + handleArtifactsFromTree(tree, structure); + + return JsonUtil.object2Json(structure); + } + + private boolean isNotStrctureArtifact(List<String> structureArtifacts, String artifact) { + return !structureArtifacts.contains(artifact); + } - for (int i = 0; i < modules.size(); i++) { - Module module = modules.get(i); - if (!isFileExistInZipContains(zipFileList, module.getYaml())) { - addFileToUnassigned(filesDataStructure, zipFileList, module.getEnv()); - addFileToUnassigned(filesDataStructure, zipFileList, module.getVol()); - addFileToUnassigned(filesDataStructure, zipFileList, module.getVolEnv()); - modules.remove(i--); - } else if (Objects.nonNull(module.getVol()) && !zipFileList.contains(module.getVol())) { - module.setVol(null); - CollectionUtils - .addIgnoreNull(filesDataStructure.getUnassigned(), module.getVolEnv()); - } else { - if (filesDataStructure.getNested().contains(module.getYaml())) { - moveModuleFileToNested(filesDataStructure, i--, module); - } - } - } - } + @Override + public OrchestrationTemplateCandidateData createCandidateDataEntity( + CandidateDataEntityTo candidateDataEntityTo, InputStream zipFileManifest, + AnalyzedZipHeatFiles analyzedZipHeatFiles) throws Exception { + + + mdcDataDebugMessage.debugEntryMessage(null); + + FileContentHandler zipContentMap = candidateDataEntityTo.getContentMap(); + FilesDataStructure filesDataStructure; + String dataStructureJson; + + if (zipFileManifest != null) { + // create data structure from manifest + filesDataStructure = createFileDataStructureFromManifest(zipFileManifest); + Set<String> zipFileList = zipContentMap.getFileList(); + balanceManifestFilesWithZipFiles(filesDataStructure, + zipContentMap, analyzedZipHeatFiles); + Set<String> filesDataStructureFiles = getFlatFileNames(filesDataStructure); + filesDataStructure.getUnassigned().addAll(zipFileList.stream() + .filter(fileName -> (!filesDataStructureFiles.contains(fileName) && + !filesDataStructure.getNested().contains(fileName) && + !fileName.equals(SdcCommon.MANIFEST_NAME))) + .collect(Collectors.toList())); + dataStructureJson = JsonUtil.object2Json(filesDataStructure); + } else { + // create data structure from based on naming convention + dataStructureJson = + heatStructureTreeToFileDataStructure(candidateDataEntityTo.getTree(), zipContentMap, + candidateDataEntityTo.getErrors(), analyzedZipHeatFiles); + } + + OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); + candidateData.setContentData(ByteBuffer.wrap(candidateDataEntityTo.getUploadedFileData())); + candidateData.setFilesDataStructure(dataStructureJson); + + mdcDataDebugMessage.debugExitMessage(null); + return candidateData; + } + + private void balanceManifestFilesWithZipFiles( + FilesDataStructure filesDataStructure, + FileContentHandler fileContentHandler, AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws Exception { + Set<String> zipFileList = fileContentHandler.getFileList(); + filesDataStructure.getNested().addAll(analyzedZipHeatFiles.getNestedFiles()); + List<Module> modules = filesDataStructure.getModules(); + if (CollectionUtils.isEmpty(modules)) { + return; + } + + for (int i = 0; i < modules.size(); i++) { + Module module = modules.get(i); + if (!isFileExistInZipContains(zipFileList, module.getYaml())) { + addFileToUnassigned(filesDataStructure, zipFileList, module.getEnv()); + addFileToUnassigned(filesDataStructure, zipFileList, module.getVol()); + addFileToUnassigned(filesDataStructure, zipFileList, module.getVolEnv()); + modules.remove(i--); + } else if (Objects.nonNull(module.getVol()) && !zipFileList.contains(module.getVol())) { + module.setVol(null); + CollectionUtils + .addIgnoreNull(filesDataStructure.getUnassigned(), module.getVolEnv()); + } else { + if (filesDataStructure.getNested().contains(module.getYaml())) { + moveModuleFileToNested(filesDataStructure, i--, module); + } + } + } + } + + private void addFileToUnassigned(FilesDataStructure filesDataStructure, Set<String> zipFileList, + String fileName) { + if (isFileExistInZipContains(zipFileList, fileName)) { + filesDataStructure.getUnassigned().add(fileName); + } + } + + private boolean isFileExistInZipContains(Set<String> zipFileList, String fileName) { + return Objects.nonNull(fileName) && zipFileList.contains(fileName); + } + + private void moveModuleFileToNested(FilesDataStructure filesDataStructure, int i, + Module module) { + if (!filesDataStructure.getNested().contains(module.getYaml())) { + filesDataStructure.getNested().add(module.getYaml()); + } + if (Objects.nonNull(module.getEnv())) { + filesDataStructure.getNested().add(module.getEnv()); + } + if (Objects.nonNull(module.getVol())) { + filesDataStructure.getNested().add(module.getVol()); + } + if (Objects.nonNull(module.getVolEnv())) { + filesDataStructure.getNested().add(module.getVolEnv()); + } + filesDataStructure.getModules().remove(i); + } + + private Set<String> getFlatFileNames(FilesDataStructure filesDataStructure) { + Set<String> fileNames = new HashSet<>(); + if (!CollectionUtils.isEmpty(filesDataStructure.getModules())) { + for (Module module : filesDataStructure.getModules()) { + CollectionUtils.addIgnoreNull(fileNames, module.getEnv()); + CollectionUtils.addIgnoreNull(fileNames, module.getVol()); + CollectionUtils.addIgnoreNull(fileNames, module.getVolEnv()); + CollectionUtils.addIgnoreNull(fileNames, module.getYaml()); + } + } + fileNames.addAll(filesDataStructure.getArtifacts().stream().collect(Collectors.toSet())); + fileNames.addAll(filesDataStructure.getNested().stream().collect(Collectors.toSet())); + fileNames.addAll(filesDataStructure.getUnassigned().stream().collect(Collectors.toSet())); + + return fileNames; + } + + private FilesDataStructure createFileDataStructureFromManifest(InputStream isManifestContent) { + + + mdcDataDebugMessage.debugEntryMessage(null); + + ManifestContent manifestContent = + JsonUtil.json2Object(isManifestContent, ManifestContent.class); + FilesDataStructure structure = new FilesDataStructure(); + for (FileData fileData : manifestContent.getData()) { + if (Objects.nonNull(fileData.getType()) && + fileData.getType().equals(FileData.Type.HEAT)) { + Module module = new Module(); + module.setYaml(fileData.getFile()); + module.setIsBase(fileData.getBase()); + addHeatDependenciesToModule(module, fileData.getData()); + structure.getModules().add(module); + } else if (HeatFileAnalyzer.isYamlOrEnvFile(fileData.getFile()) && + !FileData.Type.isArtifact(fileData.getType())) { + structure.getUnassigned().add(fileData.getFile()); + } else { + structure.getArtifacts().add(fileData.getFile()); + } + } + + mdcDataDebugMessage.debugExitMessage(null); + return structure; + } + + private void addHeatDependenciesToModule(Module module, List<FileData> data) { + if (CollectionUtils.isEmpty(data)) { + return; + } + + for (FileData fileData : data) { + if (fileData.getType().equals(FileData.Type.HEAT_ENV)) { + module.setEnv(fileData.getFile()); + } else if (fileData.getType().equals(FileData.Type.HEAT_VOL))// must be volume + { + module.setVol(fileData.getFile()); + if (!CollectionUtils.isEmpty(fileData.getData())) { + FileData volEnv = fileData.getData().get(0); + if (volEnv.getType().equals(FileData.Type.HEAT_ENV)) { + module.setVolEnv(volEnv.getFile()); + } else { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage(Messages.ILLEGAL_MANIFEST.getErrorMessage()) + .withId(Messages.ILLEGAL_MANIFEST.getErrorMessage()) + .withCategory(ErrorCategory.APPLICATION).build()); + } + } + } else { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage()) + .withId(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage()) + .withCategory(ErrorCategory.APPLICATION).build()); + } + } + } - private void addFileToUnassigned(FilesDataStructure filesDataStructure, Set<String> zipFileList, - String fileName) { - if (isFileExistInZipContains(zipFileList, fileName)) { - filesDataStructure.getUnassigned().add(fileName); - } - } + @Override + public void updateCandidateUploadData(String vspId, Version version, + OrchestrationTemplateCandidateData uploadData) { + mdcDataDebugMessage.debugEntryMessage(null); - private boolean isFileExistInZipContains(Set<String> zipFileList, String fileName) { - return Objects.nonNull(fileName) && zipFileList.contains(fileName); - } + orchestrationTemplateCandidateDao.update(vspId, version, uploadData); - private void moveModuleFileToNested(FilesDataStructure filesDataStructure, int i, - Module module) { - if (!filesDataStructure.getNested().contains(module.getYaml())) { - filesDataStructure.getNested().add(module.getYaml()); - } - if (Objects.nonNull(module.getEnv())) { - filesDataStructure.getNested().add(module.getEnv()); - } - if (Objects.nonNull(module.getVol())) { - filesDataStructure.getNested().add(module.getVol()); - } - if (Objects.nonNull(module.getVolEnv())) { - filesDataStructure.getNested().add(module.getVolEnv()); - } - filesDataStructure.getModules().remove(i); - } - - private Set<String> getFlatFileNames(FilesDataStructure filesDataStructure) { - Set<String> fileNames = new HashSet<>(); - if (!CollectionUtils.isEmpty(filesDataStructure.getModules())) { - for (Module module : filesDataStructure.getModules()) { - CollectionUtils.addIgnoreNull(fileNames, module.getEnv()); - CollectionUtils.addIgnoreNull(fileNames, module.getVol()); - CollectionUtils.addIgnoreNull(fileNames, module.getVolEnv()); - CollectionUtils.addIgnoreNull(fileNames, module.getYaml()); - } - } - fileNames.addAll(filesDataStructure.getArtifacts().stream().collect(Collectors.toSet())); - fileNames.addAll(filesDataStructure.getNested().stream().collect(Collectors.toSet())); - fileNames.addAll(filesDataStructure.getUnassigned().stream().collect(Collectors.toSet())); - - return fileNames; - } - - private FilesDataStructure createFileDataStructureFromManifest(InputStream isManifestContent) { - - - mdcDataDebugMessage.debugEntryMessage(null); - - ManifestContent manifestContent = - JsonUtil.json2Object(isManifestContent, ManifestContent.class); - FilesDataStructure structure = new FilesDataStructure(); - for (FileData fileData : manifestContent.getData()) { - if (Objects.nonNull(fileData.getType()) && - fileData.getType().equals(FileData.Type.HEAT)) { - Module module = new Module(); - module.setYaml(fileData.getFile()); - module.setIsBase(fileData.getBase()); - addHeatDependenciesToModule(module, fileData.getData()); - structure.getModules().add(module); - } else if (HeatFileAnalyzer.isYamlOrEnvFile(fileData.getFile()) && - !FileData.Type.isArtifact(fileData.getType())) { - structure.getUnassigned().add(fileData.getFile()); - } else { - structure.getArtifacts().add(fileData.getFile()); - } - } + mdcDataDebugMessage.debugExitMessage(null); + } - mdcDataDebugMessage.debugExitMessage(null); - return structure; - } + @Override + public Optional<FilesDataStructure> getOrchestrationTemplateCandidateFileDataStructure( + String vspId, Version version) { - private void addHeatDependenciesToModule(Module module, List<FileData> data) { - if (CollectionUtils.isEmpty(data)) { - return; - } + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); - for (FileData fileData : data) { - if (fileData.getType().equals(FileData.Type.HEAT_ENV)) { - module.setEnv(fileData.getFile()); - } else if (fileData.getType().equals(FileData.Type.HEAT_VOL))// must be volume - { - module.setVol(fileData.getFile()); - if (!CollectionUtils.isEmpty(fileData.getData())) { - FileData volEnv = fileData.getData().get(0); - if (volEnv.getType().equals(FileData.Type.HEAT_ENV)) { - module.setVolEnv(volEnv.getFile()); - } else { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Messages.ILLEGAL_MANIFEST.getErrorMessage()) - .withId(Messages.ILLEGAL_MANIFEST.getErrorMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); - } - } - } else { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()) - .withMessage(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage()) - .withId(Messages.FILE_TYPE_NOT_LEGAL.getErrorMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); - } - } - } + Optional<String> jsonFileDataStructure = + orchestrationTemplateCandidateDao.getStructure(vspId, version); - @Override - public void updateCandidateUploadData(OrchestrationTemplateCandidateData uploadData, - String itemId) { - mdcDataDebugMessage.debugEntryMessage(null); - orchestrationTemplateCandidateDataDao.update(itemId, uploadData); - mdcDataDebugMessage.debugExitMessage(null); + if (jsonFileDataStructure.isPresent() && JsonUtil.isValidJson(jsonFileDataStructure.get())) { + mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); + return Optional + .of(JsonUtil.json2Object(jsonFileDataStructure.get(), FilesDataStructure.class)); + } else { + mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); + return Optional.empty(); } + } - @Override - public Optional<FilesDataStructure> getOrchestrationTemplateCandidateFileDataStructure( - String vspId, Version version) { - - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); - - Optional<String> jsonFileDataStructure = - orchestrationTemplateCandidateDataDao.getStructure(vspId, version); + @Override + public void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, + FilesDataStructure fileDataStructure) { + OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface() + .updateStructure(vspId, version, fileDataStructure); + } - if (jsonFileDataStructure.isPresent() - && JsonUtil.isValidJson(jsonFileDataStructure.get())) { - mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); - return Optional - .of(JsonUtil.json2Object(jsonFileDataStructure.get(), FilesDataStructure.class)); - } else { - mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); - return Optional.empty(); - } - } + @Override + public OrchestrationTemplateCandidateData getOrchestrationTemplateCandidate(String vspId, + Version version) { + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); + mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); - @Override - public void updateOrchestrationTemplateCandidateFileDataStructure(String vspId, Version version, - FilesDataStructure fileDataStructure) { - OrchestrationTemplateCandidateDaoFactory.getInstance().createInterface() - .updateStructure(vspId, version, fileDataStructure); - } + return orchestrationTemplateCandidateDao.get(vspId, version); + } - @Override - public OrchestrationTemplateCandidateData getOrchestrationTemplateCandidate(String vspId, - Version version) { - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); - mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); + @Override + public OrchestrationTemplateCandidateData getOrchestrationTemplateCandidateInfo(String vspId, + Version version) { + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspId); + mdcDataDebugMessage.debugExitMessage("VSP Id", vspId); - return orchestrationTemplateCandidateDataDao.get(vspId, version); - } + return orchestrationTemplateCandidateDao.getInfo(vspId, version); + } @Override public String createManifest(VspDetails vspDetails, FilesDataStructure structure) { - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); - - Optional<ManifestContent> manifest = manifestCreator.createManifest(vspDetails, structure); - if (!manifest.isPresent()) { - throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); - } + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); - mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); - return JsonUtil.object2Json(manifest.get()); - } - - @Override - public Optional<ManifestContent> createManifest(VspDetails vspDetails, - FileContentHandler fileContentHandler, - AnalyzedZipHeatFiles analyzedZipHeatFiles) { - - - mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); - - mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); - return manifestCreator.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); - } - - @Override - public Optional<ByteArrayInputStream> fetchZipFileByteArrayInputStream(String vspId, - OrchestrationTemplateCandidateData candidateDataEntity, - String manifest, - OnboardingTypesEnum type, - Map<String, List<ErrorMessage>> uploadErrors) { - byte[] file; - ByteArrayInputStream byteArrayInputStream = null; - try { - file = replaceManifestInZip(candidateDataEntity.getContentData(), manifest, vspId, type); - byteArrayInputStream = new ByteArrayInputStream( - Objects.isNull(file) ? candidateDataEntity.getContentData().array() - : file); - } catch (IOException e) { - ErrorMessage errorMessage = - new ErrorMessage(ErrorLevel.ERROR, - Messages.CANDIDATE_PROCESS_FAILED.getErrorMessage()); - logger.error(errorMessage.getMessage(), e); - ErrorsUtil - .addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE, errorMessage, uploadErrors); - } - return Optional.ofNullable(byteArrayInputStream); - } - - @Override - public byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, String vspId, - OnboardingTypesEnum type) - throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - try (final ZipOutputStream zos = new ZipOutputStream(baos); - ZipInputStream zipStream = new ZipInputStream( - new ByteArrayInputStream(contentData.array()))) { - ZipEntry zipEntry; - boolean manifestWritten = false; - while ((zipEntry = zipStream.getNextEntry()) != null) { - if (!zipEntry.getName().equalsIgnoreCase(SdcCommon.MANIFEST_NAME)) { - ZipEntry loc_ze = new ZipEntry(zipEntry.getName()); - zos.putNextEntry(loc_ze); - byte[] buf = new byte[1024]; - int len; - while ((len = zipStream.read(buf)) > 0) { - zos.write(buf, 0, (len < buf.length) ? len : buf.length); - } - } else { - manifestWritten = true; - writeManifest(manifest, type, zos); - } - zos.closeEntry(); - } - if (!manifestWritten) { - writeManifest(manifest, type, zos); - zos.closeEntry(); - } - } - return baos.toByteArray(); + Optional<ManifestContent> manifest = manifestCreator.createManifest(vspDetails, structure); + if (!manifest.isPresent()) { + throw new RuntimeException(Messages.CREATE_MANIFEST_FROM_ZIP.getErrorMessage()); } - @Override - public Optional<List<ErrorMessage>> validateFileDataStructure( - FilesDataStructure filesDataStructure) { - return candidateServiceValidator.validateFileDataStructure(filesDataStructure); - } + mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); + return JsonUtil.object2Json(manifest.get()); + } - private void writeManifest(String manifest, - OnboardingTypesEnum type, - ZipOutputStream zos) throws IOException { - - if(isManifestNeedsToGetWritten(type)){ - return; - } - - zos.putNextEntry(new ZipEntry(SdcCommon.MANIFEST_NAME)); - try (InputStream manifestStream = new ByteArrayInputStream( - manifest.getBytes(StandardCharsets.UTF_8))) { - byte[] buf = new byte[1024]; - int len; - while ((len = (manifestStream.read(buf))) > 0) { - zos.write(buf, 0, (len < buf.length) ? len : buf.length); - } - } - } + @Override + public Optional<ManifestContent> createManifest(VspDetails vspDetails, + FileContentHandler fileContentHandler, + AnalyzedZipHeatFiles analyzedZipHeatFiles) { - private boolean isManifestNeedsToGetWritten(OnboardingTypesEnum type) { - return type.equals(OnboardingTypesEnum.CSAR); - } - private void handleArtifactsFromTree(HeatStructureTree tree, FilesDataStructure structure) { + mdcDataDebugMessage.debugEntryMessage("VSP Id", vspDetails.getId()); - if (Objects.isNull(tree) || Objects.isNull(tree.getArtifacts())) { - return; - } - - if (CollectionUtils.isNotEmpty(tree.getArtifacts())) { - structure.getArtifacts().addAll( - tree.getArtifacts() - .stream() - .map(Artifact::getFileName) - .filter(fileName -> !structure.getArtifacts().contains(fileName)) - .collect(Collectors.toList())); - } - } + mdcDataDebugMessage.debugExitMessage("VSP Id", vspDetails.getId()); + return manifestCreator.createManifest(vspDetails, fileContentHandler, analyzedZipHeatFiles); + } - private void handleOtherResources(HeatStructureTree tree, Set<String> usedEnvFiles, - FilesDataStructure structure) { - Set<HeatStructureTree> others = tree.getOther(); - if (Objects.isNull(others)) { - return; - } + @Override + public Optional<ByteArrayInputStream> fetchZipFileByteArrayInputStream(String vspId, + OrchestrationTemplateCandidateData candidateDataEntity, + String manifest, + OnboardingTypesEnum type, + Map<String, List<ErrorMessage>> uploadErrors) { + byte[] file; + ByteArrayInputStream byteArrayInputStream = null; + try { + file = replaceManifestInZip(candidateDataEntity.getContentData(), manifest, vspId, type); + byteArrayInputStream = new ByteArrayInputStream( + Objects.isNull(file) ? candidateDataEntity.getContentData().array() + : file); + } catch (IOException e) { + ErrorMessage errorMessage = + new ErrorMessage(ErrorLevel.ERROR, + Messages.CANDIDATE_PROCESS_FAILED.getErrorMessage()); + logger.error(errorMessage.getMessage(), e); + ErrorsUtil + .addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE, errorMessage, uploadErrors); + } + return Optional.ofNullable(byteArrayInputStream); + } - List<String> artifacts = new ArrayList<>(); - List<String> unassigned = new ArrayList<>(); - for (HeatStructureTree other : others) { - if (HeatFileAnalyzer.isYamlOrEnvFile(other.getFileName())) { - if (isEnvFileUsedByHeatFile(usedEnvFiles, other)) { - continue; - } - unassigned.add(other.getFileName()); - } else { - artifacts.add(other.getFileName()); - } - handleArtifactsFromTree(other, structure); + @Override + public byte[] replaceManifestInZip(ByteBuffer contentData, String manifest, String vspId, + OnboardingTypesEnum type) + throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + try (final ZipOutputStream zos = new ZipOutputStream(baos); + ZipInputStream zipStream = new ZipInputStream( + new ByteArrayInputStream(contentData.array()))) { + ZipEntry zipEntry; + boolean manifestWritten = false; + while ((zipEntry = zipStream.getNextEntry()) != null) { + if (!zipEntry.getName().equalsIgnoreCase(SdcCommon.MANIFEST_NAME)) { + ZipEntry loc_ze = new ZipEntry(zipEntry.getName()); + zos.putNextEntry(loc_ze); + byte[] buf = new byte[1024]; + int len; + while ((len = zipStream.read(buf)) > 0) { + zos.write(buf, 0, (len < buf.length) ? len : buf.length); + } + } else { + manifestWritten = true; + writeManifest(manifest, type, zos); } - structure.getArtifacts().addAll(artifacts); - structure.getUnassigned().addAll(unassigned); + zos.closeEntry(); + } + if (!manifestWritten) { + writeManifest(manifest, type, zos); + zos.closeEntry(); + } } + return baos.toByteArray(); + } - private boolean isEnvFileUsedByHeatFile(Set<String> usedEnvFiles, HeatStructureTree other) { - if (HeatFileAnalyzer.isEnvFile(other.getFileName())) { - if (usedEnvFiles.contains(other.getFileName())) { - return true; - } - } - return false; - } - - private void addHeatsToFileDataStructure(HeatStructureTree tree, Set<String> usedEnvFiles, - FilesDataStructure structure, - Map<String, List<ErrorMessage>> uploadErrors, - AnalyzedZipHeatFiles analyzedZipHeatFiles) - throws Exception { - List<Module> modules = new ArrayList<>(); - Set<HeatStructureTree> heatsSet = tree.getHeat(); - if (Objects.isNull(heatsSet)) { - return; - } - for (HeatStructureTree heat : heatsSet) { - if (isFileBaseFile(heat.getFileName())) { - handleSingleHeat(structure, modules, heat, uploadErrors); - } else if (isFileModuleFile(heat.getFileName(), - analyzedZipHeatFiles.getModuleFiles())) { - handleSingleHeat(structure, modules, heat, uploadErrors); - } else { - structure.getUnassigned().add(heat.getFileName()); - addNestedToFileDataStructure(heat, structure); - } - if (!Objects.isNull(heat.getEnv())) { - usedEnvFiles.add(heat.getEnv() == null ? null : heat.getEnv().getFileName()); - } - } - structure.setModules(modules); - + @Override + public Optional<List<ErrorMessage>> validateFileDataStructure( + FilesDataStructure filesDataStructure) { + return candidateServiceValidator.validateFileDataStructure(filesDataStructure); + } + + private void writeManifest(String manifest, + OnboardingTypesEnum type, + ZipOutputStream zos) throws IOException { + + if (isManifestNeedsToGetWritten(type)) { + return; + } + + zos.putNextEntry(new ZipEntry(SdcCommon.MANIFEST_NAME)); + try (InputStream manifestStream = new ByteArrayInputStream( + manifest.getBytes(StandardCharsets.UTF_8))) { + byte[] buf = new byte[1024]; + int len; + while ((len = (manifestStream.read(buf))) > 0) { + zos.write(buf, 0, (len < buf.length) ? len : buf.length); + } + } + } + + private boolean isManifestNeedsToGetWritten(OnboardingTypesEnum type) { + return type.equals(OnboardingTypesEnum.CSAR); + } + + private void handleArtifactsFromTree(HeatStructureTree tree, FilesDataStructure structure) { + + if (Objects.isNull(tree) || Objects.isNull(tree.getArtifacts())) { + return; + } + + if (CollectionUtils.isNotEmpty(tree.getArtifacts())) { + structure.getArtifacts().addAll( + tree.getArtifacts() + .stream() + .map(Artifact::getFileName) + .filter(fileName -> !structure.getArtifacts().contains(fileName)) + .collect(Collectors.toList())); + } + } + + private void handleOtherResources(HeatStructureTree tree, Set<String> usedEnvFiles, + FilesDataStructure structure) { + Set<HeatStructureTree> others = tree.getOther(); + if (Objects.isNull(others)) { + return; + } + + List<String> artifacts = new ArrayList<>(); + List<String> unassigned = new ArrayList<>(); + for (HeatStructureTree other : others) { + if (HeatFileAnalyzer.isYamlOrEnvFile(other.getFileName())) { + if (isEnvFileUsedByHeatFile(usedEnvFiles, other)) { + continue; + } + unassigned.add(other.getFileName()); + } else { + artifacts.add(other.getFileName()); + } + handleArtifactsFromTree(other, structure); + } + structure.getArtifacts().addAll(artifacts); + structure.getUnassigned().addAll(unassigned); + } + + private boolean isEnvFileUsedByHeatFile(Set<String> usedEnvFiles, HeatStructureTree other) { + if (HeatFileAnalyzer.isEnvFile(other.getFileName())) { + if (usedEnvFiles.contains(other.getFileName())) { + return true; + } + } + return false; + } + + private void addHeatsToFileDataStructure(HeatStructureTree tree, Set<String> usedEnvFiles, + FilesDataStructure structure, + Map<String, List<ErrorMessage>> uploadErrors, + AnalyzedZipHeatFiles analyzedZipHeatFiles) + throws Exception { + List<Module> modules = new ArrayList<>(); + Set<HeatStructureTree> heatsSet = tree.getHeat(); + if (Objects.isNull(heatsSet)) { + return; + } + for (HeatStructureTree heat : heatsSet) { + if (isFileBaseFile(heat.getFileName())) { + handleSingleHeat(structure, modules, heat, uploadErrors); + } else if (isFileModuleFile(heat.getFileName(), + analyzedZipHeatFiles.getModuleFiles())) { + handleSingleHeat(structure, modules, heat, uploadErrors); + } else { + structure.getUnassigned().add(heat.getFileName()); + addNestedToFileDataStructure(heat, structure); + } + if (!Objects.isNull(heat.getEnv())) { + usedEnvFiles.add(heat.getEnv() == null ? null : heat.getEnv().getFileName()); + } } + structure.setModules(modules); - private boolean isFileModuleFile(String fileName, Set<String> modulesFileNames) { - return modulesFileNames.contains(fileName); - } + } - private boolean isFileBaseFile(String fileName) { - return manifestCreator.isFileBaseFile(fileName); - } + private boolean isFileModuleFile(String fileName, Set<String> modulesFileNames) { + return modulesFileNames.contains(fileName); + } - private void handleSingleHeat(FilesDataStructure structure, List<Module> modules, - HeatStructureTree heat, - Map<String, List<ErrorMessage>> uploadErrors) { + private boolean isFileBaseFile(String fileName) { + return manifestCreator.isFileBaseFile(fileName); + } + private void handleSingleHeat(FilesDataStructure structure, List<Module> modules, + HeatStructureTree heat, + Map<String, List<ErrorMessage>> uploadErrors) { - mdcDataDebugMessage.debugEntryMessage(null); - Module module = new Module(); - module.setYaml(heat.getFileName()); - module.setIsBase(heat.getBase()); - addNestedToFileDataStructure(heat, structure); - Set<HeatStructureTree> volumeSet = heat.getVolume(); - int inx = 0; - if (Objects.nonNull(volumeSet)) { - handleVolumes(module, volumeSet, structure, inx, uploadErrors); - } - handleEnv(module, heat, false, structure); - modules.add(module); + mdcDataDebugMessage.debugEntryMessage(null); - mdcDataDebugMessage.debugExitMessage(null); + Module module = new Module(); + module.setYaml(heat.getFileName()); + module.setIsBase(heat.getBase()); + addNestedToFileDataStructure(heat, structure); + Set<HeatStructureTree> volumeSet = heat.getVolume(); + int inx = 0; + if (Objects.nonNull(volumeSet)) { + handleVolumes(module, volumeSet, structure, inx, uploadErrors); } + handleEnv(module, heat, false, structure); + modules.add(module); - private void handleVolumes(Module module, Set<HeatStructureTree> volumeSet, - FilesDataStructure structure, int inx, - Map<String, List<ErrorMessage>> uploadErrors) { + mdcDataDebugMessage.debugExitMessage(null); + } + private void handleVolumes(Module module, Set<HeatStructureTree> volumeSet, + FilesDataStructure structure, int inx, + Map<String, List<ErrorMessage>> uploadErrors) { - mdcDataDebugMessage.debugEntryMessage(null); - for (HeatStructureTree volume : volumeSet) { - if (inx++ > 0) { - ErrorsUtil.addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE, - new ErrorMessage(ErrorLevel.WARNING, - Messages.MORE_THEN_ONE_VOL_FOR_HEAT.getErrorMessage()), uploadErrors); - break; - } - handleArtifactsFromTree(volume, structure); - module.setVol(volume.getFileName()); - handleEnv(module, volume, true, structure); - addNestedToFileDataStructure(volume, structure); - } + mdcDataDebugMessage.debugEntryMessage(null); - mdcDataDebugMessage.debugExitMessage(null); + for (HeatStructureTree volume : volumeSet) { + if (inx++ > 0) { + ErrorsUtil.addStructureErrorToErrorMap(SdcCommon.UPLOAD_FILE, + new ErrorMessage(ErrorLevel.WARNING, + Messages.MORE_THEN_ONE_VOL_FOR_HEAT.getErrorMessage()), uploadErrors); + break; + } + handleArtifactsFromTree(volume, structure); + module.setVol(volume.getFileName()); + handleEnv(module, volume, true, structure); + addNestedToFileDataStructure(volume, structure); } - private void handleEnv(Module module, HeatStructureTree tree, boolean isVolEnv, - FilesDataStructure structure) { + mdcDataDebugMessage.debugExitMessage(null); + } + private void handleEnv(Module module, HeatStructureTree tree, boolean isVolEnv, + FilesDataStructure structure) { - mdcDataDebugMessage.debugEntryMessage(null); - if (Objects.nonNull(tree.getEnv())) { - if (isVolEnv) { - module.setVolEnv(tree.getEnv().getFileName()); - } else { - module.setEnv(tree.getEnv().getFileName()); - } - handleArtifactsFromTree(tree.getEnv(), structure); - } + mdcDataDebugMessage.debugEntryMessage(null); - mdcDataDebugMessage.debugExitMessage(null); + if (Objects.nonNull(tree.getEnv())) { + if (isVolEnv) { + module.setVolEnv(tree.getEnv().getFileName()); + } else { + module.setEnv(tree.getEnv().getFileName()); + } + handleArtifactsFromTree(tree.getEnv(), structure); } - private void addNestedToFileDataStructure(HeatStructureTree heat, - FilesDataStructure structure) { - Set<HeatStructureTree> nestedSet = heat.getNested(); - if (Objects.isNull(nestedSet)) { - return; - } - for (HeatStructureTree nested : nestedSet) { - if (structure.getNested().contains(nested.getFileName())) { - continue; - } - structure.getNested().add(nested.getFileName()); - if (CollectionUtils.isNotEmpty(nested.getArtifacts())) { - handleArtifactsFromTree(nested, structure); - } - addNestedToFileDataStructure(nested, structure); - } + mdcDataDebugMessage.debugExitMessage(null); + } + + private void addNestedToFileDataStructure(HeatStructureTree heat, + FilesDataStructure structure) { + Set<HeatStructureTree> nestedSet = heat.getNested(); + if (Objects.isNull(nestedSet)) { + return; + } + for (HeatStructureTree nested : nestedSet) { + if (structure.getNested().contains(nested.getFileName())) { + continue; + } + structure.getNested().add(nested.getFileName()); + if (CollectionUtils.isNotEmpty(nested.getArtifacts())) { + handleArtifactsFromTree(nested, structure); + } + addNestedToFileDataStructure(nested, structure); } + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/ManifestCreatorNamingConventionImpl.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/ManifestCreatorNamingConventionImpl.java index eed575ff02..ce18097701 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/ManifestCreatorNamingConventionImpl.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/services/impl/filedatastructuremodule/ManifestCreatorNamingConventionImpl.java @@ -68,7 +68,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { addArtifactsToManifestFileDataList(filesDataStructure, fileDataList); ManifestContent manifestContent = createManifest(vspDetails, fileDataList); - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); return Optional.of(manifestContent); } @@ -76,7 +76,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { FilesDataStructure filesDataStructure, List<FileData> fileDataList) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (CollectionUtils.isNotEmpty(filesDataStructure.getNested())) { for (String nested : filesDataStructure.getNested()) { @@ -84,7 +84,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { } } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } @Override @@ -168,7 +168,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { FilesDataStructure filesDataStructure, List<FileData> fileDataList) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); Collection<String> forArtifacts = CollectionUtils .union(filesDataStructure.getArtifacts(), filesDataStructure.getUnassigned()); @@ -178,14 +178,14 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { } } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } private void addModulesToManifestFileDataList( FilesDataStructure filesDataStructure, List<FileData> fileDataList) { - mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugEntryMessage(null); if (CollectionUtils.isNotEmpty(filesDataStructure.getModules())) { for (Module module : filesDataStructure.getModules()) { @@ -197,7 +197,7 @@ public class ManifestCreatorNamingConventionImpl implements ManifestCreator { } } - mdcDataDebugMessage.debugExitMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null); } private void addEnv(Module module, FileData fileData) { diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..982277dbaf --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.sdc.vendorsoftwareproduct.dao.VspMergeDaoFactory": "org.openecomp.sdc.vendorsoftwareproduct.dao.impl.VspMergeDaoFactoryImpl" +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ServiceModelDaoFactoryTest.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ServiceModelDaoFactoryTest.java index 39c14e64fd..4690d75a68 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ServiceModelDaoFactoryTest.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/dao/ServiceModelDaoFactoryTest.java @@ -21,7 +21,9 @@ package org.openecomp.sdc.vendorsoftwareproduct.dao; import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ItemVersionConflict; import com.amdocs.zusammen.adaptor.inbound.api.types.item.ZusammenElement; import com.amdocs.zusammen.commons.health.data.HealthInfo; import com.amdocs.zusammen.datatypes.Id; @@ -32,15 +34,19 @@ import com.amdocs.zusammen.datatypes.item.Info; import com.amdocs.zusammen.datatypes.item.Item; import com.amdocs.zusammen.datatypes.item.ItemVersion; import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus; +import com.amdocs.zusammen.datatypes.item.Resolution; import com.amdocs.zusammen.datatypes.itemversion.Tag; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.datatypes.model.ElementType; import org.openecomp.sdc.model.impl.zusammen.ServiceModelDaoZusammenImpl; -import org.openecomp.sdc.model.impl.zusammen.StructureElement; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.services.YamlUtil; +import org.openecomp.sdc.versioning.dao.types.Revision; import org.openecomp.sdc.versioning.dao.types.Version; import org.testng.Assert; import org.testng.annotations.Test; @@ -49,6 +55,7 @@ import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Optional; @@ -59,6 +66,10 @@ public class ServiceModelDaoFactoryTest { private static final String baseServiceTemplateName = "baseYaml.yaml"; private static String artifact001; + static { + SessionContextProviderFactory.getInstance().createInterface().create("test"); + } + @Test public void storeServiceModelTest() { @@ -91,14 +102,19 @@ public class ServiceModelDaoFactoryTest { ElementInfo elementInfo = new ElementInfo(); Info info = new Info(); - info.addProperty("base","baseElement"); + info.addProperty("base", "baseElement"); elementInfo.setInfo(info); ElementInfo artifactElementInfo = new ElementInfo(); - artifactElementInfo.setInfo(info); + artifactElementInfo.setInfo(new Info()); + artifactElementInfo.getInfo().setName(ElementType.Artifacts.name()); ElementInfo templateElementInfo = new ElementInfo(); - artifactElementInfo.setInfo(info); + templateElementInfo.setInfo(new Info()); + templateElementInfo.getInfo().setName(ElementType.Templates.name()); + ElementInfo serviceModelElementInfo = new ElementInfo(); + serviceModelElementInfo.setInfo(new Info()); + serviceModelElementInfo.getInfo().setName(ElementType.ServiceModel.name()); ZusammenElement element = new ZusammenElement(); ServiceTemplate serviceTemplate = new ServiceTemplate(); YamlUtil yamlUtil = new YamlUtil(); @@ -111,9 +127,11 @@ public class ServiceModelDaoFactoryTest { zusammenAdaptor); zusammenAdaptor.setItemVersion(itemVersionmock); - zusammenAdaptor.addElementInfo("null"+StructureElement.ServiceModel.name(),elementInfo); - zusammenAdaptor.addElementInfo("null"+StructureElement.Artifacts.name(),artifactElementInfo); - zusammenAdaptor.addElementInfo("null"+StructureElement.Templates.name(),templateElementInfo); + zusammenAdaptor.addElementInfo("null" + ElementType.ServiceModel.name(), elementInfo); + zusammenAdaptor.addElementInfo("null" + ElementType.Artifacts.name(), artifactElementInfo); + zusammenAdaptor.addElementInfo("null" + ElementType.Templates.name(), templateElementInfo); + zusammenAdaptor.addElementInfo("null" + ElementType.ServiceModel.name(), + serviceModelElementInfo); zusammenAdaptor.addElement(element); Object model = @@ -126,11 +144,11 @@ public class ServiceModelDaoFactoryTest { } } - private static void setArtifact(ToscaServiceModel model) - { + private static void setArtifact(ToscaServiceModel model) { artifact001 = - (String) (model).getArtifactFiles().getFileList().toArray()[0]; + (String) (model).getArtifactFiles().getFileList().toArray()[0]; } + private ToscaServiceModel getToscaServiceModel() { Map<String, ServiceTemplate> serviceTemplates = getServiceTemplates(baseServiceTemplateName); @@ -171,128 +189,225 @@ public class ServiceModelDaoFactoryTest { return serviceTemplate; } - private class ZusammenAdaptorMock implements ZusammenAdaptor - { + private class ZusammenAdaptorMock implements ZusammenAdaptor { private ItemVersion itemVersion; - private Map<String,ElementInfo> elementInfoMap = new HashMap(); - private Collection<Element> elements = new ArrayList<>(); + private Map<String, ElementInfo> elementInfoMap = new HashMap(); + private Collection<Element> elements = new ArrayList<>(); - public void setItemVersion(ItemVersion itemVersion){ + public void setItemVersion(ItemVersion itemVersion) { this.itemVersion = itemVersion; } - public void addElementInfo(String key,ElementInfo elementInfo){ - elementInfoMap.put(key,elementInfo); + public void addElementInfo(String key, ElementInfo elementInfo) { + elementInfoMap.put(key, elementInfo); } - public void addElement(Element element){ - elements.add(element); + + public void addElement(Element element) { + elements.add(element); } + @Override public Optional<ItemVersion> getFirstVersion(SessionContext context, Id itemId) { return Optional.ofNullable(itemVersion); } - @Override - public Optional<Element> getElement(SessionContext context, ElementContext elementContext, - String elementId) { - return null; - } + @Override + public Collection<ItemVersion> listPublicVersions(SessionContext context, Id itemId) { + return null; + } - @Override - public Optional<Element> getElementByName(SessionContext context, + @Override + public ItemVersion getPublicVersion(SessionContext context, Id itemId, Id versionId) { + return null; + } + + @Override + public Optional<Element> getElement(SessionContext context, ElementContext elementContext, + String elementId) { + return null; + } + + @Override + public Optional<Element> getElementByName(SessionContext context, + ElementContext elementContext, + Id parentElementId, String elementName) { + return null; + } + + @Override + public Collection<ElementInfo> listElements(SessionContext context, ElementContext elementContext, - Id parentElementId, String elementName) { - return null; - } + Id parentElementId) { + return null; + } - @Override - public Collection<ElementInfo> listElements(SessionContext context, - ElementContext elementContext, - Id parentElementId) { - return null; - } + @Override + public Collection<Element> listElementData(SessionContext context, + ElementContext elementContext, + Id parentElementId) { + return elements; + } - @Override - public Collection<Element> listElementData(SessionContext context, - ElementContext elementContext, - Id parentElementId) { - return elements; - } + @Override + public Collection<ElementInfo> listElementsByName(SessionContext context, + ElementContext elementContext, + Id parentElementId, String elementName) { - @Override - public Collection<ElementInfo> listElementsByName(SessionContext context, - ElementContext elementContext, - Id parentElementId, String elementName) { - return null; + if(elementName.equals(ElementType.VspModel.name())){ + return elementInfoMap.values(); } - @Override - public Optional<ElementInfo> getElementInfoByName(SessionContext context, - ElementContext elementContext, - Id parentElementId, String elementName) { - return Optional.ofNullable(elementInfoMap.get(parentElementId+elementName)); - } + return null; + } - @Override - public Optional<Element> saveElement(SessionContext context, ElementContext elementContext, - ZusammenElement element, String message) { - return null; - } + @Override + public Optional<ElementInfo> getElementInfoByName(SessionContext context, + ElementContext elementContext, + Id parentElementId, String elementName) { - @Override - public Collection<HealthInfo> checkHealth(SessionContext context) { - return null; - } + if(elementName.equals(ElementType.Templates.name())){ + return Optional.ofNullable(elementInfoMap.get("null" + elementName)); + }else if(elementName.equals(ElementType.Artifacts.name())) { + return Optional.ofNullable(elementInfoMap.get("null" + elementName)); + } - @Override - public Id createItem(SessionContext context, Info info) { - return null; - } + return Optional.empty(); + } + + @Override + public Element saveElement(SessionContext context, ElementContext elementContext, + ZusammenElement element, String message) { + return null; + } - @Override - public void updateItem(SessionContext context, Id itemId, Info info) { + @Override + public void resolveElementConflict(SessionContext context, ElementContext elementContext, + ZusammenElement element, Resolution resolution) { - } + } + + @Override + public Collection<HealthInfo> checkHealth(SessionContext context) { + return null; + } - @Override - public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, + @Override + public Id createItem(SessionContext context, Info info) { + return null; + } + + @Override + public void updateItem(SessionContext context, Id itemId, Info info) { + + } + + @Override + public Id createVersion(SessionContext context, Id itemId, Id baseVersionId, + ItemVersionData itemVersionData) { + return null; + } + + @Override + public void updateVersion(SessionContext context, Id itemId, Id versionId, ItemVersionData itemVersionData) { - return null; - } - @Override - public void updateVersion(SessionContext context, Id itemId, Id versionId, - ItemVersionData itemVersionData) { + } - } + @Override + public ItemVersion getVersion(SessionContext context, Id itemId, Id versionId) { + return null; + } - @Override - public void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag) { + @Override + public ItemVersionStatus getVersionStatus(SessionContext context, Id itemId, Id versionId) { + return null; + } - } + @Override + public ItemVersionConflict getVersionConflict(SessionContext context, Id itemId, Id versionId) { + return null; + } - @Override - public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, String changeRef) { + @Override + public void tagVersion(SessionContext context, Id itemId, Id versionId, Tag tag) { - } + } - @Override - public Optional<ElementInfo> getElementInfo(SessionContext context, - ElementContext elementContext, - Id elementId) { - return null; - } + @Override + public void resetVersionHistory(SessionContext context, Id itemId, Id versionId, + String changeRef) { - @Override - public String getVersion(SessionContext sessionContext) { - return null; - } - @Override - public Collection<Item> listItems(SessionContext context) { - return null; - } } + + /*@Override + public void revertVersionToRevision(SessionContext context, Id itemId, Id versionId, + Id revisionId) { + + } + + @Override + public ItemVersionRevisions listVersionRevisions(SessionContext context, Id itemId, + Id versionId) { + return null; + }*/ + + @Override + public void publishVersion(SessionContext context, Id itemId, Id versionId, String message) { + + } + + @Override + public void syncVersion(SessionContext sessionContext, Id itemId, Id versionId) { + + } + + @Override + public void forceSyncVersion(SessionContext context, Id itemId, Id versionId) { + + } + + @Override + public Optional<ElementInfo> getElementInfo(SessionContext context, + ElementContext elementContext, + Id elementId) { + return null; + } + + @Override + public String getVersion(SessionContext sessionContext) { + return null; + } + + @Override + public void revert(SessionContext sessionContext, String itemId, String versionId, + String revisionId) { + + } + + @Override + public List<Revision> listRevisions(SessionContext sessionContext, String itemId, + String versionId) { + return null; + } + + @Override + public Optional<ElementConflict> getElementConflict(SessionContext context, + ElementContext elementContext, + Id id) { + return null; + } + + @Override + public Collection<Item> listItems(SessionContext context) { + return null; + } + + @Override + public Item getItem(SessionContext context, Id itemId) { + return null; + } + } } diff --git a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImplTest.java b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImplTest.java index 9f2f733a64..dde8d83dea 100644 --- a/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-vendor-software-product-lib/openecomp-sdc-vendor-software-product-core/src/test/java/org/openecomp/sdc/vendorsoftwareproduct/informationArtifact/impl/TxtInformationArtifactGeneratorImplTest.java @@ -21,41 +21,9 @@ package org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.HEADER; -import static org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.impl.TxtInformationArtifactConstants.VFC_COMPUTE_CPU_OVER_SUBSCRIPTION; - -import org.junit.Assert; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails; -import org.openecomp.sdc.vendorsoftwareproduct.informationArtifact.InformationArtifactData; import org.openecomp.sdc.vendorsoftwareproduct.questionnaire.QuestionnaireDataService; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.ComponentQuestionnaire; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute.Compute; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute.GuestOS; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.compute.NumOfVMs; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general.Hypervisor; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.general.Recovery; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.component.network.NetworkCapacity; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic.IpConfiguration; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic.Network; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic.NicQuestionnaire; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.nic.Protocols; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.VspQuestionnaire; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general.Availability; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general.General; -import org.openecomp.sdc.vendorsoftwareproduct.types.questionnaire.vsp.general.StorageDataReplication; -import org.openecomp.sdc.versioning.dao.types.Version; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; public class TxtInformationArtifactGeneratorImplTest { diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/pom.xml b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/pom.xml index d11362c3a3..dcf2c6a10d 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/pom.xml +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/pom.xml @@ -15,6 +15,21 @@ <dependencies> <dependency> <groupId>org.openecomp.sdc.core</groupId> + <artifactId>openecomp-session-lib</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-core</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc</groupId> + <artifactId>openecomp-item-permissions-api</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.openecomp.sdc.core</groupId> <artifactId>openecomp-facade-core</artifactId> <version>${project.version}</version> </dependency> diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java new file mode 100644 index 0000000000..ee58902a49 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManager.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.versioning; + +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.Item; + +import java.util.Collection; +import java.util.function.Predicate; + +public interface ItemManager { + + Collection<Item> list(Predicate<Item> predicate); + + Item get(String itemId); + + Item create(Item item); + + void updateVersionStatus(String itemId, VersionStatus addedVersionStatus, + VersionStatus removedVersionStatus); + +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManagerFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManagerFactory.java new file mode 100644 index 0000000000..314ffceadb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/ItemManagerFactory.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class ItemManagerFactory extends AbstractComponentFactory<ItemManager> { + + public static ItemManagerFactory getInstance() { + return AbstractFactory.getInstance(ItemManagerFactory.class); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManager.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManager.java index 7fab25456c..c03769462b 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManager.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningManager.java @@ -20,11 +20,14 @@ package org.openecomp.sdc.versioning; +import org.openecomp.sdc.versioning.dao.types.Revision; import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.types.VersionCreationMethod; import org.openecomp.sdc.versioning.types.VersionInfo; import org.openecomp.sdc.versioning.types.VersionableEntityAction; import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; +import java.util.List; import java.util.Map; public interface VersioningManager { @@ -54,4 +57,24 @@ public interface VersioningManager { Map<String, VersionInfo> listDeletedEntitiesVersionInfo(String entityType, String user, VersionableEntityAction action); + + List<Version> list(String itemId); // TODO: 5/24/2017 filter (by status for example) + + Version get(String itemId, Version version); + + Version create(String itemId, Version version, + VersionCreationMethod creationMethod); + + void submit(String itemId, Version version, String submitDescription); + + void publish(String itemId, Version version, String message); + + void sync(String itemId, Version version); + + void forceSync(String itemId, Version version); + + void revert(String itemId, Version version, String revisionId); + + List<Revision> listRevisions(String itemId, Version version); + } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java new file mode 100644 index 0000000000..42161dfef7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/VersioningNotificationConstansts.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.versioning; + +/** + * @author avrahamg + * @since July 10, 2017 + */ +public class VersioningNotificationConstansts { + public static final String ITEM_NAME = "itemName"; + public static final String ITEM_ID = "itemId"; + public static final String SUBMIT_DESCRIPTION = "description"; + public static final String VERSION_NAME = "versionName"; + public static final String VERSION_ID = "versionId"; +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDao.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDao.java new file mode 100644 index 0000000000..f1edc1e0c0 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDao.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.versioning.dao; + +import org.openecomp.sdc.versioning.types.Item; + +import java.util.Collection; + +public interface ItemDao { + Collection<Item> list(); + + Item get(Item item); + + Item create(Item item); + + void update(Item item); +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDaoFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDaoFactory.java new file mode 100644 index 0000000000..36edaa9aa9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/ItemDaoFactory.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.dao; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class ItemDaoFactory extends AbstractComponentFactory<ItemDao> { + public static ItemDaoFactory getInstance() { + return AbstractFactory.getInstance(ItemDaoFactory.class); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDao.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDao.java new file mode 100644 index 0000000000..f557e4d4ec --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDao.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.versioning.dao; + +import org.openecomp.sdc.versioning.dao.types.Revision; +import org.openecomp.sdc.versioning.dao.types.Version; + +import java.util.List; +import java.util.Optional; + +public interface VersionDao { + List<Version> list(String itemId); + + void create(String itemId, Version version); + + void update(String itemId, Version version); + + Optional<Version> get(String itemId, Version version); + + void delete(String itemId, Version version); + + void publish(String itemId, Version version, String message); + + void sync(String itemId, Version version); + + void forceSync(String itemId, Version version); + + void revert(String itemId, Version version, String revisionId); + + List<Revision> listRevisions(String itemId, Version version); +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDaoFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDaoFactory.java new file mode 100644 index 0000000000..845b248d7e --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/VersionDaoFactory.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.dao; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class VersionDaoFactory extends AbstractComponentFactory<VersionDao> { + public static VersionDaoFactory getInstance() { + return AbstractFactory.getInstance(VersionDaoFactory.class); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java new file mode 100644 index 0000000000..492e75fdbb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java @@ -0,0 +1,42 @@ +package org.openecomp.sdc.versioning.dao.types; + +import java.util.Date; + +public class Revision { + private String id; + private String message; + private Date time; + private String user; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public void setMessage(String message) { + this.message = message; + } + + public void setTime(Date time) { + this.time = time; + } + + public String getMessage() { + return message; + } + + public Date getTime() { + return time; + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/SynchronizationState.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/SynchronizationState.java new file mode 100644 index 0000000000..f0142d3e70 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/SynchronizationState.java @@ -0,0 +1,17 @@ +package org.openecomp.sdc.versioning.dao.types; + +public enum SynchronizationState { + UpToDate("Up to date"), + OutOfSync("Out of sync"), + Merging("Merging"); + + private String displayName; + + SynchronizationState(String displayName) { + this.displayName = displayName; + } + + public String toString() { + return this.displayName; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Version.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Version.java index 82b79c6bda..b1f0b71d90 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Version.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Version.java @@ -22,23 +22,44 @@ package org.openecomp.sdc.versioning.dao.types; import com.datastax.driver.mapping.annotations.Transient; import com.datastax.driver.mapping.annotations.UDT; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; + +import java.util.Date; +import java.util.Map; @UDT(name = "version", keyspace = "dox") public class Version { - private static final Logger logger = LoggerFactory.getLogger(Version.class); public static final String VERSION_STRING_VIOLATION_MSG = "Version string must be in the format of: {integer}.{integer}"; - private int major; - private int minor; @Transient - private VersionStatus status = VersionStatus.Available; + private String id; + private int major; // TODO: 6/7/2017 remove! + private int minor; // TODO: 6/7/2017 remove! + @Transient + private String name; + @Transient + private String description; + @Transient + private String baseId; + @Transient + private Date creationTime; + @Transient + private Date modificationTime; + @Transient + private VersionStatus status = VersionStatus.Draft; + @Transient + private VersionState state; + @Transient + private Map<String, Object> additionalInfo; public Version() { } + public Version(String id) { + this.id = id; + } + + @Deprecated public Version(int major, int minor) { this.major = major; this.minor = minor; @@ -62,7 +83,6 @@ public class Version { try { version = new Version(Integer.parseInt(versionLevels[0]), Integer.parseInt(versionLevels[1])); } catch (Exception ex) { - logger.debug(ex.getMessage(), ex); throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); } @@ -85,6 +105,54 @@ public class Version { this.minor = minor; } + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getBaseId() { + return baseId; + } + + public void setBaseId(String baseId) { + this.baseId = baseId; + } + + public Date getCreationTime() { + return creationTime; + } + + public void setCreationTime(Date creationTime) { + this.creationTime = creationTime; + } + + public Date getModificationTime() { + return modificationTime; + } + + public void setModificationTime(Date modificationTime) { + this.modificationTime = modificationTime; + } + public VersionStatus getStatus() { return status; } @@ -93,6 +161,14 @@ public class Version { this.status = status; } + public VersionState getState() { + return state; + } + + public void setState(VersionState state) { + this.state = state; + } + public Version calculateNextCandidate() { return new Version(major, minor + 1); } @@ -105,6 +181,14 @@ public class Version { return major != 0 && minor == 0; } + public Map<String, Object> getAdditionalInfo() { + return additionalInfo; + } + + public void setAdditionalInfo(Map<String, Object> additionalInfo) { + this.additionalInfo = additionalInfo; + } + @Override public int hashCode() { int result = major; @@ -138,6 +222,21 @@ public class Version { @Override public String toString() { - return major + "." + minor; + return name != null ? name : major + "." + minor; + } + + @Override + public Version clone() { + Version version = new Version(); + version.setStatus(this.getStatus()); + version.setCreationTime(this.getCreationTime()); + version.setName(this.getName()); + version.setBaseId(this.getBaseId()); + version.setMajor(this.major); + version.setMinor(this.minor); + version.setModificationTime(this.getModificationTime()); + version.setDescription(this.description); + version.setId(this.getId()); + return version; } -} +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionState.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionState.java new file mode 100644 index 0000000000..8d489802b7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionState.java @@ -0,0 +1,23 @@ +package org.openecomp.sdc.versioning.dao.types; + +public class VersionState { + private SynchronizationState synchronizationState; + private boolean dirty; + + public SynchronizationState getSynchronizationState() { + return synchronizationState; + } + + public void setSynchronizationState( + SynchronizationState synchronizationState) { + this.synchronizationState = synchronizationState; + } + + public boolean isDirty() { + return dirty; + } + + public void setDirty(boolean dirty) { + this.dirty = dirty; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionStatus.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionStatus.java index cf980d6b51..e330b9506a 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionStatus.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/VersionStatus.java @@ -21,7 +21,7 @@ package org.openecomp.sdc.versioning.dao.types; public enum VersionStatus { - Available, - Locked, - Final + Draft, + Locked, /* todo remove!!*/ + Certified } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnUnlockedEntityErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnUnlockedEntityErrorBuilder.java index 4de5618e75..367a93b630 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnUnlockedEntityErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/EditOnUnlockedEntityErrorBuilder.java @@ -20,11 +20,11 @@ package org.openecomp.sdc.versioning.errors; -import static org.openecomp.sdc.versioning.errors.VersioningErrorCodes.EDIT_ON_UNLOCKED_ENTITY; - import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; +import static org.openecomp.sdc.versioning.errors.VersioningErrorCodes.EDIT_ON_UNLOCKED_ENTITY; + /** * The type Edit on unlocked entity error builder. */ diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RevisionIdNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RevisionIdNotFoundErrorBuilder.java new file mode 100644 index 0000000000..0075403acf --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/RevisionIdNotFoundErrorBuilder.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.errors; + +import org.openecomp.sdc.common.errors.BaseErrorBuilder; +import org.openecomp.sdc.common.errors.ErrorCategory; + +/** + * The mandatory field revision id not found error builder. + */ +public class RevisionIdNotFoundErrorBuilder extends BaseErrorBuilder { + + private static final String REVISION_ID_NOT_FOUND_MSG = + "Mandatory field revision id missing"; + + /** + * Instantiates a new Versionable sub entity not found error builder. + */ + public RevisionIdNotFoundErrorBuilder() { + getErrorCodeBuilder().withId(VersioningErrorCodes.MANDATORY_FIELD_REVISION_ID_MISSING); + getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); + getErrorCodeBuilder().withMessage(REVISION_ID_NOT_FOUND_MSG); + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersionableSubEntityNotFoundErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersionableSubEntityNotFoundErrorBuilder.java index 77be83f427..f717e5dbdc 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersionableSubEntityNotFoundErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersionableSubEntityNotFoundErrorBuilder.java @@ -53,7 +53,7 @@ public class VersionableSubEntityNotFoundErrorBuilder extends BaseErrorBuilder { getErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION); getErrorCodeBuilder().withMessage(String .format(SUB_ENTITY_NOT_FOUND_MSG, entityType, entityId, containingEntityType, - containingEntityId, version.toString())); + containingEntityId, version.getId())); } /** diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersioningErrorCodes.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersioningErrorCodes.java index c1c6b96bfd..3dd87d5a3f 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersioningErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/errors/VersioningErrorCodes.java @@ -40,4 +40,10 @@ public class VersioningErrorCodes { public static final String UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER = "UNDO_CHECKOUT_ON_ENTITY_LOCKED_BY_OTHER_USER"; public static final String UNDO_CHECKOUT_ON_UNLOCKED_ENTITY = "UNDO_CHECKOUT_ON_UNLOCKED_ENTITY"; + public static final String MANDATORY_FIELD_REVISION_ID_MISSING = + "MANDATORY_FIELD_REVISION_ID_MISSING"; + + + + } diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/Item.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/Item.java new file mode 100644 index 0000000000..329ac52133 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/Item.java @@ -0,0 +1,103 @@ +package org.openecomp.sdc.versioning.types; + +import org.openecomp.sdc.versioning.dao.types.VersionStatus; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +public class Item { + private String id; + private String type; + private String name; + private String description; + private Map<String, Object> properties = new HashMap<>(); + private Map<VersionStatus, Integer> versionStatusCounters = new HashMap<>(); + private Date creationTime; + private Date modificationTime; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Map<String, Object> getProperties() { + return properties; + } + + public void addProperty(String key, Object value) { + properties.put(key, value); + } + + public void setProperties(Map<String, Object> properties) { + this.properties = properties; + } + + public Map<VersionStatus, Integer> getVersionStatusCounters() { + return versionStatusCounters; + } + + public void setVersionStatusCounters(Map<VersionStatus, Integer> versionStatusCounters) { + this.versionStatusCounters = versionStatusCounters; + } + + public void addVersionStatus(VersionStatus versionStatus) { + Integer counter = versionStatusCounters.get(versionStatus); + versionStatusCounters + .put(versionStatus, counter == null ? 1 : counter + 1); + } + + public void removeVersionStatus(VersionStatus versionStatus) { + Integer counter = versionStatusCounters.get(versionStatus); + if (counter != null) { + if (counter == 1) { + versionStatusCounters.remove(versionStatus); + } else { + versionStatusCounters.put(versionStatus, counter - 1); + } + } + } + + public Date getCreationTime() { + return creationTime; + } + + public void setCreationTime(Date creationTime) { + this.creationTime = creationTime; + } + + public Date getModificationTime() { + return modificationTime; + } + + public void setModificationTime(Date modificationTime) { + this.modificationTime = modificationTime; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/NotificationEventTypes.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/NotificationEventTypes.java new file mode 100644 index 0000000000..b62f7b53e1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/NotificationEventTypes.java @@ -0,0 +1,20 @@ +package org.openecomp.sdc.versioning.types; + +/** + * @author avrahamg + * @since July 10, 2017 + */ +public enum NotificationEventTypes { + SUBMIT("submit"), + COMMIT("commit"); + + private String eventName; + + NotificationEventTypes(String eventName) { + this.eventName = eventName; + } + + public String getEventName() { + return eventName; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionCreationMethod.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionCreationMethod.java new file mode 100644 index 0000000000..6404b6b280 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/types/VersionCreationMethod.java @@ -0,0 +1,8 @@ +package org.openecomp.sdc.versioning.types; + +public enum VersionCreationMethod { + /*parent_level, + same_level, + sub_level*/ + major,minor +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/resources/factoryConfiguration.json index e38ad1a8b4..90d11f1700 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/resources/factoryConfiguration.json +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/resources/factoryConfiguration.json @@ -1,6 +1,10 @@ { + "org.openecomp.sdc.versioning.ItemManagerFactory": "org.openecomp.sdc.versioning.impl.ItemManagerFactoryImpl", "org.openecomp.sdc.versioning.VersioningManagerFactory": "org.openecomp.sdc.versioning.impl.VersioningManagerFactoryImpl", "org.openecomp.sdc.versioning.dao.VersionableEntityDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionableEntityDaoFactoryImpl", "org.openecomp.sdc.versioning.dao.VersionInfoDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionInfoDaoFactoryImpl", - "org.openecomp.sdc.versioning.dao.VersionInfoDeletedDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionInfoDeletedDaoFactoryImpl" + "org.openecomp.sdc.versioning.dao.VersionInfoDeletedDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionInfoDeletedDaoFactoryImpl", + "org.openecomp.sdc.versioning.dao.ItemDaoFactory": "org.openecomp.sdc.versioning.dao.impl.ItemDaoFactoryImpl", + "org.openecomp.sdc.versioning.dao.VersionDaoFactory": "org.openecomp.sdc.versioning.dao.impl.VersionDaoFactoryImpl", + "org.openecomp.sdc.versioning.dao.HealthCheckDaoFactory": "org.openecomp.sdc.model.impl.HealthCheckDaoFactoryImpl" }
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculator.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculator.java new file mode 100644 index 0000000000..dc9ac7b325 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculator.java @@ -0,0 +1,12 @@ +package org.openecomp.sdc.versioning; + +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.types.VersionCreationMethod; + +import java.util.Set; + +public interface VersionCalculator { + String calculate(String baseVersion, VersionCreationMethod creationMethod); + + void injectAdditionalInfo(Version version, Set<String> existingVersions); +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculatorFactory.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculatorFactory.java new file mode 100644 index 0000000000..85f02cd267 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/VersionCalculatorFactory.java @@ -0,0 +1,31 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning; + +import org.openecomp.core.factory.api.AbstractComponentFactory; +import org.openecomp.core.factory.api.AbstractFactory; + +public abstract class VersionCalculatorFactory extends AbstractComponentFactory<VersionCalculator> { + + public static VersionCalculatorFactory getInstance() { + return AbstractFactory.getInstance(VersionCalculatorFactory.class); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/ItemDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/ItemDaoFactoryImpl.java new file mode 100644 index 0000000000..0f9c9065d4 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/ItemDaoFactoryImpl.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.dao.impl; + +import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; +import org.openecomp.sdc.versioning.dao.ItemDao; +import org.openecomp.sdc.versioning.dao.ItemDaoFactory; +import org.openecomp.sdc.versioning.dao.impl.zusammen.ItemZusammenDaoImpl; + +public class ItemDaoFactoryImpl extends ItemDaoFactory { + private static ItemDao INSTANCE = + new ItemZusammenDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public ItemDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionDaoFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionDaoFactoryImpl.java new file mode 100644 index 0000000000..f8b0d71eb7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionDaoFactoryImpl.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.dao.impl; + +import org.openecomp.core.zusammen.api.ZusammenAdaptorFactory; +import org.openecomp.sdc.versioning.dao.VersionDao; +import org.openecomp.sdc.versioning.dao.VersionDaoFactory; +import org.openecomp.sdc.versioning.dao.impl.zusammen.VersionZusammenDaoImpl; + +public class VersionDaoFactoryImpl extends VersionDaoFactory { + private static VersionDao INSTANCE = + new VersionZusammenDaoImpl(ZusammenAdaptorFactory.getInstance().createInterface()); + + @Override + public VersionDao createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoCassandraImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoCassandraImpl.java index 5673da7070..0845beaa2f 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoCassandraImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/VersionableEntityDaoCassandraImpl.java @@ -24,12 +24,12 @@ import com.datastax.driver.core.ColumnDefinitions; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.mapping.UDTMapper; -import org.openecomp.sdc.logging.api.Logger; -import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.core.nosqldb.api.NoSqlDb; import org.openecomp.core.nosqldb.factory.NoSqlDbFactory; import org.openecomp.core.util.UniqueValueUtil; import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.versioning.dao.VersionableEntityDao; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.UniqueValueMetadata; diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/ItemZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/ItemZusammenDaoImpl.java new file mode 100644 index 0000000000..8fdcf71d59 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/ItemZusammenDaoImpl.java @@ -0,0 +1,104 @@ +package org.openecomp.sdc.versioning.dao.impl.zusammen; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.item.Info; +import org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.core.zusammen.api.ZusammenUtil; +import org.openecomp.sdc.versioning.dao.ItemDao; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.Item; + +import java.util.Collection; +import java.util.Map; +import java.util.stream.Collectors; + +public class ItemZusammenDaoImpl implements ItemDao { + + private ZusammenAdaptor zusammenAdaptor; + + public ItemZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } + + @Override + public Collection<Item> list() { + return zusammenAdaptor.listItems(ZusammenUtil.createSessionContext()) + .stream().map(this::mapFromZusammenItem) + .collect(Collectors.toList()); + } + + @Override + public Item get(Item item) { + return mapFromZusammenItem( + zusammenAdaptor.getItem(ZusammenUtil.createSessionContext(), new Id(item.getId()))); + } + + @Override + public Item create(Item item) { + Id itemId = zusammenAdaptor + .createItem(ZusammenUtil.createSessionContext(), mapToZusammenItemInfo(item)); + item.setId(itemId.getValue()); + return item; + } + + @Override + public void update(Item item) { + zusammenAdaptor + .updateItem(ZusammenUtil.createSessionContext(), new Id(item.getId()), + mapToZusammenItemInfo(item)); + } + + private Item mapFromZusammenItem(com.amdocs.zusammen.datatypes.item.Item zusammenItem) { + if (zusammenItem == null) { + return null; + } + Item item = new Item(); + item.setId(zusammenItem.getId().getValue()); + item.setName(zusammenItem.getInfo().getName()); + item.setDescription(zusammenItem.getInfo().getDescription()); + + zusammenItem.getInfo().getProperties().entrySet() + .forEach(property -> addPropertyToItem(property.getKey(), property.getValue(), item)); + + item.setCreationTime(zusammenItem.getCreationTime()); + item.setModificationTime(zusammenItem.getModificationTime()); + return item; + } + + private void addPropertyToItem(String propertyKey, Object propertyValue, Item item) { + switch (propertyKey) { + case InfoPropertyName.ITEM_TYPE: + item.setType((String) propertyValue); + break; + case InfoPropertyName.ITEM_VERSIONS_STATUSES: + for (Map.Entry<String, Number> statusCounter : + ((Map<String, Number>) propertyValue).entrySet()) { + item.getVersionStatusCounters().put(VersionStatus.valueOf(statusCounter.getKey()), + statusCounter.getValue().intValue()); + } + break; + default: + item.addProperty(propertyKey, propertyValue); + } + } + + private Info mapToZusammenItemInfo(Item item) { + Info info = new Info(); + info.setName(item.getName()); + info.setDescription(item.getDescription()); + info.addProperty(InfoPropertyName.ITEM_TYPE, item.getType()); + info.addProperty(InfoPropertyName.ITEM_VERSIONS_STATUSES, item.getVersionStatusCounters()); + item.getProperties().entrySet() + .forEach(property -> info.addProperty(property.getKey(), property.getValue())); + return info; + } + + private static final class InfoPropertyName { + private static final String ITEM_TYPE = "item_type"; + private static final String ITEM_VERSIONS_STATUSES = "item_versions_statuses"; + + private InfoPropertyName() { + throw new IllegalStateException("Constants class"); + } + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImpl.java new file mode 100644 index 0000000000..195973bf5c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImpl.java @@ -0,0 +1,165 @@ +package org.openecomp.sdc.versioning.dao.impl.zusammen; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus; +import com.amdocs.zusammen.datatypes.item.SynchronizationStatus; +import org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.versioning.dao.VersionDao; +import org.openecomp.sdc.versioning.dao.impl.zusammen.convertor.ItemVersionToVersionConvertor; +import org.openecomp.sdc.versioning.dao.types.Revision; +import org.openecomp.sdc.versioning.dao.types.SynchronizationState; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionState; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.openecomp.core.zusammen.api.ZusammenUtil.createSessionContext; + +public class VersionZusammenDaoImpl implements VersionDao { + + public static final class ZusammenProperty { + public static final String LABEL = "label"; + public static final String STATUS = "status"; + + private ZusammenProperty() { + throw new IllegalStateException("Constants class"); + } + } + + private ZusammenAdaptor zusammenAdaptor; + + public VersionZusammenDaoImpl(ZusammenAdaptor zusammenAdaptor) { + this.zusammenAdaptor = zusammenAdaptor; + } + + @Override + public List<Version> list(String itemId) { + ItemVersionToVersionConvertor convertor = new ItemVersionToVersionConvertor(); + return zusammenAdaptor.listPublicVersions(createSessionContext(), new Id(itemId)).stream() + .map(convertor::convert) + .collect(Collectors.toList()); + } + + @Override + public void create(String itemId, Version version) { + Id versionId = + zusammenAdaptor.createVersion(createSessionContext(), new Id(itemId), + version.getBaseId() == null ? null : new Id(version.getBaseId()), + mapToZusammenVersion(version)); + + version.setId(versionId.getValue()); + } + + @Override + public void update(String itemId, Version version) { + zusammenAdaptor.updateVersion(createSessionContext(), new Id(itemId), new Id(version.getId()), + mapToZusammenVersion(version)); + } + + @Override + public Optional<Version> get(String itemId, Version version) { + SessionContext context = createSessionContext(); + Id itemIdObj = new Id(itemId); + Id versionId = new Id(version.getId()); + ItemVersion itemVersion = zusammenAdaptor.getVersion(context, itemIdObj, versionId); + + if (itemVersion == null) { + return Optional.empty(); + } + + VersionState versionState = + convertState(zusammenAdaptor.getVersionStatus(context, itemIdObj, versionId)); + updateVersionStatus(context, itemIdObj, versionId, versionState, itemVersion); + + Version result = new ItemVersionToVersionConvertor().convert(itemVersion); + result.setState(versionState); + return Optional.of(result); + } + + @Override + public void delete(String itemId, Version version) { + throw new UnsupportedOperationException("Delete version operation is not yet supported."); + } + + @Override + public void publish(String itemId, Version version, String message) { + zusammenAdaptor + .publishVersion(createSessionContext(), new Id(itemId), new Id(version.getId()), message); + } + + @Override + public void sync(String itemId, Version version) { + zusammenAdaptor + .syncVersion(createSessionContext(), new Id(itemId), new Id(version.getId())); + } + + @Override + public void forceSync(String itemId, Version version) { + zusammenAdaptor + .forceSyncVersion(createSessionContext(), new Id(itemId), new Id(version.getId())); + } + + @Override + public void revert(String itemId, Version version, String revisionId) { + zusammenAdaptor.revert(createSessionContext(), itemId, version.getId(), revisionId); + } + + @Override + public List<Revision> listRevisions(String itemId, Version version) { + return zusammenAdaptor.listRevisions(createSessionContext(), itemId, version.getId()); + } + + private void updateVersionStatus(SessionContext context, Id itemId, Id versionId, + VersionState versionState, ItemVersion itemVersion) { + if (versionState.getSynchronizationState() != SynchronizationState.UpToDate || + versionState.isDirty()) { + String versionStatus = zusammenAdaptor.getPublicVersion(context, itemId, versionId) + .getData().getInfo().getProperty(ZusammenProperty.STATUS); + itemVersion.getData().getInfo().addProperty(ZusammenProperty.STATUS, versionStatus); + } + } + + private ItemVersionData mapToZusammenVersion(Version version) { + Info info = new Info(); + info.addProperty(ZusammenProperty.LABEL, version.toString()); + info.addProperty(ZusammenProperty.STATUS, version.getStatus().name()); + info.setName(version.getName()); + info.setDescription(version.getDescription()); + + ItemVersionData itemVersionData = new ItemVersionData(); + itemVersionData.setInfo(info); + return itemVersionData; + } + + private VersionState convertState(ItemVersionStatus versionStatus) { + VersionState state = new VersionState(); + state.setSynchronizationState(getSyncState(versionStatus.getSynchronizationStatus())); + state.setDirty(versionStatus.isDirty()); + return state; + } + + private SynchronizationState getSyncState(SynchronizationStatus synchronizationStatus) { + switch (synchronizationStatus) { + case UP_TO_DATE: + return SynchronizationState.UpToDate; + case OUT_OF_SYNC: + return SynchronizationState.OutOfSync; + case MERGING: + return SynchronizationState.Merging; + default: + throw new CoreException(new ErrorCode.ErrorCodeBuilder() + .withCategory(ErrorCategory.APPLICATION) + .withId("UNKNOWN_VERSION_STATE") + .withMessage("Version state is unknown").build()); + } + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/convertor/ItemVersionToVersionConvertor.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/convertor/ItemVersionToVersionConvertor.java new file mode 100644 index 0000000000..f47b5aa612 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/dao/impl/zusammen/convertor/ItemVersionToVersionConvertor.java @@ -0,0 +1,49 @@ +package org.openecomp.sdc.versioning.dao.impl.zusammen.convertor; + +import com.amdocs.zusammen.adaptor.inbound.api.types.item.Element; +import com.amdocs.zusammen.adaptor.inbound.api.types.item.ElementInfo; +import com.amdocs.zusammen.datatypes.item.Item; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import org.openecomp.convertor.ElementConvertor; +import org.openecomp.sdc.versioning.dao.impl.zusammen.VersionZusammenDaoImpl; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; + +public class ItemVersionToVersionConvertor extends ElementConvertor { + @Override + public Object convert(Element element) { + return null; + } + + @Override + public Object convert(Item item) { + return null; + } + + @Override + public Object convert(ElementInfo elementInfo) { + return null; + } + + @Override + public Version convert(ItemVersion itemVersion) { + if (itemVersion == null) { + return null; + } + Version version = Version.valueOf( + itemVersion.getData().getInfo().getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL)); + version.setStatus(VersionStatus.valueOf(itemVersion.getData().getInfo() + .getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS))); + version.setName(itemVersion.getData().getInfo().getName()); + version.setDescription(itemVersion.getData().getInfo().getDescription()); + + version.setId(itemVersion.getId().getValue()); + if (itemVersion.getBaseId() != null) { + version.setBaseId(itemVersion.getBaseId().getValue()); + } + version.setCreationTime(itemVersion.getCreationTime()); + version.setModificationTime(itemVersion.getModificationTime()); + return version; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java new file mode 100644 index 0000000000..ba5bd07d42 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerFactoryImpl.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.impl; + +import org.openecomp.sdc.itempermissions.PermissionsServicesFactory; +import org.openecomp.sdc.notification.factories.SubscriptionServiceFactory; +import org.openecomp.sdc.versioning.ItemManager; +import org.openecomp.sdc.versioning.ItemManagerFactory; +import org.openecomp.sdc.versioning.dao.ItemDaoFactory; + +public class ItemManagerFactoryImpl extends ItemManagerFactory { + private static final ItemManager INSTANCE = + new ItemManagerImpl(ItemDaoFactory.getInstance().createInterface(), + PermissionsServicesFactory.getInstance().createInterface(), + SubscriptionServiceFactory.getInstance().createInterface()); + + @Override + public ItemManager createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerImpl.java new file mode 100644 index 0000000000..79284542fb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/ItemManagerImpl.java @@ -0,0 +1,68 @@ +package org.openecomp.sdc.versioning.impl; + +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.notification.services.SubscriptionService; +import org.openecomp.sdc.versioning.ItemManager; +import org.openecomp.sdc.versioning.dao.ItemDao; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.Item; + +import java.util.Collection; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class ItemManagerImpl implements ItemManager { + public static final String CREATE_ITEM = "Create_Item"; + + private ItemDao itemDao; + private PermissionsServices permissionsServices; + private SubscriptionService subscriptionService; + + public ItemManagerImpl(ItemDao itemDao, PermissionsServices permissionsServices, + SubscriptionService subscriptionService) { + this.itemDao = itemDao; + this.permissionsServices = permissionsServices; + this.subscriptionService = subscriptionService; + } + + @Override + public Collection<Item> list(Predicate<Item> predicate) { + return itemDao.list().stream().filter(predicate).collect(Collectors.toList()); + } + + @Override + public Item get(String itemId) { + Item item = new Item(); + item.setId(itemId); + return itemDao.get(item); + } + + @Override + public Item create(Item item) { + Item createdItem = itemDao.create(item); + + String userId = SessionContextProviderFactory.getInstance() + .createInterface().get().getUser().getUserId(); + String itemId = createdItem.getId(); + permissionsServices.execute(itemId, userId, CREATE_ITEM); + subscriptionService.subscribe(userId, itemId); + + return createdItem; + } + + @Override + public void updateVersionStatus(String itemId, VersionStatus addedVersionStatus, + VersionStatus removedVersionStatus) { + Item item = get(itemId); + if (item == null) { + return; + } + + item.addVersionStatus(addedVersionStatus); + if (removedVersionStatus != null) { + item.removeVersionStatus(removedVersionStatus); + } + itemDao.update(item); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorFactoryImpl.java new file mode 100644 index 0000000000..2300f62180 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorFactoryImpl.java @@ -0,0 +1,14 @@ +package org.openecomp.sdc.versioning.impl; + +import org.openecomp.sdc.versioning.VersionCalculator; +import org.openecomp.sdc.versioning.VersionCalculatorFactory; + +public class MajorVersionCalculatorFactoryImpl extends VersionCalculatorFactory { + private static final VersionCalculator INSTANCE = + new MajorVersionCalculatorImpl(); + + @Override + public VersionCalculator createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorImpl.java new file mode 100644 index 0000000000..91c59e0efd --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/MajorVersionCalculatorImpl.java @@ -0,0 +1,53 @@ +package org.openecomp.sdc.versioning.impl; + +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.versioning.VersionCalculator; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.VersionCreationMethod; + +import java.util.HashSet; +import java.util.Set; + +public class MajorVersionCalculatorImpl implements VersionCalculator { + private static final String INITIAL_VERSION = "1.0"; + private static final String VERSION_STRING_VIOLATION_MSG = + "Version string must be in the format of: {integer}.{integer}"; + + @Override + public String calculate(String baseVersion, VersionCreationMethod creationMethod) { + + if (baseVersion == null) { + return INITIAL_VERSION; + } + + String[] versionLevels = baseVersion.split("\\."); + if (versionLevels.length != 2) { + throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + } + + int index = Integer.parseInt(versionLevels[0]); + index++; + versionLevels[0] = Integer.toString(index); + versionLevels[1] = "0"; + + return CommonMethods.arrayToSeparatedString(versionLevels, '.'); + } + + @Override + public void injectAdditionalInfo(Version version, Set<String> existingVersions) { + String optionalVersion; + Set<VersionCreationMethod> optionalCreationMethods = new HashSet<>(); + if(version.getStatus().equals(VersionStatus.Certified)) { + try { + optionalVersion = calculate(version.getName(), VersionCreationMethod.major); + if (!existingVersions.contains(optionalVersion)) { + optionalCreationMethods.add(VersionCreationMethod.major); + } + } catch (IllegalArgumentException iae) { + //not a valid creation method. + } + } + version.getAdditionalInfo().put("OptionalCreationMethods", optionalCreationMethods); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorFactoryImpl.java new file mode 100644 index 0000000000..155aa9c5e6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorFactoryImpl.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.versioning.impl; + +import org.openecomp.sdc.versioning.VersionCalculator; +import org.openecomp.sdc.versioning.VersionCalculatorFactory; + +public class VersionCalculatorFactoryImpl extends VersionCalculatorFactory { + private static final VersionCalculator INSTANCE = + new VersionCalculatorImpl(); + + @Override + public VersionCalculator createInterface() { + return INSTANCE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorImpl.java new file mode 100644 index 0000000000..b7008de867 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersionCalculatorImpl.java @@ -0,0 +1,155 @@ +package org.openecomp.sdc.versioning.impl; + +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.versioning.VersionCalculator; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.VersionCreationMethod; + +import java.util.HashSet; +import java.util.Set; + +public class VersionCalculatorImpl implements VersionCalculator { + + private static final String INITIAL_VERSION = "1.0"; + private static final String VERSION_STRING_VIOLATION_MSG = + "Version string must be in the format of: {integer}.{integer}"; + private static final String PARENT_LEVEL_VERSION_CANNOT_BE_CREATED_FROM_TOP_LEVEL = + "Creation of parent level version on top level version is invalid."; + private static final String SUB_LEVEL_VERSION_CANNOT_BE_CREATED_FROM_LOWEST_LEVEL = + "Creation of parent level version on top level version is invalid."; + + private static final String VERSION_CALCULATION_ERROR_MSG = + "Version calculation error."; + + private static final String INVALID_CREATION_METHOD_MSG = "Invalid creation method-"; + + + @Override + public String calculate(String baseVersion, VersionCreationMethod creationMethod) { + + if (baseVersion == null) { + return INITIAL_VERSION; + } + + String[] versionLevels = baseVersion.split("\\."); + if (versionLevels.length != 2) { + throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + } + + int index; + switch (creationMethod) { + case major: + index = Integer.parseInt(versionLevels[0]); + index++; + versionLevels[0] = Integer.toString(index); + versionLevels[1] = "0"; + break; + case minor: + index = Integer.parseInt(versionLevels[1]); + index++; + versionLevels[1] = Integer.toString(index); + break; + } + return CommonMethods.arrayToSeparatedString(versionLevels, '.'); + } + + + // version calculator when there are no version restrictions + /* @Override + public String calculate(String baseVersion, VersionCreationMethod creationMethod) { + + return calculate(baseVersion,creationMethod,2); + } + + private String calculate(String baseVersion, VersionCreationMethod creationMethod,int + maxVersionLevels) { + if (baseVersion == null) { + return INITIAL_VERSION; + } + + String[] versionLevels = baseVersion.split("\\."); + if (versionLevels.length > maxVersionLevels) { + throw new IllegalArgumentException(VERSION_STRING_VIOLATION_MSG); + } + + int index; + int versionLevel = calcVersionLevel(versionLevels); + if (versionLevel == -1) { + throw new IllegalArgumentException( + VERSION_STRING_VIOLATION_MSG + " given version:" + baseVersion); + } + int requiredVersionLevelIncrease; + switch (creationMethod) { + case parent_level: + if (versionLevel == 0) { + throw new IllegalArgumentException( + PARENT_LEVEL_VERSION_CANNOT_BE_CREATED_FROM_TOP_LEVEL + " version:" + baseVersion); + + } + requiredVersionLevelIncrease = versionLevel - 1; + versionLevels[versionLevel] = "0"; + index = Integer.getInteger(versionLevels[requiredVersionLevelIncrease]); + index++; + versionLevels[requiredVersionLevelIncrease] = Integer.toString(index); + break; + case same_level: + requiredVersionLevelIncrease = versionLevel; + index = Integer.valueOf(versionLevels[requiredVersionLevelIncrease]); + index++; + versionLevels[requiredVersionLevelIncrease] = Integer.toString(index); + break; + case sub_level: + if (versionLevel == versionLevels.length - 1) { + throw new IllegalArgumentException( + SUB_LEVEL_VERSION_CANNOT_BE_CREATED_FROM_LOWEST_LEVEL + " version:" + baseVersion); + } + requiredVersionLevelIncrease = versionLevel + 1; + if(requiredVersionLevelIncrease>maxVersionLevels){ + throw new IllegalArgumentException(INVALID_CREATION_METHOD_MSG+" max " + + "levels:"+maxVersionLevels + "requested level:"+requiredVersionLevelIncrease); + } + String newVersion = baseVersion + ".1"; + versionLevels = newVersion.split("\\."); + + break; + default: + throw new IllegalArgumentException(VERSION_CALCULATION_ERROR_MSG + " base " + + "version:" + baseVersion + " creation method:" + creationMethod); + + } + + return CommonMethods.arrayToSeparatedString(versionLevels, '.'); + }*/ + + + @Override + public void injectAdditionalInfo(Version version, Set<String> existingVersions) { + String optionalVersion; + Set<VersionCreationMethod> optionalCreationMethods = new HashSet<>(); + if(version.getStatus().equals(VersionStatus.Certified)) { + for (VersionCreationMethod versionCreationMethod : VersionCreationMethod.values()) { + try { + optionalVersion = calculate(version.getName(), versionCreationMethod); + if (!existingVersions.contains(optionalVersion)) { + optionalCreationMethods.add(versionCreationMethod); + } + } catch (IllegalArgumentException iae) { + //not a valid creation method. + } + } + } + version.getAdditionalInfo().put("OptionalCreationMethods", optionalCreationMethods); + + } + + + private int calcVersionLevel(String[] versionLevels) { + for (int i = versionLevels.length - 1; i >= 0; i--) { + if (!versionLevels[i].equals("0")) { + return i; + } + } + return -1; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerFactoryImpl.java index 8ab5c608bf..b4dbcf3a08 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerFactoryImpl.java @@ -20,16 +20,21 @@ package org.openecomp.sdc.versioning.impl; +import org.openecomp.sdc.versioning.ItemManagerFactory; +import org.openecomp.sdc.versioning.VersionCalculatorFactory; import org.openecomp.sdc.versioning.VersioningManager; import org.openecomp.sdc.versioning.VersioningManagerFactory; +import org.openecomp.sdc.versioning.dao.VersionDaoFactory; import org.openecomp.sdc.versioning.dao.VersionInfoDaoFactory; import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDaoFactory; public class VersioningManagerFactoryImpl extends VersioningManagerFactory { private static final VersioningManager INSTANCE = new VersioningManagerImpl( VersionInfoDaoFactory.getInstance().createInterface(), - VersionInfoDeletedDaoFactory.getInstance().createInterface() - ); + VersionInfoDeletedDaoFactory.getInstance().createInterface(), + VersionDaoFactory.getInstance().createInterface(), + VersionCalculatorFactory.getInstance().createInterface(), + ItemManagerFactory.getInstance().createInterface()); @Override public VersioningManager createInterface() { diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java index 4a49d5391f..7f983477cf 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/java/org/openecomp/sdc/versioning/impl/VersioningManagerImpl.java @@ -21,25 +21,31 @@ package org.openecomp.sdc.versioning.impl; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; import org.openecomp.sdc.logging.types.LoggerConstants; import org.openecomp.sdc.logging.types.LoggerErrorCode; import org.openecomp.sdc.logging.types.LoggerErrorDescription; import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.versioning.ItemManager; +import org.openecomp.sdc.versioning.VersionCalculator; import org.openecomp.sdc.versioning.VersioningManager; +import org.openecomp.sdc.versioning.dao.VersionDao; import org.openecomp.sdc.versioning.dao.VersionInfoDao; import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDao; import org.openecomp.sdc.versioning.dao.VersionableEntityDaoFactory; +import org.openecomp.sdc.versioning.dao.types.Revision; +import org.openecomp.sdc.versioning.dao.types.SynchronizationState; import org.openecomp.sdc.versioning.dao.types.UserCandidateVersion; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionHistoryEntity; import org.openecomp.sdc.versioning.dao.types.VersionInfoDeletedEntity; import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.sdc.versioning.dao.types.VersionType; -import org.openecomp.sdc.versioning.dao.types.VersionableEntityId; import org.openecomp.sdc.versioning.errors.CheckinOnEntityLockedByOtherErrorBuilder; import org.openecomp.sdc.versioning.errors.CheckinOnUnlockedEntityErrorBuilder; import org.openecomp.sdc.versioning.errors.CheckoutOnLockedEntityErrorBuilder; @@ -52,6 +58,7 @@ import org.openecomp.sdc.versioning.errors.EntityNotExistErrorBuilder; import org.openecomp.sdc.versioning.errors.SubmitLockedEntityNotAllowedErrorBuilder; import org.openecomp.sdc.versioning.errors.UndoCheckoutOnEntityLockedByOtherErrorBuilder; import org.openecomp.sdc.versioning.errors.UndoCheckoutOnUnlockedEntityErrorBuilder; +import org.openecomp.sdc.versioning.types.VersionCreationMethod; import org.openecomp.sdc.versioning.types.VersionInfo; import org.openecomp.sdc.versioning.types.VersionableEntityAction; import org.openecomp.sdc.versioning.types.VersionableEntityMetadata; @@ -66,18 +73,27 @@ import java.util.Set; import java.util.stream.Collectors; public class VersioningManagerImpl implements VersioningManager { - + private static final Logger LOGGER = LoggerFactory.getLogger(VersioningManagerImpl.class); private static final Version INITIAL_ACTIVE_VERSION = new Version(0, 0); private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); private static Map<String, Set<VersionableEntityMetadata>> versionableEntities = new HashMap<>(); - private VersionInfoDao versionInfoDao; - private VersionInfoDeletedDao versionInfoDeletedDao; + private final VersionInfoDao versionInfoDao; + private final VersionInfoDeletedDao versionInfoDeletedDao; + private VersionDao versionDao; + private VersionCalculator versionCalculator; + private ItemManager itemManager; public VersioningManagerImpl(VersionInfoDao versionInfoDao, - VersionInfoDeletedDao versionInfoDeletedDao) { + VersionInfoDeletedDao versionInfoDeletedDao, + VersionDao versionDao, + VersionCalculator versionCalculator, + ItemManager itemManager) { this.versionInfoDao = versionInfoDao; this.versionInfoDeletedDao = versionInfoDeletedDao; + this.versionDao = versionDao; + this.versionCalculator = versionCalculator; + this.itemManager = itemManager; } private static VersionInfo getVersionInfo(VersionInfoEntity versionInfoEntity, String user, @@ -146,8 +162,12 @@ public class VersioningManagerImpl implements VersioningManager { VersionInfo versionInfo = new VersionInfo(); versionInfo.setStatus(status); activeVersion.setStatus(status); - if(latestFinalVersion!= null) latestFinalVersion.setStatus(status); - if(viewableVersions != null) viewableVersions.forEach(version->version.setStatus(status)); + if (latestFinalVersion != null) { + latestFinalVersion.setStatus(status); + } + if (viewableVersions != null) { + viewableVersions.forEach(version -> version.setStatus(status)); + } versionInfo.setActiveVersion(activeVersion); versionInfo.setLatestFinalVersion(latestFinalVersion); versionInfo.setViewableVersions(toSortedList(viewableVersions)); @@ -166,11 +186,9 @@ public class VersioningManagerImpl implements VersioningManager { private static List<Version> toSortedList( Set<Version> versions) { // changing the Set to List in DB will require migration... - return versions.stream().sorted((o1, o2) -> { - return o1.getMajor() > o2.getMajor() ? 1 - : o1.getMajor() == o2.getMajor() ? (o1.getMinor() > o2.getMinor() ? 1 - : o1.getMinor() == o2.getMinor() ? 0 : -1) : -1; - }).collect(Collectors.toList()); + return versions.stream().sorted((o1, o2) -> o1.getMajor() > o2.getMajor() ? 1 + : o1.getMajor() == o2.getMajor() ? (o1.getMinor() > o2.getMinor() ? 1 + : o1.getMinor() == o2.getMinor() ? 0 : -1) : -1).collect(Collectors.toList()); } private static List<Version> getFinalVersions(Set<Version> versions) { @@ -263,8 +281,8 @@ public class VersioningManagerImpl implements VersioningManager { LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't checkout versionable entity"); throw new CoreException(new CheckoutOnLockedEntityErrorBuilder(entityType, entityId, versionInfoEntity.getCandidate().getUser()).build()); - case Final: - case Available: + case Certified: + case Draft: checkoutVersion = doCheckout(versionInfoEntity, user); break; default: @@ -300,8 +318,8 @@ public class VersioningManagerImpl implements VersioningManager { } activeVersion = undoCheckout(versionInfoEntity); break; - case Final: - case Available: + case Certified: + case Draft: MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.UNDO_CHECKOUT_ENTITY, ErrorLevel.ERROR.name(), LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), @@ -320,8 +338,9 @@ public class VersioningManagerImpl implements VersioningManager { deleteVersionFromEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), versionInfoEntity.getCandidate().getVersion(), versionInfoEntity.getActiveVersion()); - versionInfoEntity.setStatus(versionInfoEntity.getActiveVersion().isFinal() ? VersionStatus.Final - : VersionStatus.Available); + versionInfoEntity + .setStatus(versionInfoEntity.getActiveVersion().isFinal() ? VersionStatus.Certified + : VersionStatus.Draft); versionInfoEntity.setCandidate(null); versionInfoDao.update(versionInfoEntity); return versionInfoEntity.getActiveVersion(); @@ -341,8 +360,8 @@ public class VersioningManagerImpl implements VersioningManager { Version checkedInVersion = null; switch (versionInfoEntity.getStatus()) { - case Available: - case Final: + case Draft: + case Certified: MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.CHECKIN_ENTITY, ErrorLevel.ERROR.name(), LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't checkin versionable entity"); @@ -379,7 +398,7 @@ public class VersioningManagerImpl implements VersioningManager { Version submitVersion = null; switch (versionInfoEntity.getStatus()) { - case Final: + case Certified: MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), "Can't submit versionable entity"); @@ -391,7 +410,7 @@ public class VersioningManagerImpl implements VersioningManager { LoggerErrorCode.PERMISSION_ERROR.getErrorCode(), "Can't submit versionable entity"); throw new CoreException(new SubmitLockedEntityNotAllowedErrorBuilder(entityType, entityId, versionInfoEntity.getCandidate().getUser()).build()); - case Available: + case Draft: submitVersion = doSubmit(versionInfoEntity, user, submitDescription); break; default: @@ -444,6 +463,143 @@ public class VersioningManagerImpl implements VersioningManager { return activeVersions; } + @Override + public List<Version> list(String itemId) { + + List<Version> versions = versionDao.list(itemId); + Set<String> versionsNames = versions.stream().map(Version::getName).collect(Collectors.toSet()); + versions.forEach(version -> { + version.setAdditionalInfo(new HashMap<>()); + versionCalculator.injectAdditionalInfo(version, versionsNames); + }); + return versions; + } + + @Override + public Version get(String itemId, Version version) { + return versionDao.get(itemId, version) + .map(retrievedVersion -> getUpdateRetrievedVersion(itemId, retrievedVersion)) + .orElseGet(() -> getSyncedVersion(itemId, version)); + } + + private Version getUpdateRetrievedVersion(String itemId, Version version) { + if (version.getStatus() == VersionStatus.Certified && + (version.getState().getSynchronizationState() == SynchronizationState.OutOfSync || + version.getState().isDirty())) { + forceSync(itemId, version); + LOGGER.info("Item Id {}, version Id {}: Force sync is done", itemId, version.getId()); + version = versionDao.get(itemId, version) + .orElseThrow(() -> new IllegalStateException( + "Get version after a successful force sync must return the version")); + } + return version; + } + + private Version getSyncedVersion(String itemId, Version version) { + sync(itemId, version); + LOGGER.info("Item Id {}, version Id {}: First time sync is done", itemId, version.getId()); + return versionDao.get(itemId, version) + .orElseThrow(() -> new IllegalStateException( + "Get version after a successful sync must return the version")); + } + + @Override + public Version create(String itemId, Version version, VersionCreationMethod creationMethod) { + String baseVersionName = null; + if (version.getBaseId() == null) { + version.setDescription("Initial version"); + } else { + baseVersionName = get(itemId, new Version(version.getBaseId())).getName(); + } + String versionName = versionCalculator.calculate(baseVersionName, creationMethod); + validateVersionName(itemId, versionName); + version.setName(versionName); + + versionDao.create(itemId, version); + itemManager.updateVersionStatus(itemId, VersionStatus.Draft, null); + + publish(itemId, version, String.format("Initial version: %s ", version.getName())); + return version; + } + + private void validateVersionName(String itemId, String versionName) { + if (versionDao.list(itemId).stream() + .anyMatch(version -> versionName.equals(version.getName()))) { + String errorDescription = String + .format("Item %s: create version failed, a version with the name %s already exist", + itemId, versionName); + + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY, + LoggerTragetServiceName.CREATE_VERSION, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), errorDescription); + + throw new CoreException(new ErrorCode.ErrorCodeBuilder() + .withCategory(ErrorCategory.APPLICATION) + .withId("VERSION_NAME_ALREADY_EXIST") + .withMessage(errorDescription) + .build()); + } + } + + @Override + public void submit(String itemId, Version version, String submitDescription) { + version = get(itemId, version); + + validateSubmit(itemId, version); + + version.setStatus(VersionStatus.Certified); + versionDao.update(itemId, version); + + publish(itemId, version, submitDescription); + + itemManager.updateVersionStatus(itemId, VersionStatus.Certified, VersionStatus.Draft); + } + + private void validateSubmit(String itemId, Version version) { + if (version.getStatus() == VersionStatus.Certified) { + String errorDescription = String + .format("Item %s: submit version failed, version %s is already Certified", itemId, + version.getId()); + + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.SUBMIT_ENTITY, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), errorDescription); + + throw new CoreException(new ErrorCode.ErrorCodeBuilder() + .withCategory(ErrorCategory.APPLICATION) + .withId("VERSION_ALREADY_CERTIFIED") + .withMessage(errorDescription) + .build()); + } + } + + @Override + public void publish(String itemId, Version version, String message) { + versionDao.publish(itemId, version, message); + } + + + @Override + public void sync(String itemId, Version version) { + versionDao.sync(itemId, version); + } + + @Override + public void forceSync(String itemId, Version version) { + versionDao.forceSync(itemId, version); + } + + @Override + public void revert(String itemId, Version version, String revisionId) { + versionDao.revert(itemId, version, revisionId); + } + + @Override + public List<Revision> listRevisions(String itemId, Version version) { + return versionDao.listRevisions(itemId, version); + + } + private void markAsCheckedOut(VersionInfoEntity versionInfoEntity, String checkingOutUser) { versionInfoEntity.setStatus(VersionStatus.Locked); versionInfoEntity.setCandidate(new UserCandidateVersion(checkingOutUser, @@ -491,7 +647,7 @@ public class VersioningManagerImpl implements VersioningManager { versionInfoEntity.setCandidate(null); versionInfoEntity.setActiveVersion(userCandidateVersion.getVersion()); versionInfoEntity.getViewableVersions().add(versionInfoEntity.getActiveVersion()); - versionInfoEntity.setStatus(VersionStatus.Available); + versionInfoEntity.setStatus(VersionStatus.Draft); closeVersionOnEntity(versionInfoEntity.getEntityType(), versionInfoEntity.getEntityId(), versionInfoEntity.getActiveVersion()); @@ -519,22 +675,12 @@ public class VersioningManagerImpl implements VersioningManager { versionInfoEntity.setViewableVersions(viewableVersions); versionInfoEntity.setActiveVersion(finalVersion); versionInfoEntity.setLatestFinalVersion(finalVersion); - versionInfoEntity.setStatus(VersionStatus.Final); + versionInfoEntity.setStatus(VersionStatus.Certified); versionInfoDao.update(versionInfoEntity); return finalVersion; } - private void createVersionHistory(VersionableEntityId entityId, Version version, String user, - String description, VersionType type) { - VersionHistoryEntity versionHistory = new VersionHistoryEntity(entityId); - versionHistory.setVersion(version); - versionHistory.setUser(user); - versionHistory.setDescription(description); - versionHistory.setType(type); - //versionHistoryDao.create(versionHistory); - } - private void initVersionOnEntity(String entityType, String entityId, Version baseVersion, Version newVersion) { Set<VersionableEntityMetadata> entityMetadatas = versionableEntities.get(entityType); diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/resources/factoryConfiguration.json b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/resources/factoryConfiguration.json new file mode 100644 index 0000000000..d2d16eff37 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/main/resources/factoryConfiguration.json @@ -0,0 +1,3 @@ +{ + "org.openecomp.sdc.versioning.VersionCalculatorFactory": "org.openecomp.sdc.versioning.impl.MajorVersionCalculatorFactoryImpl" +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImplTest.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImplTest.java new file mode 100644 index 0000000000..1f1efdf6cb --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/dao/impl/zusammen/VersionZusammenDaoImplTest.java @@ -0,0 +1,265 @@ +package org.openecomp.sdc.versioning.dao.impl.zusammen; + +import com.amdocs.zusammen.datatypes.Id; +import com.amdocs.zusammen.datatypes.SessionContext; +import com.amdocs.zusammen.datatypes.UserInfo; +import com.amdocs.zusammen.datatypes.item.Info; +import com.amdocs.zusammen.datatypes.item.ItemVersion; +import com.amdocs.zusammen.datatypes.item.ItemVersionData; +import com.amdocs.zusammen.datatypes.item.ItemVersionStatus; +import com.amdocs.zusammen.datatypes.item.SynchronizationStatus; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.core.zusammen.api.ZusammenAdaptor; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.versioning.dao.types.Version; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isNull; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.verify; + +public class VersionZusammenDaoImplTest { + + private static final String USER = "user1"; + @Mock + private ZusammenAdaptor zusammenAdaptorMock; + @InjectMocks + private VersionZusammenDaoImpl versionDao; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + SessionContextProviderFactory.getInstance().createInterface().create(USER); + } + + @Test + public void testList() throws Exception { + String itemId = "itemId"; + Id versionId1 = new Id("v1_id"); + Id versionId2 = new Id("v2_id"); + Id versionId3 = new Id("v3_id"); + + List<ItemVersion> zusammenVersions = Stream.of( + createZusammenVersion(versionId1, null, "version desc", "1.0", VersionStatus.Certified), + createZusammenVersion(versionId2, versionId1, "version desc", "2.0", VersionStatus.Certified + ), + createZusammenVersion(versionId3, versionId2, "version desc", "3.0", VersionStatus.Draft)) + .collect(Collectors.toList()); + doReturn(zusammenVersions).when(zusammenAdaptorMock) + .listPublicVersions(eq(createZusammenContext()), eq(new Id(itemId))); + + List<Version> versions = versionDao.list(itemId); + Assert.assertEquals(versions.size(), 3); + + int zusammenVersionIndex; + for (Version version : versions) { + zusammenVersionIndex = versionId1.getValue().equals(version.getId()) + ? 0 + : versionId2.getValue().equals(version.getId()) + ? 1 + : 2; + assetVersionEquals(version, zusammenVersions.get(zusammenVersionIndex)); + } + } + + @Test + public void testCreate() throws Exception { + testCreate(null); + } + + @Test + public void testCreateBasedOn() throws Exception { + testCreate("baseId"); + } + + private void testCreate(String baseId) { + String itemId = "itemId"; + Version version = new Version(1, 0); + version.setBaseId(baseId); + version.setName("version name"); + version.setDescription("version description"); + version.setStatus(VersionStatus.Draft); + + doReturn(new Id("versionId")).when(zusammenAdaptorMock) + .createVersion(eq(createZusammenContext()), eq(new Id(itemId)), + baseId == null ? isNull(Id.class) : eq(new Id(baseId)), any(ItemVersionData.class)); + + ArgumentCaptor<ItemVersionData> capturedZusammenVersion = + ArgumentCaptor.forClass(ItemVersionData.class); + + versionDao.create(itemId, version); + + verify(zusammenAdaptorMock) + .createVersion(eq(createZusammenContext()), eq(new Id(itemId)), + baseId == null ? isNull(Id.class) : eq(new Id(baseId)), + capturedZusammenVersion.capture()); + + Info capturedInfo = capturedZusammenVersion.getValue().getInfo(); + Assert.assertEquals(capturedInfo.getName(), version.getName()); + Assert.assertEquals(capturedInfo.getDescription(), version.getDescription()); + Assert.assertEquals(VersionStatus + .valueOf(capturedInfo.getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS)), + version.getStatus()); + Assert.assertEquals(capturedInfo.getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL), + version.toString()); + } + + @Test + public void testUpdate() throws Exception { + String itemId = "itemId"; + Version version = new Version(1, 0); + version.setId("versionId"); + version.setBaseId("baseId"); + version.setName("version name"); + version.setDescription("version description"); + version.setStatus(VersionStatus.Certified); + + ArgumentCaptor<ItemVersionData> capturedZusammenVersion = + ArgumentCaptor.forClass(ItemVersionData.class); + + versionDao.update(itemId, version); + + verify(zusammenAdaptorMock) + .updateVersion(eq(createZusammenContext()), eq(new Id(itemId)), eq(new Id(version.getId())), + capturedZusammenVersion.capture()); + + Info capturedInfo = capturedZusammenVersion.getValue().getInfo(); + Assert.assertEquals(capturedInfo.getName(), version.getName()); + Assert.assertEquals(capturedInfo.getDescription(), version.getDescription()); + Assert.assertEquals(VersionStatus + .valueOf(capturedInfo.getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS)), + version.getStatus()); + Assert.assertEquals(capturedInfo.getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL), + version.toString()); + } + + @Test + public void testGetNonExisting() throws Exception { + Optional<Version> version = versionDao.get("itemId", new Version("versionId")); + + Assert.assertEquals(version, Optional.empty()); + } + + @Test + public void testGet() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + + SessionContext zusammenContext = createZusammenContext(); + Id itemIdObj = new Id(itemId); + Id versionIdObj = new Id(versionId); + + ItemVersion zusammenPrivateVersion = + createZusammenVersion(versionIdObj, new Id("baseId"), "version desc updated", "2.0", + VersionStatus.Draft); + doReturn(zusammenPrivateVersion).when(zusammenAdaptorMock) + .getVersion(eq(zusammenContext), eq(itemIdObj), eq(versionIdObj)); + + doReturn(new ItemVersionStatus(SynchronizationStatus.UP_TO_DATE, true)) + .when(zusammenAdaptorMock) + .getVersionStatus(eq(zusammenContext), eq(itemIdObj), eq(versionIdObj)); + + ItemVersion zusammenPublicVersion = + createZusammenVersion(versionIdObj, new Id("baseId"), "version desc", "2.0", + VersionStatus.Certified); + doReturn(zusammenPublicVersion).when(zusammenAdaptorMock) + .getPublicVersion(eq(zusammenContext), eq(itemIdObj), eq(versionIdObj)); + + Optional<Version> version = versionDao.get(itemId, new Version(versionId)); + + Assert.assertTrue(version.isPresent()); + zusammenPrivateVersion.getData().getInfo() + .addProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS, + VersionStatus.Certified.name()); + assetVersionEquals(version.get(), zusammenPrivateVersion); + } + + // TODO: 12/20/2017 complete tests + /* @Test + public void testDelete() throws Exception { + + } + + @Test + public void testPublish() throws Exception { + + } + + @Test + public void testSync() throws Exception { + + } + + @Test + public void testForceSync() throws Exception { + + } + + @Test + public void testRevert() throws Exception { + + } + + @Test + public void testListRevisions() throws Exception { + + }*/ + + private void assetVersionEquals(Version version, ItemVersion zusammenVersion) { + Assert.assertEquals(version.getId(), zusammenVersion.getId().getValue()); + Assert.assertEquals(version.getBaseId(), + zusammenVersion.getBaseId() == null ? null : zusammenVersion.getBaseId().getValue()); + Info info = zusammenVersion.getData().getInfo(); + Assert.assertEquals(version.getName(), info.getName()); + Assert.assertEquals(version.getDescription(), info.getDescription()); + Assert.assertEquals(version.getStatus(), + VersionStatus.valueOf(info.getProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS))); + String label = info.getProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL).toString(); + Assert + .assertEquals(version.getMajor(), Integer.parseInt(label.substring(0, label.indexOf('.')))); + Assert.assertEquals(version.getMinor(), + Integer.parseInt(label.substring(label.indexOf('.') + 1, label.length()))); + Assert.assertEquals(version.getCreationTime(), zusammenVersion.getCreationTime()); + Assert.assertEquals(version.getModificationTime(), zusammenVersion.getModificationTime()); + } + + private ItemVersion createZusammenVersion(Id id, Id baseId, String description, String label, + VersionStatus status) { + ItemVersion version = new ItemVersion(); + version.setId(id); + version.setBaseId(baseId); + Info info = new Info(); + info.setName(id + "_name"); + info.setDescription(description); + info.addProperty(VersionZusammenDaoImpl.ZusammenProperty.LABEL, label); + info.addProperty(VersionZusammenDaoImpl.ZusammenProperty.STATUS, status.name()); + ItemVersionData data = new ItemVersionData(); + data.setInfo(info); + version.setData(data); + version.setCreationTime(new Date()); + version.setModificationTime(new Date()); + return version; + } + + private SessionContext createZusammenContext() { + SessionContext sessionContext = new SessionContext(); + sessionContext.setUser(new UserInfo(USER)); + sessionContext.setTenant("dox"); + return sessionContext; + } + +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/ItemManagerImplTest.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/ItemManagerImplTest.java new file mode 100644 index 0000000000..755bfb4442 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/ItemManagerImplTest.java @@ -0,0 +1,124 @@ +package org.openecomp.sdc.versioning.impl; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.openecomp.sdc.common.session.SessionContextProviderFactory; +import org.openecomp.sdc.itempermissions.PermissionsServices; +import org.openecomp.sdc.notification.services.SubscriptionService; +import org.openecomp.sdc.versioning.dao.ItemDao; +import org.openecomp.sdc.versioning.dao.types.VersionStatus; +import org.openecomp.sdc.versioning.types.Item; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Collection; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +public class ItemManagerImplTest { + + @Mock + private ItemDao itemDao; + @Mock + private PermissionsServices permissionsServices; + @Mock + private SubscriptionService subscriptionService; + @InjectMocks + private ItemManagerImpl itemManager; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testList() throws Exception { + doReturn(Stream.of( + createItem("item1", "A"), + createItem("item2", "B"), + createItem("item3", "B"), + createItem("item4", "A")) + .collect(Collectors.toList())).when(itemDao).list(); + + Collection<Item> items = itemManager.list(item -> "B".equals(item.getType())); + Assert.assertEquals(items.size(), 2); + Assert.assertTrue(items.stream().anyMatch(item -> "item2".equals(item.getName()))); + Assert.assertTrue(items.stream().anyMatch(item -> "item3".equals(item.getName()))); + } + + @Test + public void testGetNotExisting() throws Exception { + Item item = itemManager.get("item1"); + Assert.assertNull(item); + } + + @Test + public void testGet() throws Exception { + Item toBeReturned = new Item(); + toBeReturned.setId("itemId"); + doReturn(toBeReturned).when(itemDao).get(any(Item.class)); + + Item item = itemManager.get("itemId"); + Assert.assertEquals(item.getId(), "itemId"); + } + + @Test + public void testCreate() throws Exception { + SessionContextProviderFactory.getInstance().createInterface().create("user1"); + + Item toBeReturned = new Item(); + toBeReturned.setId("itemId"); + doReturn(toBeReturned).when(itemDao).create(any(Item.class)); + + Item item = itemManager.create(createItem("item1", "A")); + Assert.assertEquals(item.getId(), "itemId"); + } + + @Test + public void testUpdateNotExistingVersionStatus() throws Exception { + itemManager.updateVersionStatus("itemId", VersionStatus.Certified, VersionStatus.Draft); + verify(itemDao, never()).update(any(Item.class)); + } + + @Test + public void testUpdateVersionStatusWhenNone() throws Exception { + Item item = new Item(); + item.setId("itemId"); + doReturn(item).when(itemDao).get(any(Item.class)); + + itemManager.updateVersionStatus("itemId", VersionStatus.Certified, VersionStatus.Draft); + verify(itemDao).update(item); + Assert.assertEquals(item.getVersionStatusCounters().get(VersionStatus.Certified).intValue(), 1); + Assert.assertNull(item.getVersionStatusCounters().get(VersionStatus.Draft)); + } + + @Test + public void testUpdateVersionStatus() throws Exception { + Item item = new Item(); + item.setId("itemId"); + item.getVersionStatusCounters().put(VersionStatus.Certified, 2); + item.getVersionStatusCounters().put(VersionStatus.Draft, 5); + doReturn(item).when(itemDao).get(any(Item.class)); + + itemManager.updateVersionStatus("itemId", VersionStatus.Certified, VersionStatus.Draft); + verify(itemDao).update(item); + Assert.assertEquals(item.getVersionStatusCounters().get(VersionStatus.Certified).intValue(), 3); + Assert.assertEquals(item.getVersionStatusCounters().get(VersionStatus.Draft).intValue(), 4); + } + + private Item createItem(String name, String type) { + Item item = new Item(); + item.setId(name); + item.setName(name); + item.setType(type); + return item; + } + +}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/VersioningManagerImplTest.java b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/VersioningManagerImplTest.java index d35de4f3d1..2d1109abe6 100644 --- a/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/VersioningManagerImplTest.java +++ b/openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-core/src/test/java/org/openecomp/sdc/versioning/impl/VersioningManagerImplTest.java @@ -21,39 +21,326 @@ package org.openecomp.sdc.versioning.impl; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.verify; - import org.mockito.ArgumentCaptor; -import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.versioning.dao.VersionInfoDao; -import org.openecomp.sdc.versioning.dao.VersionInfoDeletedDao; -import org.openecomp.sdc.versioning.dao.types.UserCandidateVersion; +import org.openecomp.sdc.versioning.ItemManager; +import org.openecomp.sdc.versioning.VersionCalculator; +import org.openecomp.sdc.versioning.dao.VersionDao; +import org.openecomp.sdc.versioning.dao.types.Revision; +import org.openecomp.sdc.versioning.dao.types.SynchronizationState; import org.openecomp.sdc.versioning.dao.types.Version; -import org.openecomp.sdc.versioning.dao.types.VersionInfoDeletedEntity; -import org.openecomp.sdc.versioning.dao.types.VersionInfoEntity; +import org.openecomp.sdc.versioning.dao.types.VersionState; import org.openecomp.sdc.versioning.dao.types.VersionStatus; -import org.openecomp.sdc.versioning.types.VersionInfo; -import org.openecomp.sdc.versioning.types.VersionableEntityAction; +import org.openecomp.sdc.versioning.types.VersionCreationMethod; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.openecomp.sdc.versioning.dao.types.SynchronizationState.OutOfSync; +import static org.openecomp.sdc.versioning.dao.types.SynchronizationState.UpToDate; +import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Certified; +import static org.openecomp.sdc.versioning.dao.types.VersionStatus.Draft; public class VersioningManagerImplTest { + @Mock + private VersionDao versionDaoMock; + @Mock + private VersionCalculator versionCalculatorMock; + @Mock + private ItemManager itemManagerMock; + @InjectMocks + private VersioningManagerImpl versioningManager; + + @BeforeMethod + public void setUp() throws Exception { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testList() throws Exception { + String itemId = "itemId"; + + List<Version> returnedVersions = Stream.of(createVersion("1", null, null, false), + createVersion("2", null, null, false), + createVersion("3", null, null, false)).collect(Collectors.toList()); + doReturn(returnedVersions).when(versionDaoMock).list(itemId); + + List<Version> versions = versioningManager.list(itemId); + Assert.assertEquals(versions, returnedVersions); + } + + @Test(expectedExceptions = Exception.class) + public void testGetNonExisting() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + doReturn(Optional.empty()).when(versionDaoMock).get(itemId, version); + doThrow(new Exception()).when(versionDaoMock).sync(itemId, version); + + versioningManager.get(itemId, version); + } + + @Test + public void testGetNonExistingForUser() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version requestedVersion = new Version(versionId); + + Version returnedVersion = createVersion(versionId, Draft, UpToDate, false); + doReturn(Optional.empty()).doReturn(Optional.of(returnedVersion)) + .when(versionDaoMock).get(itemId, requestedVersion); + + Version version = versioningManager.get(itemId, requestedVersion); + Assert.assertEquals(version, returnedVersion); + + verify(versionDaoMock, times(2)).get(itemId, requestedVersion); + verify(versionDaoMock).sync(itemId, requestedVersion); + } + + @Test + public void testGetOutOfSyncCertified() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version requestedVersion = new Version(versionId); + + Version returnedVersion = createVersion(versionId, Certified, UpToDate, false); + doReturn(Optional.of(createVersion(versionId, Certified, OutOfSync, false))) + .doReturn(Optional.of(returnedVersion)) + .when(versionDaoMock).get(itemId, requestedVersion); + + Version version = versioningManager.get(itemId, requestedVersion); + Assert.assertEquals(version, returnedVersion); + + verify(versionDaoMock, times(2)).get(itemId, requestedVersion); + verify(versionDaoMock).forceSync(itemId, requestedVersion); + } + + @Test + public void testGet() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version requestedVersion = new Version(versionId); + + Version returnedVersion = createVersion(versionId, Draft, OutOfSync, true); + doReturn(Optional.of(returnedVersion)).when(versionDaoMock).get(itemId, requestedVersion); + + Version version = versioningManager.get(itemId, requestedVersion); + Assert.assertEquals(version, returnedVersion); + + verify(versionDaoMock).get(itemId, requestedVersion); + verify(versionDaoMock, never()).sync(any(), any()); + verify(versionDaoMock, never()).forceSync(any(), any()); + } + + @Test + public void testCreate() throws Exception { + String itemId = "itemId"; + Version requestedVersion = new Version(); + + String versionName = "versionName"; + doReturn(versionName).when(versionCalculatorMock).calculate(null, VersionCreationMethod.major); + + doReturn(Stream.of(createVersion("1", null, null, false), + createVersion("2", null, null, false), + createVersion("3", null, null, false)).collect(Collectors.toList())) + .when(versionDaoMock).list(itemId); + + Version version = + versioningManager.create(itemId, requestedVersion, VersionCreationMethod.major); + Assert.assertNotNull(version); + Assert.assertEquals(version.getName(), versionName); + + verify(versionDaoMock).create(itemId, requestedVersion); + verify(itemManagerMock).updateVersionStatus(itemId, Draft, null); + verify(versionDaoMock).publish(eq(itemId), eq(requestedVersion), anyString()); + } + + @Test + public void testCreateBasedOn() throws Exception { + String itemId = "itemId"; + Version requestedVersion = new Version(); + requestedVersion.setBaseId("baseVersionId"); + + Version baseVersion = createVersion(requestedVersion.getBaseId(), Certified, UpToDate, false); + // TODO: 12/13/2017 fix to eq(new Version("baseVersionId")) when version.equals will be fixed + doReturn(Optional.of(baseVersion)).when(versionDaoMock).get(eq(itemId), any(Version.class)); + + String versionName = "4.0"; + doReturn(versionName) + .when(versionCalculatorMock).calculate(baseVersion.getName(), VersionCreationMethod.major); + + doReturn(Stream.of(createVersion("1", null, null, false), + createVersion("2", null, null, false), + createVersion("3", null, null, false)).collect(Collectors.toList())) + .when(versionDaoMock).list(itemId); + + Version version = + versioningManager.create(itemId, requestedVersion, VersionCreationMethod.major); + Assert.assertNotNull(version); + Assert.assertEquals(version.getName(), versionName); + + verify(versionDaoMock).create(itemId, requestedVersion); + verify(itemManagerMock).updateVersionStatus(itemId, Draft, null); + verify(versionDaoMock).publish(eq(itemId), eq(requestedVersion), anyString()); + } + + @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = + "Item itemId: create version failed, a version with the name 2.0 already exist") + public void testCreateWithExistingName() throws Exception { + String itemId = "itemId"; + Version version = new Version(); + version.setBaseId("baseVersionId"); + + Version baseVersion = createVersion(version.getBaseId(), Certified, UpToDate, false); + // TODO: 12/13/2017 fix to eq(new Version("baseVersionId")) when version.equals will be fixed + doReturn(Optional.of(baseVersion)).when(versionDaoMock).get(eq(itemId), any(Version.class)); + + String versionName = "2.0"; + doReturn(versionName) + .when(versionCalculatorMock).calculate(baseVersion.getName(), VersionCreationMethod.major); + + doReturn(Stream.of(createVersion("1", null, null, false), + createVersion("2", null, null, false), + createVersion("3", null, null, false)).collect(Collectors.toList())) + .when(versionDaoMock).list(itemId); + + versioningManager.create(itemId, version, VersionCreationMethod.major); + } + + @Test(expectedExceptions = CoreException.class, expectedExceptionsMessageRegExp = + "Item itemId: submit version failed, version versionId is already Certified") + public void testSubmitCertified() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + Version returnedVersion = createVersion(versionId, Certified, UpToDate, false); + doReturn(Optional.of(returnedVersion)).when(versionDaoMock).get(itemId, version); + + versioningManager.submit(itemId, version, "Submit message"); + } + + @Test + public void testSubmit() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + ArgumentCaptor<Version> versionArgumentCaptor = ArgumentCaptor.forClass(Version.class); + + Version returnedVersion = createVersion(versionId, Draft, UpToDate, false); + doReturn(Optional.of(returnedVersion)).when(versionDaoMock).get(itemId, version); + + String submitDescription = "Submit message"; + versioningManager.submit(itemId, version, submitDescription); + + verify(versionDaoMock).update(eq(itemId), versionArgumentCaptor.capture()); + Assert.assertEquals(Certified, versionArgumentCaptor.getValue().getStatus()); + verify(versionDaoMock).publish(itemId, version, submitDescription); + verify(itemManagerMock).updateVersionStatus(itemId, Certified, Draft); + } + + @Test + public void testPublish() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + String publishDescription = "Publish message"; + + versioningManager.publish(itemId, version, publishDescription); + + verify(versionDaoMock).publish(itemId, version, publishDescription); + } + + @Test + public void testSync() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + versioningManager.sync(itemId, version); + + verify(versionDaoMock).sync(itemId, version); + } + + @Test + public void testForceSync() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + versioningManager.forceSync(itemId, version); + + verify(versionDaoMock).forceSync(itemId, version); + } + + @Test + public void testRevert() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + String revisionId = "revisionId"; + + versioningManager.revert(itemId, version, revisionId); + + verify(versionDaoMock).revert(itemId, version, revisionId); + } + + @Test + public void testListRevisions() throws Exception { + String itemId = "itemId"; + String versionId = "versionId"; + Version version = new Version(versionId); + + List<Revision> returnedRevisions = + Stream.of(new Revision(), new Revision()).collect(Collectors.toList()); + doReturn(returnedRevisions) + .when(versionDaoMock).listRevisions(itemId, version); + + List<Revision> revisions = versioningManager.listRevisions(itemId, version); + Assert.assertEquals(revisions, returnedRevisions); + } + + private Version createVersion(String id, VersionStatus status, + SynchronizationState syncState, boolean dirty) { + Version version = new Version(id); + version.setName(id + ".0"); + version.setDescription(id + " desc"); + version.setStatus(status); + + VersionState state = new VersionState(); + state.setSynchronizationState(syncState); + state.setDirty(dirty); + version.setState(state); + return version; + } + +/* private static final String USR1 = "usr1"; private static final String USR2 = "usr2"; private static final String TYPE1 = "Type1"; -/* private static final String TYPE2 = "Type2";*/ +*/ +/* private static final String TYPE2 = "Type2";*//* + private static final String ID1 = "Id1"; +*/ /* private static final String ID2 = "Id2"; private static final String ID3 = "Id3"; private static final String TYPE1_TABLE_NAME = "vendor_license_model"; @@ -61,17 +348,20 @@ public class VersioningManagerImplTest { private static final String TYPE1_VERSION_NAME = "version"; private static final String TYPE2_TABLE_NAME = "feature_group"; private static final String TYPE2_ID_NAME = "vlm_id"; - private static final String TYPE2_VERSION_NAME = "version";*/ + private static final String TYPE2_VERSION_NAME = "version";*//* + private static final Version VERSION0 = new Version(0, 0); private static final Version VERSION01 = new Version(0, 1); private static final Version VERSION02 = new Version(0, 2); private static final Version VERSION10 = new Version(1, 0); private static final Version VERSION11 = new Version(1, 1); - /* private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); + */ +/* private static final NoSqlDb noSqlDb = NoSqlDbFactory.getInstance().createInterface(); private static UDTMapper<Version> versionMapper = - noSqlDb.getMappingManager().udtMapper(Version.class);*/ + noSqlDb.getMappingManager().udtMapper(Version.class);*//* + @Mock private VersionInfoDao versionInfoDaoMock; @Mock @@ -87,7 +377,8 @@ public class VersioningManagerImplTest { MockitoAnnotations.initMocks(this); } - /* @BeforeClass + */ +/* @BeforeClass private void init() { versionInfoDaoMock.delete(new VersionInfoEntity(TYPE1, ID1)); versionInfoDaoMock.delete(new VersionInfoEntity(TYPE1, ID2)); @@ -103,8 +394,10 @@ public class VersioningManagerImplTest { new VersionableEntityMetadata(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME)); versioningManager.register(TYPE2, new VersionableEntityMetadata(TYPE2_TABLE_NAME, TYPE2_ID_NAME, TYPE2_VERSION_NAME)); - }*/ + }*//* + +*/ /* @Test public void testRegister() throws Exception { VersionableEntityMetadata entityMetadata = @@ -116,7 +409,8 @@ public class VersioningManagerImplTest { Set<VersionableEntityMetadata> type1Entities = versionableEntities.get(TYPE1); Assert.assertNotNull(type1Entities); Assert.assertTrue(type1Entities.contains(entityMetadata)); - }*/ + }*//* + @Test(expectedExceptions = CoreException.class) public void testCreateAlreadyExisting() { @@ -129,8 +423,10 @@ public class VersioningManagerImplTest { Version version = versioningManager.create(TYPE1, ID1, USR1); Assert.assertEquals(version, VERSION01); +*/ /* createVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, - version);*/ + version);*//* + verify(versionInfoDaoMock).create(versionInfoEntityArg.capture()); VersionInfoEntity versionInfoEntity = versionInfoEntityArg.getValue(); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, new Version(0, 0), VERSION01, USR1, @@ -152,7 +448,7 @@ public class VersioningManagerImplTest { @Test public void testDelete() { VersionInfoEntity versionInfoEntity = new VersionInfoEntity(); - versionInfoEntity.setStatus(VersionStatus.Available); + versionInfoEntity.setStatus(VersionStatus.Draft); doReturn(versionInfoEntity).when(versionInfoDaoMock).get(anyObject()); versioningManager.delete(TYPE1, ID1, USR1); @@ -171,13 +467,14 @@ public class VersioningManagerImplTest { @Test public void testUndoDelete() { VersionInfoDeletedEntity versionInfoDeletedEntity = new VersionInfoDeletedEntity(); - versionInfoDeletedEntity.setStatus(VersionStatus.Available); + versionInfoDeletedEntity.setStatus(VersionStatus.Draft); doReturn(versionInfoDeletedEntity).when(versionInfoDeletedDaoMock).get(anyObject()); versioningManager.undoDelete(TYPE1, ID1, USR1); verify(versionInfoDeletedDaoMock).delete(versionInfoDeletedEntity); verify(versionInfoDaoMock).create(versionInfoEntityArg.capture()); +*/ /* VersionInfoDeletedEntity versionInfoDeletedEntity = versionInfoDeletedDaoMock.get(new VersionInfoDeletedEntity(TYPE1, ID1)); @@ -190,7 +487,8 @@ public class VersioningManagerImplTest { Assert.assertNull(versionInfoEntity); versioningManager.undoDelete(TYPE1, ID1, USR1); versionInfoEntity = versionInfoDaoMock.get(new VersionInfoEntity(TYPE1, ID1)); - Assert.assertNotNull(versionInfoEntity);*/ + Assert.assertNotNull(versionInfoEntity);*//* + } @Test(expectedExceptions = CoreException.class) @@ -216,7 +514,7 @@ public class VersioningManagerImplTest { public void testCheckoutOnFinalized() { Set<Version> viewableVersions = new HashSet<>(); viewableVersions.add(VERSION10); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Final, VERSION10, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Certified, VERSION10, null, viewableVersions, VERSION10); Version version = versioningManager.checkout(TYPE1, ID1, USR1); @@ -225,18 +523,20 @@ public class VersioningManagerImplTest { VersionInfoEntity versionInfoEntity = versionInfoDaoMock.get(new VersionInfoEntity(TYPE1, ID1)); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, VERSION10, VERSION11, USR1, VersionStatus.Locked, viewableVersions, VERSION10); +*/ /* ResultSet results = loadVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, VERSION11); - Assert.assertTrue(results.iterator().hasNext());*/ + Assert.assertTrue(results.iterator().hasNext());*//* + } @Test public void testCheckout() { Set<Version> viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); Version version = versioningManager.checkout(TYPE1, ID1, USR1); @@ -248,10 +548,12 @@ public class VersioningManagerImplTest { assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, VERSION01, VERSION02, USR1, VersionStatus.Locked, viewableVersions, null); +*/ /* ResultSet results = loadVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, VERSION02); - Assert.assertTrue(results.iterator().hasNext());*/ + Assert.assertTrue(results.iterator().hasNext());*//* + } @Test(expectedExceptions = CoreException.class) @@ -263,7 +565,7 @@ public class VersioningManagerImplTest { public void testUndoCheckoutOnAvailable() { Set<Version> viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); versioningManager.undoCheckout(TYPE1, ID1, USR1); @@ -273,7 +575,7 @@ public class VersioningManagerImplTest { public void testUndoCheckouOnFinalized() { Set<Version> viewableVersions = new HashSet<>(); viewableVersions.add(VERSION10); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Final, VERSION10, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Certified, VERSION10, null, viewableVersions, VERSION10); versioningManager.undoCheckout(TYPE1, ID1, USR2); } @@ -298,12 +600,14 @@ public class VersioningManagerImplTest { VersionInfoEntity versionInfoEntity = versionInfoDaoMock.get(new VersionInfoEntity(TYPE1, ID1)); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, VERSION01, null, null, - VersionStatus.Available, viewableVersions, null); + VersionStatus.Draft, viewableVersions, null); +*/ /* ResultSet results = loadVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, VERSION02); - Assert.assertFalse(results.iterator().hasNext());*/ + Assert.assertFalse(results.iterator().hasNext());*//* + } @Test(expectedExceptions = CoreException.class) @@ -315,7 +619,7 @@ public class VersioningManagerImplTest { public void testCheckinOnAvailable() { Set<Version> viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); versioningManager.checkin(TYPE1, ID1, USR1, "fail checkin"); @@ -326,7 +630,7 @@ public class VersioningManagerImplTest { public void testCheckinOnFinalized() { Set<Version> viewableVersions = new HashSet<>(); viewableVersions.add(VERSION10); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Final, VERSION10, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Certified, VERSION10, null, viewableVersions, VERSION10); versioningManager.checkin(TYPE1, ID1, USR1, "failed checkin"); @@ -354,7 +658,7 @@ public class VersioningManagerImplTest { viewableVersions.add(VERSION01); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, VERSION01, null, null, - VersionStatus.Available, viewableVersions, null); + VersionStatus.Draft, viewableVersions, null); } @Test(expectedExceptions = CoreException.class) @@ -374,7 +678,7 @@ public class VersioningManagerImplTest { public void testSubmitOnFinalized() { Set<Version> viewableVersions = new HashSet<>(); viewableVersions.add(VERSION10); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Final, VERSION10, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Certified, VERSION10, null, viewableVersions, VERSION10); versioningManager.submit(TYPE1, ID1, USR2, "failed submit"); } @@ -390,7 +694,7 @@ public class VersioningManagerImplTest { viewableVersions.add(new Version(3, 0)); viewableVersions.add(new Version(3, 1)); viewableVersions.add(version32); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, version32, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, version32, null, viewableVersions, new Version(3, 0)); Version version = versioningManager.submit(TYPE1, ID1, USR1, "submit msg"); @@ -403,12 +707,14 @@ public class VersioningManagerImplTest { VersionInfoEntity versionInfoEntity = versionInfoEntityArg.getValue(); assretVersionInfoEntity(versionInfoEntity, TYPE1, ID1, version40, null, null, - VersionStatus.Final, viewableVersions, version40); + VersionStatus.Certified, viewableVersions, version40); +*/ /* ResultSet results = loadVersionableEntityRecord(TYPE1_TABLE_NAME, TYPE1_ID_NAME, TYPE1_VERSION_NAME, ID1, VERSION10); - Assert.assertTrue(results.iterator().hasNext());*/ + Assert.assertTrue(results.iterator().hasNext());*//* + } @Test(expectedExceptions = CoreException.class) @@ -420,12 +726,12 @@ public class VersioningManagerImplTest { public void testGetVersionInfoForReadOnAvailable() { Set<Version> viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); VersionInfo versionInfo = versioningManager.getEntityVersionInfo(TYPE1, ID1, USR1, VersionableEntityAction.Read); - assertVersionInfo(versionInfo, VERSION01, VersionStatus.Available, null, + assertVersionInfo(versionInfo, VERSION01, VersionStatus.Draft, null, viewableVersions, null); } @@ -433,7 +739,7 @@ public class VersioningManagerImplTest { public void testGetVersionInfoForWriteOnAvailable() { Set<Version> viewableVersions = new HashSet<>(); viewableVersions.add(VERSION01); - mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Available, VERSION01, null, viewableVersions, + mockVersionInfoEntity(TYPE1, ID1, VersionStatus.Draft, VERSION01, null, viewableVersions, null); versioningManager.getEntityVersionInfo(TYPE1, ID1, USR1, VersionableEntityAction.Write); @@ -488,6 +794,7 @@ public class VersioningManagerImplTest { assertVersionInfo(versionInfo, VERSION02, VersionStatus.Locked, USR1, viewableVersions, null); } +*/ /* private void createVersionableEntityRecord(String tableName, String idName, String versionName, String id, Version version) { noSqlDb.execute( @@ -500,7 +807,8 @@ public class VersioningManagerImplTest { return noSqlDb.execute( String.format("select * from %s where %s=? and %s=?", tableName, idName, versionName), id, versionMapper.toUDT(version)); - }*/ + }*//* + private static void assretVersionInfoEntity(VersionInfoEntity actual, String entityType, @@ -553,4 +861,5 @@ public class VersioningManagerImplTest { doReturn(mock).when(versionInfoDaoMock).get(anyObject()); return mock; } +*/ } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/CreateToscaObjectErrorBuilder.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/CreateToscaObjectErrorBuilder.java index f9a3da2e75..daeb570086 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/CreateToscaObjectErrorBuilder.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-api/src/main/java/org/openecomp/core/converter/errors/CreateToscaObjectErrorBuilder.java @@ -5,15 +5,14 @@ import org.openecomp.sdc.common.errors.ErrorCategory; public class CreateToscaObjectErrorBuilder extends BaseErrorBuilder { private static final String CANT_CREATE_OBJECT_FROM_CLASS = - "Can't create %s from %s. Reason - %s"; + "Can't create %s from %s."; private static final String IMPORT_TOSCA = "IMPORT_TOSCA"; public CreateToscaObjectErrorBuilder(String className, - String objectId, - String reason) { + String objectId) { getErrorCodeBuilder() .withId(IMPORT_TOSCA) .withCategory(ErrorCategory.APPLICATION) - .withMessage(String.format(CANT_CREATE_OBJECT_FROM_CLASS, className, objectId, reason)); + .withMessage(String.format(CANT_CREATE_OBJECT_FROM_CLASS, className, objectId)); } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java index e7ff3aa8ee..39a53b499d 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterImpl.java @@ -12,7 +12,17 @@ import org.openecomp.sdc.common.errors.CoreException; import org.openecomp.sdc.common.errors.ErrorCategory; import org.openecomp.sdc.common.errors.ErrorCode; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import org.openecomp.sdc.tosca.datatypes.model.*; +import org.openecomp.sdc.tosca.datatypes.model.ArtifactDefinition; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityAssignment; +import org.openecomp.sdc.tosca.datatypes.model.Import; +import org.openecomp.sdc.tosca.datatypes.model.InterfaceDefinition; +import org.openecomp.sdc.tosca.datatypes.model.NodeFilter; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; @@ -21,11 +31,28 @@ import org.yaml.snakeyaml.error.YAMLException; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import java.util.jar.Manifest; import java.util.regex.Pattern; -import static org.openecomp.core.converter.datatypes.Constants.*; +import static org.openecomp.core.converter.datatypes.Constants.capabilities; +import static org.openecomp.core.converter.datatypes.Constants.definitionsDir; +import static org.openecomp.core.converter.datatypes.Constants.globalStName; +import static org.openecomp.core.converter.datatypes.Constants.globalSubstitution; +import static org.openecomp.core.converter.datatypes.Constants.inputs; +import static org.openecomp.core.converter.datatypes.Constants.mainStName; +import static org.openecomp.core.converter.datatypes.Constants.manifestFileName; +import static org.openecomp.core.converter.datatypes.Constants.metadataFile; +import static org.openecomp.core.converter.datatypes.Constants.nodeType; +import static org.openecomp.core.converter.datatypes.Constants.openecompHeatIndex; +import static org.openecomp.core.converter.datatypes.Constants.outputs; +import static org.openecomp.core.converter.datatypes.Constants.requirements; import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.GLOBAL_SUBSTITUTION_SERVICE_FILE_NAME; public class ToscaConverterImpl implements ToscaConverter { @@ -89,9 +116,8 @@ public class ToscaConverterImpl implements ToscaConverter { } } catch (YAMLException ye) { throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage("Invalid YAML content in file " + key + ". reason - " - + ye.getMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); + .withMessage("Invalid YAML content in file " + key) + .withCategory(ErrorCategory.APPLICATION).build(), ye); } } @@ -181,9 +207,8 @@ public class ToscaConverterImpl implements ToscaConverter { } catch (YAMLException ye) { throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage("Invalid YAML content in file" + serviceTemplateName + ". reason - " - + ye.getMessage()) - .withCategory(ErrorCategory.APPLICATION).build()); + .withMessage("Invalid YAML content in file" + serviceTemplateName) + .withCategory(ErrorCategory.APPLICATION).build(), ye); } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterManagerImpl.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterManagerImpl.java index 520e41817e..4917533dd8 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterManagerImpl.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterManagerImpl.java @@ -5,6 +5,8 @@ import org.openecomp.core.converter.api.ToscaConverterManager; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import java.lang.reflect.Constructor; @@ -14,8 +16,10 @@ import java.util.Map; public class ToscaConverterManagerImpl implements ToscaConverterManager { + private static final Logger LOGGER = LoggerFactory.getLogger(ToscaConverterManagerImpl.class.getName()); private static List<ToscaConverter> toscaConverters; private static final String toscaConverterFileName = "ToscaConverters.json"; + private static final String TOSCA_CONVERTER_IMPL_FORMAT_ERROR = "Failed to construct TOSCA converter for '%s' implementation."; static { toscaConverters = getConvertersList(); @@ -40,7 +44,8 @@ public class ToscaConverterManagerImpl implements ToscaConverterManager { Class<?> clazz = Class.forName(implClassName); Constructor<?> constructor = clazz.getConstructor(); toscaConvertersList.add((ToscaConverter) constructor.newInstance()); - }catch (Exception e){ + }catch (Exception ex){ + LOGGER.debug(String.format(TOSCA_CONVERTER_IMPL_FORMAT_ERROR, implClassName), ex); continue; } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterUtil.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterUtil.java index 20ac6413e7..d34d46796d 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterUtil.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/ToscaConverterUtil.java @@ -4,6 +4,8 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.openecomp.core.converter.errors.CreateToscaObjectErrorBuilder; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; import java.lang.reflect.Field; import java.util.HashSet; @@ -20,6 +22,8 @@ public class ToscaConverterUtil { private static final String DEFAULT_CAPITAL = "Default"; private static Set<String> defaultValueKeys; + private static Logger LOGGER = LoggerFactory.getLogger(ToscaConverterUtil.class.getName()); + static { defaultValueKeys = Stream.of(DEFAULT, DEFAULT_CAPITAL).collect(Collectors.toSet()); @@ -30,10 +34,10 @@ public class ToscaConverterUtil { Class<T> classToCreate) { try { return createObjectUsingSetters(objectCandidate, classToCreate); - } catch (Exception e) { + } catch (Exception ex) { throw new CoreException( - new CreateToscaObjectErrorBuilder(classToCreate.getSimpleName(), objectId, e.getMessage()) - .build()); + new CreateToscaObjectErrorBuilder(classToCreate.getSimpleName(), objectId) + .build(), ex); } } @@ -68,6 +72,8 @@ public class ToscaConverterUtil { return Objects.nonNull(fieldValueToAssign) && Objects.nonNull(classToCreate.getMethod(methodName, field.getType())); } catch (NoSuchMethodException e) { + LOGGER.debug(String.format("Could not extract method '%s' from class '%s'. returning false " + + "with filedType '%s'.", methodName, classToCreate, field.getType()), e); return false; } } diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/services/ServiceTemplateReaderServiceImpl.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/services/ServiceTemplateReaderServiceImpl.java index 22780af343..ee39af98c9 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/services/ServiceTemplateReaderServiceImpl.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/main/java/org/openecomp/core/impl/services/ServiceTemplateReaderServiceImpl.java @@ -7,7 +7,14 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; -import static org.openecomp.core.converter.datatypes.Constants.*; +import static org.openecomp.core.converter.datatypes.Constants.definitionVersion; +import static org.openecomp.core.converter.datatypes.Constants.inputs; +import static org.openecomp.core.converter.datatypes.Constants.metadata; +import static org.openecomp.core.converter.datatypes.Constants.nodeTemplates; +import static org.openecomp.core.converter.datatypes.Constants.nodeTypes; +import static org.openecomp.core.converter.datatypes.Constants.outputs; +import static org.openecomp.core.converter.datatypes.Constants.substitutionMappings; +import static org.openecomp.core.converter.datatypes.Constants.topologyTemplate; public class ServiceTemplateReaderServiceImpl implements ServiceTemplateReaderService { diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java index 5ee96aba07..df34b89cbb 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConverterImplTest.java @@ -2,7 +2,6 @@ package org.openecomp.core.converter.impl; import org.apache.commons.collections.CollectionUtils; import org.junit.Assert; -import org.junit.Ignore; import org.junit.Test; import org.openecomp.core.converter.ToscaConverter; import org.openecomp.core.impl.ToscaConverterImpl; diff --git a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConvertorDefinitionsTest.java b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConvertorDefinitionsTest.java index 1ee8f6c05f..82a36950f3 100644 --- a/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConvertorDefinitionsTest.java +++ b/openecomp-be/lib/openecomp-tosca-converter-lib/openecomp-tosca-converter-core/src/test/java/org/openecomp/core/converter/impl/ToscaConvertorDefinitionsTest.java @@ -13,9 +13,15 @@ import java.net.URL; import java.util.Map; import java.util.Set; -import static org.openecomp.sdc.common.utils.CommonUtil.*; -import static org.junit.Assert.*; -import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.DEFININTION_VERSION; +import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.GLOBAL_SUBSTITUTION_SERVICE_FILE_NAME; +import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.HEAT_INDEX; +import static org.openecomp.core.impl.GlobalSubstitutionServiceTemplate.TEMPLATE_NAME_PROPERTY; +import static org.openecomp.sdc.common.utils.CommonUtil.validateAndUploadFileContent; public class ToscaConvertorDefinitionsTest { diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java index 45e6c3deef..30e767beeb 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/main/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImpl.java @@ -53,8 +53,8 @@ import org.openecomp.sdc.tosca.errors.ToscaNodeTypeNotFoundErrorBuilder; import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.tosca.services.ToscaExtensionYamlUtil; +import org.openecomp.sdc.tosca.services.ToscaUtil; import java.util.ArrayList; import java.util.Collection; diff --git a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java index aad21634a8..d082d2febf 100644 --- a/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java +++ b/openecomp-be/lib/openecomp-tosca-lib/src/test/java/org/openecomp/sdc/tosca/services/impl/ToscaAnalyzerServiceImplTest.java @@ -20,12 +20,6 @@ package org.openecomp.sdc.tosca.services.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; @@ -58,6 +52,12 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + /** * @author Avrahamg diff --git a/openecomp-be/lib/pom.xml b/openecomp-be/lib/pom.xml index ea1faaec4b..d031dd4d04 100644 --- a/openecomp-be/lib/pom.xml +++ b/openecomp-be/lib/pom.xml @@ -10,7 +10,7 @@ <artifactId>openecomp-sdc</artifactId> <groupId>org.openecomp.sdc</groupId> <version>1.2.0-SNAPSHOT</version> - <relativePath>..</relativePath> + <relativePath>..</relativePath> </parent> <modules> @@ -33,5 +33,8 @@ <module>openecomp-sdc-activity-log-lib</module> <module>openecomp-tosca-converter-lib</module> <module>openecomp-sdc-orchestration-lib</module> + <module>openecomp-sdc-notification-lib</module> + <module>openecomp-item-permissions-lib</module> + <module>openecomp-conflict-lib</module> </modules> </project> |