diff options
author | vasraz <vasyl.razinkov@est.tech> | 2021-03-22 15:33:06 +0000 |
---|---|---|
committer | Christophe Closset <christophe.closset@intl.att.com> | 2021-03-24 06:59:47 +0000 |
commit | d378c37fbd1ecec7b43394926f1ca32a695e07de (patch) | |
tree | 5c8a085f8732f980d871d966ac49361644efa698 /openecomp-be/lib/openecomp-healing-lib | |
parent | a6ae7294ecd336d7e88f915710b08e2658eaee00 (diff) |
Reformat openecomp-be
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech>
Issue-ID: SDC-3449
Change-Id: I13e02322f8e00820cc5a1d85752caaeda9bf10d1
Diffstat (limited to 'openecomp-be/lib/openecomp-healing-lib')
17 files changed, 504 insertions, 699 deletions
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 38d7d84ce7..ed63a29913 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,22 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.api; +import java.util.Optional; import org.openecomp.sdc.datatypes.model.ItemType; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Optional; - /** * Created by Talio on 11/29/2016. */ public interface HealingManager { - /** - * @return healed version, if healing was not performed - Optional.empty. - */ - Optional<Version> healItemVersion(String itemId, Version version, ItemType itemType, - boolean force); + /** + * @return healed version, if healing was not performed - Optional.empty. + */ + Optional<Version> healItemVersion(String itemId, Version version, ItemType itemType, boolean force); } 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 index 9ea6a53b2c..b8c1f27b1d 100644 --- 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.dao; import java.util.Optional; @@ -27,7 +26,7 @@ import java.util.Optional; */ public interface HealingDao { - Optional<Boolean> getItemHealingFlag(String space, String itemId, String versionId); + Optional<Boolean> getItemHealingFlag(String space, String itemId, String versionId); - void setItemHealingFlag(boolean healingNeededFlag, 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 5e375ee046..e76f2d1580 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.factory; import org.openecomp.core.factory.api.AbstractComponentFactory; @@ -28,7 +27,8 @@ import org.openecomp.sdc.healing.api.HealingManager; * Created by Talio on 11/29/2016. */ public abstract class HealingManagerFactory extends AbstractComponentFactory<HealingManager> { - public static HealingManagerFactory getInstance(){ + + public static HealingManagerFactory getInstance() { return AbstractFactory.getInstance(HealingManagerFactory.class); } } 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 46ed591f8c..97fe393fd1 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 @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.healing.interfaces; import org.openecomp.sdc.versioning.dao.types.Version; public interface Healer { - boolean isHealingNeeded(String itemId, Version version); + boolean isHealingNeeded(String itemId, Version version); - void heal(String itemId, Version version) throws Exception; + void 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 index becf7b8ae8..b6889d17e2 100644 --- 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,9 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.types; public class ConfigConstants { - public static final String HEALING_NAMESPACE = "healing"; + + 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/HealCode.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealCode.java index 420d75621f..fb9f795817 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealCode.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-api/src/main/java/org/openecomp/sdc/healing/types/HealCode.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. @@ -17,15 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.types; /** * Created by Talio on 11/29/2016. */ public enum HealCode { - FILE_DATA_STRUCTURE_HEALER, - QUESTIONNAIRE_HEALER, - COMPOSITION_DATA_HEALER, - SUB_ENTITIES_QUESTIONNAIRE_HEALER; + FILE_DATA_STRUCTURE_HEALER, QUESTIONNAIRE_HEALER, COMPOSITION_DATA_HEALER, SUB_ENTITIES_QUESTIONNAIRE_HEALER; } 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 index 2e1093e0ab..2f62a5cacd 100644 --- 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,10 +17,8 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.types; public enum HealerType { - data, - structure + data, structure } 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 index d813c41448..0e60932392 100644 --- 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,50 +17,42 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - 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 java.util.Optional; 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); - } + 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")); + } - @Accessor - interface HealingAccessor { + @Override + public void setItemHealingFlag(boolean healingNeededFlag, String space, String itemId, String versionId) { + accessor.setItemHealingFlag(healingNeededFlag, space, itemId, versionId); + } - @Query("SELECT healing_needed FROM healing WHERE space=? AND item_id=? AND version_id=?") - ResultSet getItemHealingFlag(String space, String itemId, String versionId); + @Accessor + interface HealingAccessor { - @Query("UPDATE healing SET healing_needed=? WHERE space=? AND item_id=? AND version_id=?") - void setItemHealingFlag(boolean flag, String space, String itemId, String versionId); + @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 5a283f954b..9fff4f4698 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.impl; import org.openecomp.sdc.healing.api.HealingManager; @@ -29,9 +28,9 @@ 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( - VersioningManagerFactory.getInstance().createInterface(), new HealingDaoImpl()); + 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 fa9c6d1cdf..4478c00a63 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 @@ -17,10 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.impl; - +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.openecomp.core.utilities.CommonMethods; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.json.JsonUtil; @@ -39,235 +46,178 @@ 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.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - public class HealingManagerImpl implements HealingManager { - 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; + 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(final String itemId, final Version version, - final ItemType itemType, final boolean force) { - String user = getUser(); - populateVersionInfo(itemId, version); - - if (!isHealingNeeded(itemId, version, force, user)) { - return Optional.empty(); + public HealingManagerImpl(VersioningManager versioningManager, HealingDao healingDao) { + this.versioningManager = versioningManager; + this.healingDao = healingDao; } - Map<String, Collection<String>> healersByType = getItemHealers(itemType); - List<String> failureMessages = new LinkedList<>(); - List<Healer> structureHealersToRun = - getHealersToRun(healersByType.get(HealerType.structure.name()), itemId, version, - failureMessages); - List<Healer> dataHealersToRun = - getHealersToRun(healersByType.get(HealerType.data.name()), itemId, version, - failureMessages); - - if (structureHealersToRun.isEmpty() && dataHealersToRun.isEmpty()) { - markAsHealed(itemId, version.getId(), user); - markAsHealed(itemId, version.getId(), PUBLIC_USER); - return Optional.empty(); + @Override + public Optional<Version> healItemVersion(final String itemId, final Version version, final ItemType itemType, final boolean force) { + String user = getUser(); + populateVersionInfo(itemId, version); + if (!isHealingNeeded(itemId, version, force, user)) { + return Optional.empty(); + } + Map<String, Collection<String>> healersByType = getItemHealers(itemType); + List<String> failureMessages = new LinkedList<>(); + List<Healer> structureHealersToRun = getHealersToRun(healersByType.get(HealerType.structure.name()), itemId, version, failureMessages); + List<Healer> dataHealersToRun = getHealersToRun(healersByType.get(HealerType.data.name()), itemId, version, failureMessages); + if (structureHealersToRun.isEmpty() && dataHealersToRun.isEmpty()) { + markAsHealed(itemId, version.getId(), user); + markAsHealed(itemId, version.getId(), PUBLIC_USER); + return Optional.empty(); + } + Optional<Version> healVersion = getHealVersion(itemId, version); + if (!healVersion.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(); + } + failureMessages.addAll(doHeal(itemId, healVersion.get(), version, structureHealersToRun, dataHealersToRun, user, force)); + handleFailures(failureMessages); + return healVersion; } - Optional<Version> healVersion = getHealVersion(itemId, version); - if (!healVersion.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(); + private void populateVersionInfo(String itemId, Version version) { + if (version.getStatus() != null) { + return; + } + Version retrievedVersion = versioningManager.get(itemId, version); + version.setStatus(retrievedVersion.getStatus()); + version.setBaseId(retrievedVersion.getBaseId()); } - failureMessages.addAll( - doHeal(itemId, healVersion.get(), version, structureHealersToRun, dataHealersToRun, user, - force)); - handleFailures(failureMessages); - - return healVersion; - } - - private void populateVersionInfo(String itemId, Version version) { - if (version.getStatus() != null) { - return; + private boolean isHealingNeeded(String itemId, Version version, boolean force, String user) { + return force || isHealingFlagOn(itemId, version.getId(), user).orElse(isHealingFlagOn(itemId, version.getId(), PUBLIC_USER).orElse( + version.getStatus() == VersionStatus.Draft && version.getBaseId() != null && isHealingFlagOn(itemId, version.getBaseId(), user) + .orElse(isHealingFlagOn(itemId, version.getBaseId(), PUBLIC_USER).orElse(false)))); } - Version retrievedVersion = versioningManager.get(itemId, version); - version.setStatus(retrievedVersion.getStatus()); - version.setBaseId(retrievedVersion.getBaseId()); - } - - private boolean isHealingNeeded(String itemId, Version version, boolean force, String user) { - return force || isHealingFlagOn(itemId, version.getId(), user) - .orElse(isHealingFlagOn(itemId, version.getId(), PUBLIC_USER) - .orElse(version.getStatus() == VersionStatus.Draft && version.getBaseId() != null && - isHealingFlagOn(itemId, version.getBaseId(), user) - .orElse(isHealingFlagOn(itemId, version.getBaseId(), PUBLIC_USER) - .orElse(false)))); - } - - private Optional<Version> getHealVersion(String itemId, Version version) { - return version.getStatus() == VersionStatus.Certified - ? createNewVersion(itemId, version.getId()) - : Optional.of(version); - } - - private Optional<Version> createNewVersion(String itemId, String versionId) { - Version newVersion = new Version(); - newVersion.setBaseId(versionId); - newVersion.setDescription("Version is created by healing process"); - try { - return Optional.of(versioningManager.create(itemId, newVersion, VersionCreationMethod.major)); - } catch (Exception e) { - return Optional.empty(); + private Optional<Version> getHealVersion(String itemId, Version version) { + return version.getStatus() == VersionStatus.Certified ? createNewVersion(itemId, version.getId()) : Optional.of(version); } - } - private List<String> doHeal(String itemId, Version version, Version origVersion, - List<Healer> structureHealersToRun, - List<Healer> dataHealersToRun, String user, - boolean force) { - boolean publicFlagOn = isHealingFlagOn(itemId, origVersion.getId(), PUBLIC_USER) - .orElse(origVersion.getBaseId() != null && - isHealingFlagOn(itemId, origVersion.getBaseId(), PUBLIC_USER).orElse(false)); + private Optional<Version> createNewVersion(String itemId, String versionId) { + Version newVersion = new Version(); + newVersion.setBaseId(versionId); + newVersion.setDescription("Version is created by healing process"); + try { + return Optional.of(versioningManager.create(itemId, newVersion, VersionCreationMethod.major)); + } catch (Exception e) { + return Optional.empty(); + } + } - List<String> failureMessages = - force || origVersion.getStatus() == VersionStatus.Certified || publicFlagOn - ? healPublic(itemId, version, origVersion, structureHealersToRun, dataHealersToRun, - user) - : new LinkedList<>(); + private List<String> doHeal(String itemId, Version version, Version origVersion, List<Healer> structureHealersToRun, + List<Healer> dataHealersToRun, String user, boolean force) { + boolean publicFlagOn = isHealingFlagOn(itemId, origVersion.getId(), PUBLIC_USER) + .orElse(origVersion.getBaseId() != null && isHealingFlagOn(itemId, origVersion.getBaseId(), PUBLIC_USER).orElse(false)); + List<String> failureMessages = + force || origVersion.getStatus() == VersionStatus.Certified || publicFlagOn ? healPublic(itemId, version, origVersion, + structureHealersToRun, dataHealersToRun, user) : new LinkedList<>(); + failureMessages.addAll(healPrivate(itemId, version, origVersion, structureHealersToRun, dataHealersToRun, user)); + return failureMessages; + } - failureMessages.addAll( - healPrivate(itemId, version, origVersion, structureHealersToRun, dataHealersToRun, user)); + private List<String> healPrivate(String itemId, Version version, Version origVersion, List<Healer> structureHealersToRun, + List<Healer> dataHealersToRun, String user) { + List<String> failureMessages; + if (origVersion.getStatus() == VersionStatus.Certified) { + failureMessages = executeHealers(itemId, version, + Stream.concat(structureHealersToRun.stream(), dataHealersToRun.stream()).collect(Collectors.toList())); + } else { + if (structureHealersToRun.isEmpty()) { + failureMessages = executeHealers(itemId, version, dataHealersToRun); + } else { + versioningManager.forceSync(itemId, version); + failureMessages = new LinkedList<>(); + } + } + markAsHealed(itemId, origVersion.getId(), user); + return failureMessages; + } - return failureMessages; - } + private List<String> healPublic(String itemId, Version version, Version origVersion, List<Healer> structureHealersToRun, + List<Healer> dataHealersToRun, String user) { + List<String> failureMessages = origVersion.getStatus() == VersionStatus.Certified ? new LinkedList<>() + : healPublic(itemId, version, Stream.concat(structureHealersToRun.stream(), dataHealersToRun.stream()).collect(Collectors.toList()), + user); + markAsHealed(itemId, origVersion.getId(), PUBLIC_USER); + return failureMessages; + } - private List<String> healPrivate(String itemId, Version version, Version origVersion, - List<Healer> structureHealersToRun, - List<Healer> dataHealersToRun, String user) { - List<String> failureMessages; - if (origVersion.getStatus() == VersionStatus.Certified) { - failureMessages = executeHealers(itemId, version, - Stream.concat(structureHealersToRun.stream(), dataHealersToRun.stream()) - .collect(Collectors.toList())); - } else { - if (structureHealersToRun.isEmpty()) { - failureMessages = executeHealers(itemId, version, dataHealersToRun); - } else { + private List<String> healPublic(String itemId, Version version, List<Healer> healers, String user) { + String tenant = SessionContextProviderFactory.getInstance().createInterface().get().getTenant(); + SessionContextProviderFactory.getInstance().createInterface().create(user + HEALING_USER_SUFFIX, tenant); versioningManager.forceSync(itemId, version); - failureMessages = new LinkedList<>(); - } + List<String> failureMessages = executeHealers(itemId, version, healers); + 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, tenant); + return failureMessages; } - markAsHealed(itemId, origVersion.getId(), user); - return failureMessages; - } - - private List<String> healPublic(String itemId, Version version, Version origVersion, - List<Healer> structureHealersToRun, - List<Healer> dataHealersToRun, String user) { - List<String> failureMessages = origVersion.getStatus() == VersionStatus.Certified - ? new LinkedList<>() - : healPublic(itemId, version, - Stream.concat(structureHealersToRun.stream(), dataHealersToRun.stream()) - .collect(Collectors.toList()), user); - - markAsHealed(itemId, origVersion.getId(), PUBLIC_USER); - return failureMessages; - } - - private List<String> healPublic(String itemId, Version version, List<Healer> healers, - String user) { - String tenant = SessionContextProviderFactory.getInstance().createInterface().get().getTenant(); - SessionContextProviderFactory.getInstance().createInterface() - .create(user + HEALING_USER_SUFFIX, tenant); - - versioningManager.forceSync(itemId, version); - List<String> failureMessages = executeHealers(itemId, version, healers); - Version publicVersion = versioningManager.get(itemId, version); - - if (Objects.nonNull(publicVersion.getState()) && publicVersion.getState().isDirty()) { - versioningManager.publish(itemId, version, "Healing vsp"); + private List<String> executeHealers(String itemId, Version version, List<Healer> healers) { + List<String> failureMessages = new LinkedList<>(); + for (Healer healer : healers) { + try { + healer.heal(itemId, version); + } catch (Exception e) { + failureMessages.add(String.format("Failure in healer %s: %s", healer.getClass().getName(), e.getMessage())); + } + } + return failureMessages; } - SessionContextProviderFactory.getInstance().createInterface().create(user, tenant); - return failureMessages; - } - - private List<String> executeHealers(String itemId, Version version, List<Healer> healers) { - List<String> failureMessages = new LinkedList<>(); - for (Healer healer : healers) { - try { - healer.heal(itemId, version); - } catch (Exception e) { - failureMessages.add( - String.format("Failure in healer %s: %s", healer.getClass().getName(), e.getMessage())); - } + private Optional<Boolean> isHealingFlagOn(String itemId, String version, String user) { + return healingDao.getItemHealingFlag(user, itemId, version); } - return failureMessages; - } - - private Optional<Boolean> isHealingFlagOn(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 void markAsHealed(String itemId, String versionId, String user) { + healingDao.setItemHealingFlag(false, user, itemId, versionId); + } - private void handleFailures(List<String> failureMessages) { - if (!failureMessages.isEmpty()) { - throw new CoreException(new ErrorCode.ErrorCodeBuilder() - .withCategory(ErrorCategory.APPLICATION) - .withMessage(CommonMethods.listToSeparatedString(failureMessages, '\n')).build()); + private void handleFailures(List<String> failureMessages) { + if (!failureMessages.isEmpty()) { + throw new CoreException(new ErrorCode.ErrorCodeBuilder().withCategory(ErrorCategory.APPLICATION) + .withMessage(CommonMethods.listToSeparatedString(failureMessages, '\n')).build()); + } } - } - private List<Healer> getHealersToRun(Collection<String> healersClassNames, String itemId, - Version version, List<String> failureMessages) { - return healersClassNames == null - ? Collections.emptyList() - : healersClassNames.stream() - .map(healerClassName -> getHealerInstance(healerClassName, failureMessages)) - .filter(Optional::isPresent) - .map(Optional::get) - .filter(healer -> healer.isHealingNeeded(itemId, version)) - .collect(Collectors.toList()); - } + private List<Healer> getHealersToRun(Collection<String> healersClassNames, String itemId, Version version, List<String> failureMessages) { + return healersClassNames == null ? Collections.emptyList() + : healersClassNames.stream().map(healerClassName -> getHealerInstance(healerClassName, failureMessages)).filter(Optional::isPresent) + .map(Optional::get).filter(healer -> healer.isHealingNeeded(itemId, version)).collect(Collectors.toList()); + } - private Optional<Healer> getHealerInstance(String healerClassName, List<String> failureMessages) { - try { - return Optional.of((Healer) Class.forName(healerClassName).getConstructor().newInstance()); - } catch (Exception e) { - failureMessages - .add(String.format(Messages.CANT_LOAD_HEALING_CLASS.getErrorMessage(), healerClassName)); - return Optional.empty(); + private Optional<Healer> getHealerInstance(String healerClassName, List<String> failureMessages) { + try { + return Optional.of((Healer) Class.forName(healerClassName).getConstructor().newInstance()); + } catch (Exception e) { + failureMessages.add(String.format(Messages.CANT_LOAD_HEALING_CLASS.getErrorMessage(), healerClassName)); + return Optional.empty(); + } } - } - private Map<String, Collection<String>> getItemHealers(ItemType itemType) { - Map healingConfig = FileUtils - .readViaInputStream(HEALERS_BY_ENTITY_TYPE_FILE, - stream -> JsonUtil.json2Object(stream, Map.class)); - return (Map<String, Collection<String>>) healingConfig - .getOrDefault(itemType.name(), Collections.emptyMap()); - } + private Map<String, Collection<String>> getItemHealers(ItemType itemType) { + Map healingConfig = FileUtils.readViaInputStream(HEALERS_BY_ENTITY_TYPE_FILE, stream -> JsonUtil.json2Object(stream, Map.class)); + return (Map<String, Collection<String>>) healingConfig.getOrDefault(itemType.name(), Collections.emptyMap()); + } - private String getUser() { - return SessionContextProviderFactory.getInstance().createInterface().get().getUser() - .getUserId(); - } + 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/java/org/openecomp/sdc/healing/utils/HealingConfiguration.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingConfiguration.java index 7767277444..2cfa874d28 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingConfiguration.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingConfiguration.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. @@ -17,11 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.utils; /** * Created by Talio on 11/29/2016. */ public class HealingConfiguration { + } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingUtil.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingUtil.java index e955c83b79..3a815e9867 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingUtil.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-core/src/main/java/org/openecomp/sdc/healing/utils/HealingUtil.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. @@ -17,11 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.utils; /** * Created by Talio on 11/29/2016. */ public class HealingUtil { + } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentDataHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentDataHealer.java index 1e6299ce17..7dd86ddb5b 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentDataHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ComponentDataHealer.java @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.healing.healers; import com.google.common.annotations.VisibleForTesting; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import java.util.Collection; +import java.util.Objects; import org.apache.commons.lang.StringUtils; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDao; @@ -26,14 +27,11 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentDaoFactory; import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; -import java.util.Objects; - public class ComponentDataHealer implements Healer { private static final String VFC_CODE = "vfcCode"; //earlier present in composition data private static final String NFC_FUNCTION = "nfcFunction"; - private static final String NFC_NAMING_CODE = "nfcNamingCode"; + private static final String NFC_NAMING_CODE = "nfcNamingCode"; private static final String GENERAL = "general"; private final ComponentDao componentDao; @@ -46,12 +44,22 @@ public class ComponentDataHealer implements Healer { this.componentDao = componentDao; } + private static void moveAttribute(JsonObject compositionJsonObj, JsonObject questJsonObject, JsonObject general, String compositionAttrName, + String questAttrName) { + if (Objects.nonNull(compositionJsonObj.get(compositionAttrName))) { + if (general == null) { + general = new JsonObject(); + } + general.addProperty(questAttrName, compositionJsonObj.get(compositionAttrName).getAsString()); + questJsonObject.add(GENERAL, general); + compositionJsonObj.remove(compositionAttrName); + } + } + @Override public boolean isHealingNeeded(String itemId, Version version) { - final Collection<ComponentEntity> componentEntities = - componentDao.listCompositionAndQuestionnaire(itemId, version); - return Objects.nonNull(componentEntities) && !componentEntities.isEmpty() && - componentEntities.stream().anyMatch(this::checkNfcParams); + final Collection<ComponentEntity> componentEntities = componentDao.listCompositionAndQuestionnaire(itemId, version); + return Objects.nonNull(componentEntities) && !componentEntities.isEmpty() && componentEntities.stream().anyMatch(this::checkNfcParams); } private boolean checkNfcParams(ComponentEntity componentEntity) { @@ -66,8 +74,7 @@ public class ComponentDataHealer implements Healer { @Override public void heal(String itemId, Version version) throws Exception { - final Collection<ComponentEntity> componentEntities = - componentDao.listCompositionAndQuestionnaire(itemId, version); + final Collection<ComponentEntity> componentEntities = componentDao.listCompositionAndQuestionnaire(itemId, version); if (Objects.nonNull(componentEntities) && !componentEntities.isEmpty()) { componentEntities.forEach(componentEntity -> { final String compositionData = componentEntity.getCompositionData(); @@ -76,32 +83,18 @@ public class ComponentDataHealer implements Healer { } } - private void updateComponentData(String itemId, Version version, ComponentEntity componentEntity, - String questionnaireData, String compositionData) { + private void updateComponentData(String itemId, Version version, ComponentEntity componentEntity, String questionnaireData, + String compositionData) { if (!StringUtils.isEmpty(compositionData)) { JsonParser jsonParser = new JsonParser(); JsonObject json = (JsonObject) jsonParser.parse(compositionData); JsonObject questionnaireJson = (JsonObject) jsonParser.parse(questionnaireData); - moveAttribute(json, questionnaireJson, questionnaireJson.getAsJsonObject(GENERAL), VFC_CODE, - NFC_NAMING_CODE); - moveAttribute(json, questionnaireJson, questionnaireJson.getAsJsonObject(GENERAL), NFC_FUNCTION, - NFC_FUNCTION); + moveAttribute(json, questionnaireJson, questionnaireJson.getAsJsonObject(GENERAL), VFC_CODE, NFC_NAMING_CODE); + moveAttribute(json, questionnaireJson, questionnaireJson.getAsJsonObject(GENERAL), NFC_FUNCTION, NFC_FUNCTION); componentEntity.setCompositionData(json.toString()); componentDao.update(componentEntity); componentEntity.setQuestionnaireData(questionnaireJson.toString()); - componentDao.updateQuestionnaireData(itemId,version,componentEntity.getId(), questionnaireJson.toString()); - } - } - - private static void moveAttribute(JsonObject compositionJsonObj, JsonObject questJsonObject, - JsonObject general, String compositionAttrName, String questAttrName ) { - if (Objects.nonNull(compositionJsonObj.get(compositionAttrName))) { - if (general == null) { - general = new JsonObject(); - } - general.addProperty(questAttrName, compositionJsonObj.get(compositionAttrName).getAsString()); - questJsonObject.add(GENERAL, general); - compositionJsonObj.remove(compositionAttrName); + componentDao.updateQuestionnaireData(itemId, version, componentEntity.getId(), questionnaireJson.toString()); } } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ManufacturerReferenceNumberHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ManufacturerReferenceNumberHealer.java index 0416cc9479..e371463ef3 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ManufacturerReferenceNumberHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ManufacturerReferenceNumberHealer.java @@ -13,9 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.sdc.healing.healers; +import java.util.Collection; +import java.util.Objects; +import java.util.Set; import org.openecomp.sdc.healing.interfaces.Healer; import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDao; import org.openecomp.sdc.vendorlicense.dao.FeatureGroupDaoFactory; @@ -26,90 +28,71 @@ import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacade; import org.openecomp.sdc.vendorlicense.facade.VendorLicenseFacadeFactory; import org.openecomp.sdc.versioning.dao.types.Version; -import java.util.Collection; -import java.util.Objects; -import java.util.Set; - public class ManufacturerReferenceNumberHealer implements Healer { - private static final String MANUFACTURER_REFERENCE_NUMBER = "MRN"; - private final VendorLicenseFacade vendorLicenseFacade; - private final FeatureGroupDao featureGroupDao; - - public ManufacturerReferenceNumberHealer() { - this(VendorLicenseFacadeFactory.getInstance().createInterface(), FeatureGroupDaoFactory - .getInstance().createInterface()); - } - - public ManufacturerReferenceNumberHealer(VendorLicenseFacade vendorLicenseFacade, - FeatureGroupDao featureGroupDao) { - this.vendorLicenseFacade = vendorLicenseFacade; - this.featureGroupDao = featureGroupDao; - } + private static final String MANUFACTURER_REFERENCE_NUMBER = "MRN"; + private final VendorLicenseFacade vendorLicenseFacade; + private final FeatureGroupDao featureGroupDao; - @Override - public boolean isHealingNeeded(String itemId, Version version) { - return Objects.isNull(vendorLicenseFacade.listEntitlementPools - (itemId, version).iterator().next().getManufacturerReferenceNumber()) ? true : - false; - } - - @Override - public void heal(String itemId, Version version) throws Exception { - - healEntitlementPools(itemId, version); - healLicenseKeyGroups(itemId, version); - healFeatureGroups(itemId, version); - } - - private void healEntitlementPools(String itemId, Version version) { - Collection<EntitlementPoolEntity> entitlementPoolEntities = vendorLicenseFacade - .listEntitlementPools(itemId, version); - - for (EntitlementPoolEntity entitlementPoolEntity : entitlementPoolEntities) { - Set<String> referencingFeatureGroup = entitlementPoolEntity.getReferencingFeatureGroups(); + public ManufacturerReferenceNumberHealer() { + this(VendorLicenseFacadeFactory.getInstance().createInterface(), FeatureGroupDaoFactory.getInstance().createInterface()); + } - if (referencingFeatureGroup.size() == 1) { - entitlementPoolEntity.setManufacturerReferenceNumber(getMRN(itemId, version, - referencingFeatureGroup)); - } else { - entitlementPoolEntity.setManufacturerReferenceNumber(MANUFACTURER_REFERENCE_NUMBER); - } - vendorLicenseFacade.updateEntitlementPool(entitlementPoolEntity); + public ManufacturerReferenceNumberHealer(VendorLicenseFacade vendorLicenseFacade, FeatureGroupDao featureGroupDao) { + this.vendorLicenseFacade = vendorLicenseFacade; + this.featureGroupDao = featureGroupDao; } - } - private void healLicenseKeyGroups(String itemId, Version version) { - Collection<LicenseKeyGroupEntity> licenseKeyGroupEntities = vendorLicenseFacade - .listLicenseKeyGroups(itemId, version); + @Override + public boolean isHealingNeeded(String itemId, Version version) { + return Objects.isNull(vendorLicenseFacade.listEntitlementPools(itemId, version).iterator().next().getManufacturerReferenceNumber()) ? true + : false; + } - for (LicenseKeyGroupEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { - Set<String> referencingFeatureGroup = licenseKeyGroupEntity.getReferencingFeatureGroups(); - if (referencingFeatureGroup.size() == 1) { - licenseKeyGroupEntity.setManufacturerReferenceNumber(getMRN(itemId, version, - referencingFeatureGroup)); - } else { - licenseKeyGroupEntity.setManufacturerReferenceNumber(MANUFACTURER_REFERENCE_NUMBER); - } - vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroupEntity); + @Override + public void heal(String itemId, Version version) throws Exception { + healEntitlementPools(itemId, version); + healLicenseKeyGroups(itemId, version); + healFeatureGroups(itemId, version); } - } - private String getMRN(String itemId, Version - version, Set<String> referencingFeatureGroup) { - FeatureGroupEntity featureGroupEntity = vendorLicenseFacade.getFeatureGroup(new - FeatureGroupEntity(itemId, version, referencingFeatureGroup.iterator().next())); - return featureGroupEntity.getManufacturerReferenceNumber(); - } + private void healEntitlementPools(String itemId, Version version) { + Collection<EntitlementPoolEntity> entitlementPoolEntities = vendorLicenseFacade.listEntitlementPools(itemId, version); + for (EntitlementPoolEntity entitlementPoolEntity : entitlementPoolEntities) { + Set<String> referencingFeatureGroup = entitlementPoolEntity.getReferencingFeatureGroups(); + if (referencingFeatureGroup.size() == 1) { + entitlementPoolEntity.setManufacturerReferenceNumber(getMRN(itemId, version, referencingFeatureGroup)); + } else { + entitlementPoolEntity.setManufacturerReferenceNumber(MANUFACTURER_REFERENCE_NUMBER); + } + vendorLicenseFacade.updateEntitlementPool(entitlementPoolEntity); + } + } - private void healFeatureGroups(String itemId, Version version) { + private void healLicenseKeyGroups(String itemId, Version version) { + Collection<LicenseKeyGroupEntity> licenseKeyGroupEntities = vendorLicenseFacade.listLicenseKeyGroups(itemId, version); + for (LicenseKeyGroupEntity licenseKeyGroupEntity : licenseKeyGroupEntities) { + Set<String> referencingFeatureGroup = licenseKeyGroupEntity.getReferencingFeatureGroups(); + if (referencingFeatureGroup.size() == 1) { + licenseKeyGroupEntity.setManufacturerReferenceNumber(getMRN(itemId, version, referencingFeatureGroup)); + } else { + licenseKeyGroupEntity.setManufacturerReferenceNumber(MANUFACTURER_REFERENCE_NUMBER); + } + vendorLicenseFacade.updateLicenseKeyGroup(licenseKeyGroupEntity); + } + } - Collection<FeatureGroupEntity> featureGroupEntities = vendorLicenseFacade.listFeatureGroups - (itemId, version); + private String getMRN(String itemId, Version version, Set<String> referencingFeatureGroup) { + FeatureGroupEntity featureGroupEntity = vendorLicenseFacade + .getFeatureGroup(new FeatureGroupEntity(itemId, version, referencingFeatureGroup.iterator().next())); + return featureGroupEntity.getManufacturerReferenceNumber(); + } - for (FeatureGroupEntity featureGroupEntity : featureGroupEntities) { - featureGroupEntity.setManufacturerReferenceNumber(null); - featureGroupDao.update(featureGroupEntity); + private void healFeatureGroups(String itemId, Version version) { + Collection<FeatureGroupEntity> featureGroupEntities = vendorLicenseFacade.listFeatureGroups(itemId, version); + for (FeatureGroupEntity featureGroupEntity : featureGroupEntities) { + featureGroupEntity.setManufacturerReferenceNumber(null); + featureGroupDao.update(featureGroupEntity); + } } - } } diff --git a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NetworkPackageHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NetworkPackageHealer.java index 3b716da1ca..d4ce921133 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NetworkPackageHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/NetworkPackageHealer.java @@ -16,9 +16,12 @@ * Modifications copyright (c) 2019 Nokia * ================================================================================ */ - package org.openecomp.sdc.healing.healers; +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 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; @@ -27,6 +30,12 @@ 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 java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.ByteBuffer; +import java.util.Collection; +import java.util.Objects; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; @@ -51,49 +60,31 @@ import org.openecomp.sdc.vendorsoftwareproduct.services.filedatastructuremodule. import org.openecomp.sdc.vendorsoftwareproduct.services.utils.CandidateEntityBuilder; 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.Collection; -import java.util.Objects; - -import static org.openecomp.core.zusammen.api.ZusammenUtil.*; - public class NetworkPackageHealer implements Healer { private static final byte[] EMPTY_DATA_BYTES = "{}".getBytes(); - private static final String MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR = - "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidate"; + private static final String MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR = "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidate"; private static final String MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_CONTENT_ERROR = - "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidateContent" - + " under OrchestrationTemplateCandidate"; - - private static final String MISSING_VSP_MODEL_ERROR = - "Vsp with invalid structure: does not contain element VspModel"; + "Vsp with invalid structure: does not contain element OrchestrationTemplateCandidateContent" + " under OrchestrationTemplateCandidate"; + private static final String MISSING_VSP_MODEL_ERROR = "Vsp with invalid structure: does not contain element VspModel"; private static final String MISSING_ORCHESTRATION_TEMPLATE_ERROR = - "Vsp with invalid structure: does not contain element OrchestrationTemplate" + " under VspModel element"; + "Vsp with invalid structure: does not contain element OrchestrationTemplate" + " under VspModel element"; private static final String MISSING_ORCHESTRATION_TEMPLATE_VALIDATE_DATA_ERROR = - "Vsp with invalid structure: does not contain element OrchestrationTemplateValidationData" - + " under OrchestrationTemplate element"; - + "Vsp with invalid structure: does not contain element OrchestrationTemplateValidationData" + " under OrchestrationTemplate element"; private final VendorSoftwareProductInfoDao vspInfoDao; private final ZusammenAdaptor zusammenAdaptor; private final CandidateEntityBuilder candidateEntityBuilder; public NetworkPackageHealer() { - this(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), - ZusammenAdaptorFactory.getInstance().createInterface(), - CandidateServiceFactory.getInstance().createInterface()); + this(VendorSoftwareProductInfoDaoFactory.getInstance().createInterface(), ZusammenAdaptorFactory.getInstance().createInterface(), + CandidateServiceFactory.getInstance().createInterface()); } - private NetworkPackageHealer(VendorSoftwareProductInfoDao vspInfoDao, ZusammenAdaptor zusammenAdaptor, - CandidateService candidateService) { + private NetworkPackageHealer(VendorSoftwareProductInfoDao vspInfoDao, ZusammenAdaptor zusammenAdaptor, CandidateService candidateService) { this(vspInfoDao, zusammenAdaptor, new CandidateEntityBuilder(candidateService)); } - NetworkPackageHealer(VendorSoftwareProductInfoDao vspInfoDao, ZusammenAdaptor zusammenAdaptor, - CandidateEntityBuilder candidateEntityBuilder) { + NetworkPackageHealer(VendorSoftwareProductInfoDao vspInfoDao, ZusammenAdaptor zusammenAdaptor, CandidateEntityBuilder candidateEntityBuilder) { this.vspInfoDao = vspInfoDao; this.zusammenAdaptor = zusammenAdaptor; this.candidateEntityBuilder = candidateEntityBuilder; @@ -101,242 +92,170 @@ public class NetworkPackageHealer implements Healer { @Override public boolean isHealingNeeded(String itemId, Version version) { - return OnboardingMethod.NetworkPackage.name() - .equals(vspInfoDao.get(new VspDetails(itemId, version)).getOnboardingMethod()) - && isVspMissingAddedElements(itemId, version); + return OnboardingMethod.NetworkPackage.name().equals(vspInfoDao.get(new VspDetails(itemId, version)).getOnboardingMethod()) + && isVspMissingAddedElements(itemId, version); } @Override public void heal(String itemId, Version version) throws Exception { SessionContext context = createSessionContext(); ElementContext elementContext = new ElementContext(itemId, version.getId()); - Element candidateElement = getElement(context, elementContext, null, ElementType.OrchestrationTemplateCandidate, - MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR); - - Collection<Element> candidateSubs = - zusammenAdaptor.listElementData(context, elementContext, candidateElement.getElementId()); - - Id candidateValidationElementId = - creatIfAbsentCandidateValidationElementId(candidateSubs, context, elementContext, candidateElement); - + MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_ERROR); + Collection<Element> candidateSubs = zusammenAdaptor.listElementData(context, elementContext, candidateElement.getElementId()); + Id candidateValidationElementId = creatIfAbsentCandidateValidationElementId(candidateSubs, context, elementContext, candidateElement); Element orchestrationTemplateElement = getOrchestrationTemplateElement(context, elementContext); - - Collection<Element> orchestrationTemplateSubs = - zusammenAdaptor.listElementData(context, elementContext, orchestrationTemplateElement.getElementId()); - - Id structureElementId = createIfAbsentStructureElementId(orchestrationTemplateSubs, context, elementContext, - orchestrationTemplateElement); - - Element orchestrationTemplateValidationElement = - getOrchestrationTemplateValidationElement(orchestrationTemplateSubs); - - OrchestrationTemplateEntity orchestrationTemplateEntity = - getOrchestrationTemplateEntity(orchestrationTemplateElement, orchestrationTemplateValidationElement); - + Collection<Element> orchestrationTemplateSubs = zusammenAdaptor + .listElementData(context, elementContext, orchestrationTemplateElement.getElementId()); + Id structureElementId = createIfAbsentStructureElementId(orchestrationTemplateSubs, context, elementContext, orchestrationTemplateElement); + Element orchestrationTemplateValidationElement = getOrchestrationTemplateValidationElement(orchestrationTemplateSubs); + OrchestrationTemplateEntity orchestrationTemplateEntity = getOrchestrationTemplateEntity(orchestrationTemplateElement, + orchestrationTemplateValidationElement); if (StringUtils.isEmpty(orchestrationTemplateEntity.getFileSuffix())) { return; } - Element candidateContentElement = getCandidateContentElement(candidateSubs); - VspDetails vspDetails = vspInfoDao.get(new VspDetails(itemId, version)); if (isEqual(orchestrationTemplateEntity, getCandidateData(candidateElement, candidateContentElement))) { - if (isProcessedEntityValid(orchestrationTemplateEntity)) { - emptyStructureElementAndSub(context, elementContext, candidateElement.getElementId(), - ElementType.OrchestrationTemplateCandidate, candidateContentElement.getElementId(), - ElementType.OrchestrationTemplateCandidateContent); - - populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(), structureElementId, - vspDetails, context, elementContext); + emptyStructureElementAndSub(context, elementContext, candidateElement.getElementId(), ElementType.OrchestrationTemplateCandidate, + candidateContentElement.getElementId(), ElementType.OrchestrationTemplateCandidateContent); + populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(), structureElementId, vspDetails, context, + elementContext); } else { - emptyStructureElementAndSub(context, elementContext, orchestrationTemplateElement.getElementId(), - ElementType.OrchestrationTemplate, orchestrationTemplateValidationElement.getElementId(), - ElementType.OrchestrationTemplateValidationData); - + emptyStructureElementAndSub(context, elementContext, orchestrationTemplateElement.getElementId(), ElementType.OrchestrationTemplate, + orchestrationTemplateValidationElement.getElementId(), ElementType.OrchestrationTemplateValidationData); populateCandidateValidationData(context, elementContext, candidateValidationElementId, - orchestrationTemplateEntity.getValidationData()); + orchestrationTemplateEntity.getValidationData()); } } else { - populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(), structureElementId, - vspDetails, context, elementContext); + populateOrchestrationTemplateStructure(orchestrationTemplateElement.getData(), structureElementId, vspDetails, context, elementContext); } } private boolean isVspMissingAddedElements(String vspId, Version version) { SessionContext context = createSessionContext(); ElementContext elementContext = new ElementContext(vspId, version.getId()); - - return zusammenAdaptor.listElementsByName(context, elementContext, null, - ElementType.OrchestrationTemplateCandidate.name()).stream().noneMatch( - candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name() - .equals(candidateSub.getInfo().getName())); + return zusammenAdaptor.listElementsByName(context, elementContext, null, ElementType.OrchestrationTemplateCandidate.name()).stream() + .noneMatch(candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name().equals(candidateSub.getInfo().getName())); } private boolean isEqual(OrchestrationTemplateEntity orchestrationTemplateEntity, - OrchestrationTemplateCandidateData orchestrationTemplateCandidateData) { - return orchestrationTemplateEntity.getFileName().equals(orchestrationTemplateCandidateData.getFileName()) - && orchestrationTemplateEntity.getFileSuffix() - .equals(orchestrationTemplateCandidateData.getFileSuffix()); + OrchestrationTemplateCandidateData orchestrationTemplateCandidateData) { + return orchestrationTemplateEntity.getFileName().equals(orchestrationTemplateCandidateData.getFileName()) && orchestrationTemplateEntity + .getFileSuffix().equals(orchestrationTemplateCandidateData.getFileSuffix()); } private boolean isProcessedEntityValid(OrchestrationTemplateEntity orchestrationTemplateEntity) { return !orchestrationTemplateEntity.getValidationData().contains(ErrorLevel.ERROR.name()); } - private void populateCandidateValidationData(SessionContext context, ElementContext elementContext, - Id candidateValidationElementId, String validationData) { - ZusammenElement candidateValidationElement = - buildStructuralElement(ElementType.OrchestrationTemplateCandidateValidationData, Action.UPDATE); + private void populateCandidateValidationData(SessionContext context, ElementContext elementContext, Id candidateValidationElementId, + String validationData) { + ZusammenElement candidateValidationElement = buildStructuralElement(ElementType.OrchestrationTemplateCandidateValidationData, Action.UPDATE); candidateValidationElement.setElementId(candidateValidationElementId); candidateValidationElement.setData(new ByteArrayInputStream(validationData.getBytes())); - - zusammenAdaptor.saveElement(context, elementContext, candidateValidationElement, - "Healed Orchestration Template Candidate Validation data"); + zusammenAdaptor.saveElement(context, elementContext, candidateValidationElement, "Healed Orchestration Template Candidate Validation data"); } - private void populateOrchestrationTemplateStructure(InputStream processedFile, Id structureElementId, - VspDetails vspDetails, SessionContext context, ElementContext elementContext) throws Exception { + private void populateOrchestrationTemplateStructure(InputStream processedFile, Id structureElementId, VspDetails vspDetails, + SessionContext context, ElementContext elementContext) throws Exception { byte[] byteData = FileUtils.toByteArray(processedFile); FileContentHandler contentMap = CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, byteData); - OrchestrationTemplateCandidateData orchestrationTemplateEntityData = - candidateEntityBuilder - .buildCandidateEntityFromZip(vspDetails, byteData, contentMap, null); + OrchestrationTemplateCandidateData orchestrationTemplateEntityData = candidateEntityBuilder + .buildCandidateEntityFromZip(vspDetails, byteData, contentMap, null); String fileDataStructure = orchestrationTemplateEntityData.getFilesDataStructure(); - - ZusammenElement orchestrationTemplateStructure = - buildStructuralElement(ElementType.OrchestrationTemplateStructure, Action.UPDATE); + ZusammenElement orchestrationTemplateStructure = buildStructuralElement(ElementType.OrchestrationTemplateStructure, Action.UPDATE); orchestrationTemplateStructure.setElementId(structureElementId); orchestrationTemplateStructure.setData(new ByteArrayInputStream(fileDataStructure.getBytes())); - - zusammenAdaptor.saveElement(context, elementContext, orchestrationTemplateStructure, - "Healed Orchestration Template Structure"); + zusammenAdaptor.saveElement(context, elementContext, orchestrationTemplateStructure, "Healed Orchestration Template Structure"); } private Element getOrchestrationTemplateElement(SessionContext context, ElementContext elementContext) { - ElementInfo vspModelElement = - zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()) - .orElseThrow(() -> new CoreException( - new ErrorCode.ErrorCodeBuilder().withMessage(MISSING_VSP_MODEL_ERROR).build())); - - return getElement(context, elementContext, vspModelElement.getId(), ElementType.OrchestrationTemplate, - MISSING_ORCHESTRATION_TEMPLATE_ERROR); + ElementInfo vspModelElement = zusammenAdaptor.getElementInfoByName(context, elementContext, null, ElementType.VspModel.name()) + .orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(MISSING_VSP_MODEL_ERROR).build())); + return getElement(context, elementContext, vspModelElement.getId(), ElementType.OrchestrationTemplate, MISSING_ORCHESTRATION_TEMPLATE_ERROR); } private Element getOrchestrationTemplateValidationElement(Collection<Element> orchestrationTemplateSubs) { - return orchestrationTemplateSubs.stream() - .filter(orchestrationTemplateSub -> ElementType.OrchestrationTemplateValidationData.name() - .equals(orchestrationTemplateSub.getInfo() - .getName())).findFirst().orElseThrow( - () -> new CoreException(new ErrorCode.ErrorCodeBuilder() - .withMessage(MISSING_ORCHESTRATION_TEMPLATE_VALIDATE_DATA_ERROR) - .build())); - + return orchestrationTemplateSubs.stream().filter( + orchestrationTemplateSub -> ElementType.OrchestrationTemplateValidationData.name().equals(orchestrationTemplateSub.getInfo().getName())) + .findFirst().orElseThrow( + () -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(MISSING_ORCHESTRATION_TEMPLATE_VALIDATE_DATA_ERROR).build())); } private Element getCandidateContentElement(Collection<Element> candidateSubs) { - return candidateSubs.stream().filter(candidateSub -> ElementType.OrchestrationTemplateCandidateContent.name() - .equals(candidateSub.getInfo().getName())) - .findFirst().orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage( - MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_CONTENT_ERROR).build())); + return candidateSubs.stream() + .filter(candidateSub -> ElementType.OrchestrationTemplateCandidateContent.name().equals(candidateSub.getInfo().getName())).findFirst() + .orElseThrow(() -> new CoreException( + new ErrorCode.ErrorCodeBuilder().withMessage(MISSING_ORCHESTRATION_TEMPLATE_CANDIDATE_CONTENT_ERROR).build())); } - private Id createIfAbsentStructureElementId(Collection<Element> orchestrationTemplateSubs, SessionContext context, - ElementContext elementContext, Element orchestrationTemplateElement) { - return orchestrationTemplateSubs.stream() - .filter(orchestrationTemplateSub -> ElementType.OrchestrationTemplateStructure.name() - .equals(orchestrationTemplateSub.getInfo() - .getName())).findFirst() - .map(Element::getElementId).orElse(addStructureSubElement(context, elementContext, - ElementType.OrchestrationTemplateStructure, orchestrationTemplateElement.getElementId())); + private Id createIfAbsentStructureElementId(Collection<Element> orchestrationTemplateSubs, SessionContext context, ElementContext elementContext, + Element orchestrationTemplateElement) { + return orchestrationTemplateSubs.stream().filter( + orchestrationTemplateSub -> ElementType.OrchestrationTemplateStructure.name().equals(orchestrationTemplateSub.getInfo().getName())) + .findFirst().map(Element::getElementId).orElse(addStructureSubElement(context, elementContext, ElementType.OrchestrationTemplateStructure, + orchestrationTemplateElement.getElementId())); } - private Id creatIfAbsentCandidateValidationElementId(Collection<Element> candidateSubs, SessionContext context, - ElementContext elementContext, Element candidateElement) { + private Id creatIfAbsentCandidateValidationElementId(Collection<Element> candidateSubs, SessionContext context, ElementContext elementContext, + Element candidateElement) { return candidateSubs.stream() - .filter(candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name() - .equals(candidateSub.getInfo().getName())).findFirst() - .map(Element::getElementId).orElse(addStructureSubElement(context, elementContext, - ElementType.OrchestrationTemplateCandidateValidationData, candidateElement.getElementId())); + .filter(candidateSub -> ElementType.OrchestrationTemplateCandidateValidationData.name().equals(candidateSub.getInfo().getName())) + .findFirst().map(Element::getElementId).orElse( + addStructureSubElement(context, elementContext, ElementType.OrchestrationTemplateCandidateValidationData, + candidateElement.getElementId())); } - private Element getElement(SessionContext context, ElementContext elementContext, Id parentElementId, - ElementType elementType, String errorMessage) { + private Element getElement(SessionContext context, ElementContext elementContext, Id parentElementId, ElementType elementType, + String errorMessage) { return zusammenAdaptor.getElementByName(context, elementContext, parentElementId, elementType.name()) - .orElseThrow(() -> new CoreException( - new ErrorCode.ErrorCodeBuilder().withMessage(errorMessage).build())); + .orElseThrow(() -> new CoreException(new ErrorCode.ErrorCodeBuilder().withMessage(errorMessage).build())); } - private OrchestrationTemplateEntity getOrchestrationTemplateEntity(Element orchestrationTemplateElement, - Element validationDataElement) { + private OrchestrationTemplateEntity getOrchestrationTemplateEntity(Element orchestrationTemplateElement, Element validationDataElement) { OrchestrationTemplateEntity orchestrationTemplateEntity = new OrchestrationTemplateEntity(); - if (isNotEmpty(orchestrationTemplateElement.getData())) { - orchestrationTemplateEntity - .setContentData(ByteBuffer.wrap(FileUtils.toByteArray(orchestrationTemplateElement.getData()))); + orchestrationTemplateEntity.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(orchestrationTemplateElement.getData()))); } - orchestrationTemplateEntity - .setFileSuffix(validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); - orchestrationTemplateEntity - .setFileName(validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal())); + orchestrationTemplateEntity.setFileSuffix(validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); + orchestrationTemplateEntity.setFileName(validationDataElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal())); if (isNotEmpty(validationDataElement.getData())) { - orchestrationTemplateEntity - .setValidationData(new String(FileUtils.toByteArray(validationDataElement.getData()))); + orchestrationTemplateEntity.setValidationData(new String(FileUtils.toByteArray(validationDataElement.getData()))); } return orchestrationTemplateEntity; } - private OrchestrationTemplateCandidateData getCandidateData(Element candidateElement, - Element candidateContentElement) { + private OrchestrationTemplateCandidateData getCandidateData(Element candidateElement, Element candidateContentElement) { OrchestrationTemplateCandidateData candidateData = new OrchestrationTemplateCandidateData(); candidateData.setFilesDataStructure(new String(FileUtils.toByteArray(candidateElement.getData()))); candidateData.setContentData(ByteBuffer.wrap(FileUtils.toByteArray(candidateContentElement.getData()))); - candidateData - .setFileSuffix(candidateContentElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); + candidateData.setFileSuffix(candidateContentElement.getInfo().getProperty(InfoPropertyName.FILE_SUFFIX.getVal())); candidateData.setFileName(candidateContentElement.getInfo().getProperty(InfoPropertyName.FILE_NAME.getVal())); return candidateData; } - private Id addStructureSubElement(SessionContext context, ElementContext elementContext, ElementType elementType, - Id parentElementId) { + private Id addStructureSubElement(SessionContext context, ElementContext elementContext, ElementType elementType, Id parentElementId) { ZusammenElement newElement = buildStructuralElement(elementType, Action.CREATE); - ZusammenElement parentElement = buildElement(parentElementId, Action.IGNORE); parentElement.addSubElement(newElement); - return zusammenAdaptor.saveElement(context, elementContext, parentElement, - String.format("Add element %s under element id %s", elementType.name(), parentElementId)) - .getSubElements().iterator().next().getElementId(); + String.format("Add element %s under element id %s", elementType.name(), parentElementId)).getSubElements().iterator().next() + .getElementId(); } - private void emptyStructureElementAndSub(SessionContext context, ElementContext elementContext, Id elementId, - ElementType elementType, Id subElementId, ElementType subElementType) { + private void emptyStructureElementAndSub(SessionContext context, ElementContext elementContext, Id elementId, ElementType elementType, + Id subElementId, ElementType subElementType) { ZusammenElement subElement = buildStructuralElement(subElementType, Action.UPDATE); subElement.setElementId(subElementId); subElement.setData(new ByteArrayInputStream(EMPTY_DATA_BYTES)); - ZusammenElement element = buildStructuralElement(elementType, Action.UPDATE); element.setElementId(elementId); element.setData(new ByteArrayInputStream(EMPTY_DATA_BYTES)); element.addSubElement(subElement); - zusammenAdaptor.saveElement(context, elementContext, element, - String.format("Empty element %s and its sub element %s", elementType.name(), subElementType.name())); - } - - public enum InfoPropertyName { - FILE_SUFFIX("fileSuffix"), FILE_NAME("fileName"); - - private String val; - - InfoPropertyName(String val) { - this.val = val; - } - - private String getVal() { - return val; - } + String.format("Empty element %s and its sub element %s", elementType.name(), subElementType.name())); } private boolean isNotEmpty(InputStream elementData) { @@ -351,4 +270,17 @@ public class NetworkPackageHealer implements Healer { } return !ArrayUtils.isEmpty(byteElementData); } + + public enum InfoPropertyName { + FILE_SUFFIX("fileSuffix"), FILE_NAME("fileName"); + private String val; + + InfoPropertyName(String val) { + this.val = val; + } + + private String getVal() { + return val; + } + } } 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 index 9fcc6e5b74..2d89661d26 100644 --- 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -17,9 +17,13 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.healers; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Objects; +import java.util.Optional; import org.openecomp.sdc.common.errors.SdcRuntimeException; import org.openecomp.sdc.common.session.SessionContextProviderFactory; import org.openecomp.sdc.healing.interfaces.Healer; @@ -34,70 +38,57 @@ import org.openecomp.sdc.versioning.dao.ItemDaoFactory; import org.openecomp.sdc.versioning.dao.types.Version; import org.openecomp.sdc.versioning.types.Item; -import java.util.*; - /** * Created by ayalaben on 8/28/2017 */ public class OwnerHealer implements Healer { - private static final String HEALING_USER_SUFFIX = "_healer"; - private static final ItemPermissionsDao permissionsDao = - ItemPermissionsDaoFactory.getInstance().createInterface(); - private static final ItemDao itemDao = ItemDaoFactory.getInstance().createInterface(); - - private static final SubscribersDao subscribersDao = SubscribersDaoFactory.getInstance() - .createInterface(); - - @Override - public boolean isHealingNeeded(String itemId, Version version) { - return permissionsDao.listItemPermissions(itemId).stream().noneMatch(this::isOwnerPermission) || - isOwnerMissingOnItem(itemId); - } - - public void heal(String itemId, Version version) { - Collection<ItemPermissionsEntity> itemPermissions = permissionsDao.listItemPermissions(itemId); - if (itemPermissions.stream().noneMatch(this::isOwnerPermission)) { - String currentUserId = - SessionContextProviderFactory.getInstance().createInterface().get().getUser().getUserId() - .replace(HEALING_USER_SUFFIX, ""); + private static final String HEALING_USER_SUFFIX = "_healer"; + private static final ItemPermissionsDao permissionsDao = ItemPermissionsDaoFactory.getInstance().createInterface(); + private static final ItemDao itemDao = ItemDaoFactory.getInstance().createInterface(); + private static final SubscribersDao subscribersDao = SubscribersDaoFactory.getInstance().createInterface(); - permissionsDao.updateItemPermissions(itemId, PermissionTypes.Owner.name(), - Collections.singleton(currentUserId), new HashSet<>()); - - updateItemOwner(itemId, currentUserId); - - subscribersDao.subscribe(currentUserId, itemId); + @Override + public boolean isHealingNeeded(String itemId, Version version) { + return permissionsDao.listItemPermissions(itemId).stream().noneMatch(this::isOwnerPermission) || isOwnerMissingOnItem(itemId); + } - } else if (isOwnerMissingOnItem(itemId)) { - Optional<ItemPermissionsEntity> ownerOpt = - itemPermissions.stream().filter(this::isOwnerPermission).findFirst(); - if (ownerOpt.isPresent()) { - updateItemOwner(itemId, ownerOpt.get().getUserId()); - } else { - throw new SdcRuntimeException("Unexpected error in Owner Healer. Item id: " + itemId); - } + public void heal(String itemId, Version version) { + 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<>()); + updateItemOwner(itemId, currentUserId); + subscribersDao.subscribe(currentUserId, itemId); + } else if (isOwnerMissingOnItem(itemId)) { + Optional<ItemPermissionsEntity> ownerOpt = itemPermissions.stream().filter(this::isOwnerPermission).findFirst(); + if (ownerOpt.isPresent()) { + updateItemOwner(itemId, ownerOpt.get().getUserId()); + } else { + throw new SdcRuntimeException("Unexpected error in Owner Healer. Item id: " + itemId); + } + } } - } - private void updateItemOwner(String itemId, String userId) { - Item item = new Item(); - item.setId(itemId); - Item retrievedItem = itemDao.get(item); - if (Objects.nonNull(retrievedItem)) { - retrievedItem.setOwner(userId); - itemDao.update(retrievedItem); + private void updateItemOwner(String itemId, String userId) { + Item item = new Item(); + item.setId(itemId); + Item retrievedItem = itemDao.get(item); + if (Objects.nonNull(retrievedItem)) { + retrievedItem.setOwner(userId); + itemDao.update(retrievedItem); + } } - } - private boolean isOwnerMissingOnItem(String itemId) { - Item item = new Item(); - item.setId(itemId); - Item retrievedItem = itemDao.get(item); - return Objects.nonNull(retrievedItem) && Objects.isNull(retrievedItem.getOwner()); - } + private boolean isOwnerMissingOnItem(String itemId) { + Item item = new Item(); + item.setId(itemId); + Item retrievedItem = itemDao.get(item); + return Objects.nonNull(retrievedItem) && Objects.isNull(retrievedItem.getOwner()); + } - private boolean isOwnerPermission(ItemPermissionsEntity permissionsEntity) { - return permissionsEntity.getPermission().equals(PermissionTypes.Owner.name()); - } + 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/ToscaServiceModelHealer.java b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ToscaServiceModelHealer.java index 1aed46163d..b65629002a 100644 --- a/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ToscaServiceModelHealer.java +++ b/openecomp-be/lib/openecomp-healing-lib/openecomp-sdc-healing-impl/src/main/java/org/openecomp/sdc/healing/healers/ToscaServiceModelHealer.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. @@ -17,9 +17,11 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.sdc.healing.healers; +import java.io.IOException; +import java.util.Objects; +import java.util.Optional; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.converter.ToscaConverter; import org.openecomp.core.converter.factory.ToscaConverterFactory; @@ -40,99 +42,73 @@ import org.openecomp.sdc.vendorsoftwareproduct.dao.OrchestrationTemplateDaoFacto import org.openecomp.sdc.vendorsoftwareproduct.dao.type.OrchestrationTemplateEntity; import org.openecomp.sdc.versioning.dao.types.Version; -import java.io.IOException; -import java.util.Objects; -import java.util.Optional; - public class ToscaServiceModelHealer implements Healer { - private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao; - private OrchestrationTemplateDao orchestrationTemplateDao; - private static final String VALIDATION_FAILURE_MESSAGE = "Product was updated. Please " + - "update the uploaded Heat file according to these validation errors: \n"; - - public ToscaServiceModelHealer() { - this.serviceModelDao = ServiceModelDaoFactory.getInstance().createInterface(); - this.orchestrationTemplateDao = OrchestrationTemplateDaoFactory.getInstance().createInterface(); - } - - public ToscaServiceModelHealer( - ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao, - OrchestrationTemplateDao orchestrationTemplateDao) { - this.serviceModelDao = serviceModelDao; - this.orchestrationTemplateDao = orchestrationTemplateDao; - } - - @Override - public boolean isHealingNeeded(String itemId, Version version) { - OrchestrationTemplateEntity orchestrationTemplate = - orchestrationTemplateDao.get(itemId, version); - OnboardingTypesEnum onboardingTypes = - OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplate.getFileSuffix()); - return Objects.nonNull(onboardingTypes) && - Objects.nonNull(orchestrationTemplate.getContentData()); - } + private static final String VALIDATION_FAILURE_MESSAGE = + "Product was updated. Please " + "update the uploaded Heat file according to these validation errors: \n"; + private ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao; + private OrchestrationTemplateDao orchestrationTemplateDao; - @Override - public void heal(String itemId, Version version) throws Exception { - OrchestrationTemplateEntity orchestrationTemplateEntity = - orchestrationTemplateDao.get(itemId, version); - OnboardingTypesEnum type = - OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplateEntity.getFileSuffix()); - - Optional<ToscaServiceModel> healedServiceModel = - healServiceModel(orchestrationTemplateEntity, type); - - healedServiceModel.ifPresent(serviceModel -> serviceModelDao - .overrideServiceModel(itemId, version, serviceModel)); - } - - private Optional<ToscaServiceModel> healServiceModel( - OrchestrationTemplateEntity orchestrationTemplateEntity, - OnboardingTypesEnum type) throws IOException { - switch (type) { - case ZIP: - return Optional.of(healServiceModelFromZip( - getFileContentHandlerForHealing(orchestrationTemplateEntity, type))); + public ToscaServiceModelHealer() { + this.serviceModelDao = ServiceModelDaoFactory.getInstance().createInterface(); + this.orchestrationTemplateDao = OrchestrationTemplateDaoFactory.getInstance().createInterface(); + } - case CSAR: - return Optional.of(healServiceModelFromCsar( - getFileContentHandlerForHealing(orchestrationTemplateEntity, type))); + public ToscaServiceModelHealer(ServiceModelDao<ToscaServiceModel, ServiceElement> serviceModelDao, + OrchestrationTemplateDao orchestrationTemplateDao) { + this.serviceModelDao = serviceModelDao; + this.orchestrationTemplateDao = orchestrationTemplateDao; + } - default: - return Optional.empty(); + @Override + public boolean isHealingNeeded(String itemId, Version version) { + OrchestrationTemplateEntity orchestrationTemplate = orchestrationTemplateDao.get(itemId, version); + OnboardingTypesEnum onboardingTypes = OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplate.getFileSuffix()); + return Objects.nonNull(onboardingTypes) && Objects.nonNull(orchestrationTemplate.getContentData()); } - } - private FileContentHandler getFileContentHandlerForHealing( - OrchestrationTemplateEntity orchestrationTemplateEntity, OnboardingTypesEnum type) - throws IOException { - byte[] uploadedFileContent = orchestrationTemplateEntity.getContentData().array(); - return CommonUtil.validateAndUploadFileContent(type, uploadedFileContent); - } + @Override + public void heal(String itemId, Version version) throws Exception { + OrchestrationTemplateEntity orchestrationTemplateEntity = orchestrationTemplateDao.get(itemId, version); + OnboardingTypesEnum type = OnboardingTypesEnum.getOnboardingTypesEnum(orchestrationTemplateEntity.getFileSuffix()); + Optional<ToscaServiceModel> healedServiceModel = healServiceModel(orchestrationTemplateEntity, type); + healedServiceModel.ifPresent(serviceModel -> serviceModelDao.overrideServiceModel(itemId, version, serviceModel)); + } - private ToscaServiceModel healServiceModelFromZip(FileContentHandler contentMap) { - TranslatorOutput translatorOutput = - HeatToToscaUtil.loadAndTranslateTemplateData(contentMap); + private Optional<ToscaServiceModel> healServiceModel(OrchestrationTemplateEntity orchestrationTemplateEntity, OnboardingTypesEnum type) + throws IOException { + switch (type) { + case ZIP: + return Optional.of(healServiceModelFromZip(getFileContentHandlerForHealing(orchestrationTemplateEntity, type))); + case CSAR: + return Optional.of(healServiceModelFromCsar(getFileContentHandlerForHealing(orchestrationTemplateEntity, type))); + default: + return Optional.empty(); + } + } - if (areThereValidationErrors(translatorOutput)) { - String validationErrorsAsString = MessageContainerUtil.getErrorMessagesListAsString - (MessageContainerUtil - .getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages())); - throw new RuntimeException(VALIDATION_FAILURE_MESSAGE + validationErrorsAsString); + private FileContentHandler getFileContentHandlerForHealing(OrchestrationTemplateEntity orchestrationTemplateEntity, OnboardingTypesEnum type) + throws IOException { + byte[] uploadedFileContent = orchestrationTemplateEntity.getContentData().array(); + return CommonUtil.validateAndUploadFileContent(type, uploadedFileContent); } - return translatorOutput.getToscaServiceModel(); - } + private ToscaServiceModel healServiceModelFromZip(FileContentHandler contentMap) { + TranslatorOutput translatorOutput = HeatToToscaUtil.loadAndTranslateTemplateData(contentMap); + if (areThereValidationErrors(translatorOutput)) { + String validationErrorsAsString = MessageContainerUtil + .getErrorMessagesListAsString(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages())); + throw new RuntimeException(VALIDATION_FAILURE_MESSAGE + validationErrorsAsString); + } + return translatorOutput.getToscaServiceModel(); + } - private boolean areThereValidationErrors(TranslatorOutput translatorOutput) { - return MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, - translatorOutput.getErrorMessages())); - } + private boolean areThereValidationErrors(TranslatorOutput translatorOutput) { + return MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, translatorOutput.getErrorMessages())); + } - private ToscaServiceModel healServiceModelFromCsar(FileContentHandler contentMap) - throws IOException { - ToscaConverter toscaConverter = ToscaConverterFactory.getInstance().createInterface(); - return toscaConverter.convert(contentMap); - } + private ToscaServiceModel healServiceModelFromCsar(FileContentHandler contentMap) throws IOException { + ToscaConverter toscaConverter = ToscaConverterFactory.getInstance().createInterface(); + return toscaConverter.convert(contentMap); + } } |