Catalog alignment
[sdc.git] / asdctool / src / main / java / org / openecomp / sdc / asdctool / migration / tasks / mig1902 / SdcResourceIconMigration.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.asdctool.migration.tasks.mig1902;
22
23 import com.google.common.annotations.VisibleForTesting;
24 import org.openecomp.sdc.asdctool.migration.core.DBVersion;
25 import org.openecomp.sdc.asdctool.migration.core.task.Migration;
26 import org.openecomp.sdc.asdctool.migration.core.task.MigrationResult;
27 import org.openecomp.sdc.asdctool.migration.tasks.InstanceMigrationBase;
28 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
29 import org.openecomp.sdc.be.dao.jsongraph.JanusGraphDao;
30 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
31 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
32 import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
33 import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
34 import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
35 import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
36 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
37 import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum;
38 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
39 import org.openecomp.sdc.common.log.wrappers.Logger;
40 import org.springframework.stereotype.Component;
41
42 import java.math.BigInteger;
43 import java.util.EnumMap;
44 import java.util.HashMap;
45 import java.util.List;
46 import java.util.Map;
47
48 @Component
49 public class SdcResourceIconMigration extends InstanceMigrationBase implements Migration {
50
51     private static final Logger log = Logger.getLogger(SdcResourceIconMigration.class);
52
53     private Map <String, String> resourceTypeToIconMap = new HashMap<>();
54
55     @VisibleForTesting
56     SdcResourceIconMigration(JanusGraphDao janusGraphDao) {
57         super(janusGraphDao);
58     }
59
60
61     @Override
62     public String description() {
63         return "update iconPath for VL and CP nodes";
64     }
65
66     @Override
67     public DBVersion getVersion() {
68         return DBVersion.from(BigInteger.valueOf(1902), BigInteger.valueOf(0));
69     }
70
71     @Override
72     public MigrationResult migrate() {
73         StorageOperationStatus status;
74         try {
75             updateNodeTypeIconAndStoreInMap(ResourceTypeEnum.VL);
76             updateNodeTypeIconAndStoreInMap(ResourceTypeEnum.CP);
77
78             if (!resourceTypeToIconMap.isEmpty()) {
79                 status = upgradeTopologyTemplates();
80             } else {
81                 log.error("No VL and CP node definitions found");
82                 status = StorageOperationStatus.NOT_FOUND;
83             }
84         }
85         catch(Exception e) {
86             log.error("Exception thrown: {}", e);
87             status = StorageOperationStatus.GENERAL_ERROR;
88         }
89         return status == StorageOperationStatus.OK ?
90                     MigrationResult.success() : MigrationResult.error("failed to update iconPath for VL and CP nodes. Error : " + status);
91     }
92
93     @Override
94     protected StorageOperationStatus handleOneContainer(GraphVertex containerVorig) {
95         StorageOperationStatus status = StorageOperationStatus.OK;
96         GraphVertex containerV = getVertexById(containerVorig.getUniqueId());
97
98         Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>)containerV.getJson();
99         if (jsonComposition != null && !jsonComposition.isEmpty()) {
100             CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
101             Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
102
103             long updateCount = componentInstances.values()
104                     .stream()
105                     .filter(this::updateIconInsideInstance).count();
106             if (updateCount > 0) {
107                 status = updateVertexAndCommit(containerV);
108             }
109         }
110         else {
111             log.warn("No json found for template <{}> uniqueId <{}>",
112                     containerV.getMetadataProperties().get(GraphPropertyEnum.NAME),
113                     containerV.getMetadataProperties().get(GraphPropertyEnum.UNIQUE_ID));
114         }
115         if (log.isInfoEnabled()) {
116             log.info("Upgrade status is <{}> for topology template <{}> uniqueId <{}>",
117                     status.name(), containerV.getMetadataProperties().get(GraphPropertyEnum.NAME),
118                     containerV.getMetadataProperties().get(GraphPropertyEnum.UNIQUE_ID));
119         }
120         return status;
121     }
122
123
124     @VisibleForTesting
125     boolean updateIconInsideInstance(ComponentInstanceDataDefinition componentInstanceDataDefinition) {
126         String iconPath = resourceTypeToIconMap.get(componentInstanceDataDefinition.getComponentName());
127         if (iconPath != null) {
128             componentInstanceDataDefinition.setIcon(iconPath);
129             if (log.isDebugEnabled()) {
130                 log.debug("Icon of component {} is set to {}", componentInstanceDataDefinition.getComponentName(), iconPath);
131             }
132             return true;
133         }
134         return false;
135     }
136
137     @VisibleForTesting
138     void updateNodeTypeIconAndStoreInMap(ResourceTypeEnum resourceType) {
139         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
140         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
141
142         propertiesToMatch.put(GraphPropertyEnum.RESOURCE_TYPE, resourceType.name());
143         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
144
145         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
146
147         String iconPath = String.valueOf(resourceType.getValue()).toLowerCase();
148
149         Map<String, String> resourceNameToIconMap = janusGraphDao.getByCriteria(VertexTypeEnum.NODE_TYPE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll)
150                 .either(vl-> updateIconResource(vl, iconPath), status->null);
151
152         if (resourceNameToIconMap != null) {
153             resourceTypeToIconMap.putAll(resourceNameToIconMap);
154         }
155         else {
156             log.warn("Failed to get resources of type <{}>", resourceType.name());
157         }
158     }
159
160     private Map <String, String> updateIconResource(List<GraphVertex> vertexList, String iconPath) {
161         if (vertexList.isEmpty()) {
162             return null;
163         }
164         Map <String, String> nameToIconMap = new HashMap<>();
165         vertexList.forEach(v->{
166             StorageOperationStatus status = updateIconOnVertex(v, iconPath);
167             if (status == StorageOperationStatus.OK) {
168                 if (log.isDebugEnabled()) {
169                     log.debug("Node type's {} icon is updated to {}", v.getMetadataProperty(GraphPropertyEnum.NAME), iconPath);
170                 }
171                 nameToIconMap.put(String.valueOf(v.getMetadataProperty(GraphPropertyEnum.NAME)), iconPath);
172             }
173             else {
174                 log.error("Failed to update node type {} icon due to a reason: {}",
175                                 v.getMetadataProperty(GraphPropertyEnum.NAME), status);
176                 throw new RuntimeException("Node update failure");
177             }
178         });
179         return nameToIconMap;
180     }
181
182     private StorageOperationStatus updateIconOnVertex(GraphVertex vertex, String iconPath) {
183         vertex.setJsonMetadataField(JsonPresentationFields.ICON, iconPath);
184         return updateVertexAndCommit(vertex);
185     }
186
187 }