aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/AttributeBusinessLogic.java
blob: ef82eba0a4f0dd17109b2b3e9d7dd967620685a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.sdc.be.components.impl;

import fj.data.Either;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.elements.AttributeDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.AttributeDefinition;
import org.openecomp.sdc.be.model.DataTypeDefinition;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
import org.openecomp.sdc.be.model.operations.api.IElementOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * This class holds the business logic relevant for attributes manipulation.
 * 
 * @author mshitrit
 *
 */
@Component("attributeBusinessLogic")
public class AttributeBusinessLogic extends BaseBusinessLogic {

    private static final String CREATE_ATTRIBUTE = "CreateAttribute";
    private static final String UPDATE_ATTRIBUTE = "UpdateAttribute";
    private static final String DELETE_ATTRIBUTE = "DeleteAttribute";

    private static final Logger log = Logger.getLogger(AttributeBusinessLogic.class);
    private static final String FAILED_TO_LOCK_COMPONENT_ERROR = "Failed to lock component {}. Error - {}";

    @Autowired
    public AttributeBusinessLogic(IElementOperation elementDao,
        IGroupOperation groupOperation,
        IGroupInstanceOperation groupInstanceOperation,
        IGroupTypeOperation groupTypeOperation,
        InterfaceOperation interfaceOperation,
        InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
        ArtifactsOperations artifactToscaOperation) {
        super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
            interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
    }

    /**
     * Created attribute on the resource with resourceId
     *
     * @param resourceId
     * @param newAttributeDef
     * @param userId
     * @return AttributeDefinition if created successfully Or ResponseFormat
     */
    public Either<AttributeDataDefinition, ResponseFormat> createAttribute(String resourceId, AttributeDataDefinition newAttributeDef, String userId) {
        Either<AttributeDataDefinition, ResponseFormat> result = null;
        validateUserExists(userId);

        StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
        if (lockResult != StorageOperationStatus.OK) {
            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(CREATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
            log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
            return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
        }

        try {
            // Get the resource from DB
            Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
            if (status.isRight()) {
                return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
            }
            Resource resource = status.left().value();

            // verify that resource is checked-out and the user is the last updater
            if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
                return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
            }

            // verify attribute does not exist in resource
            if (isAttributeExist(resource.getAttributes(), resourceId, newAttributeDef.getName())) {
                return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_ALREADY_EXIST, newAttributeDef.getName()));
            }
            Map<String, DataTypeDefinition> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);
            // validate property default values
            Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue((AttributeDefinition)newAttributeDef, eitherAllDataTypes);
            if (defaultValuesValidation.isRight()) {
                return Either.right(defaultValuesValidation.right().value());
            }

            handleDefaultValue((AttributeDefinition)newAttributeDef, eitherAllDataTypes);

            // add the new attribute to resource on graph
            // need to get StorageOpaerationStatus and convert to ActionStatus from
            // componentsUtils
            Either<AttributeDataDefinition, StorageOperationStatus> either = toscaOperationFacade.addAttributeOfResource(resource, newAttributeDef);
            if (either.isRight()) {
                result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(either.right().value()), resource.getName()));
                return result;
            }
            result = Either.left(either.left().value());

            return result;
        } finally {
            commitOrRollback(result);
            graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
        }

    }

    private boolean isAttributeExist(List<AttributeDataDefinition> attributes, String resourceUid, String propertyName) {
        boolean isExist = false;
        if (attributes != null) {
            isExist = attributes.stream().anyMatch(p -> Objects.equals(p.getName(), propertyName) && Objects.equals(p.getParentUniqueId(), resourceUid));
        }
        return isExist;

    }

    /**
     * @param resourceId
     * @param attributeId
     * @param userId
     * @return
     */
    public Either<AttributeDataDefinition, ResponseFormat> getAttribute(String resourceId, String attributeId, String userId) {

        validateUserExists(userId);

        // Get the resource from DB
        Either<Resource, StorageOperationStatus> status = toscaOperationFacade.getToscaElement(resourceId);
        if (status.isRight()) {
            return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
        }
        Resource resource = status.left().value();

        List<AttributeDataDefinition> attributes = resource.getAttributes();
        if (attributes == null) {
            return Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, ""));
        } else {
            // verify attribute exist in resource
            Optional<AttributeDataDefinition> optionalAtt = attributes.stream().filter(att -> att.getUniqueId().equals(attributeId) && resourceId.equals(att.getParentUniqueId())).findAny();
            return optionalAtt.<Either<AttributeDataDefinition, ResponseFormat>>map(Either::left).orElseGet(() -> Either.right(componentsUtils.getResponseFormat(ActionStatus.ATTRIBUTE_NOT_FOUND, "")));
        }
    }

    /**
     * Updates Attribute on resource
     *
     * @param resourceId
     * @param attributeId
     * @param newAttDef
     * @param userId
     * @return
     */
    public Either<AttributeDataDefinition, ResponseFormat> updateAttribute(String resourceId, String attributeId, AttributeDataDefinition newAttDef, String userId) {
        Either<AttributeDataDefinition, ResponseFormat> result = null;

        StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
        if (lockResult != StorageOperationStatus.OK) {
            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(UPDATE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
            log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
            return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
        }
        try {
            // Get the resource from DB
            Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
            if (eitherResource.isRight()) {
                return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
            }
            Resource resource = eitherResource.left().value();

            // verify that resource is checked-out and the user is the last updater
            if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
                return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
            }

            // verify attribute exist in resource
            Either<AttributeDataDefinition, ResponseFormat> eitherAttribute = getAttribute(resourceId, attributeId, userId);
            if (eitherAttribute.isRight()) {
                return Either.right(eitherAttribute.right().value());
            }
            Map<String, DataTypeDefinition> eitherAllDataTypes = getAllDataTypes(applicationDataTypeCache);

            // validate attribute default values
            Either<Boolean, ResponseFormat> defaultValuesValidation = validatePropertyDefaultValue((AttributeDefinition)newAttDef, eitherAllDataTypes);
            if (defaultValuesValidation.isRight()) {
                return Either.right(defaultValuesValidation.right().value());
            }

            // add the new property to resource on graph
            StorageOperationStatus validateAndUpdateAttribute = propertyOperation.validateAndUpdateProperty((AttributeDefinition)newAttDef, eitherAllDataTypes);
            if (validateAndUpdateAttribute != StorageOperationStatus.OK) {
                log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, validateAndUpdateAttribute);
                result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(validateAndUpdateAttribute), resource.getName()));
            }

            Either<AttributeDataDefinition, StorageOperationStatus> eitherAttUpdate = toscaOperationFacade.updateAttributeOfResource(resource, newAttDef);

            if (eitherAttUpdate.isRight()) {
                log.debug("Problem while updating attribute with id {}. Reason - {}", attributeId, eitherAttUpdate.right().value());
                result = Either.right(componentsUtils.getResponseFormatByResource(componentsUtils.convertFromStorageResponse(eitherAttUpdate.right().value()), resource.getName()));
                return result;
            }

            result = Either.left(eitherAttUpdate.left().value());
            return result;
        } finally {
            commitOrRollback(result);
            graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
        }

    }

    /**
     * Deletes Attribute on resource
     *
     * @param resourceId
     * @param attributeId
     * @param userId
     * @return
     */
    public Either<AttributeDataDefinition, ResponseFormat> deleteAttribute(String resourceId, String attributeId, String userId) {

        Either<AttributeDataDefinition, ResponseFormat> result = null;

        validateUserExists(userId);

        StorageOperationStatus lockResult = graphLockOperation.lockComponent(resourceId, NodeTypeEnum.Resource);
        if (lockResult != StorageOperationStatus.OK) {
            BeEcompErrorManager.getInstance().logBeFailedLockObjectError(DELETE_ATTRIBUTE, NodeTypeEnum.Resource.name().toLowerCase(), resourceId);
            log.info(FAILED_TO_LOCK_COMPONENT_ERROR, resourceId, lockResult);
            return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
        }

        try {
            // Get the resource from DB
            Either<Resource, StorageOperationStatus> eitherResource = toscaOperationFacade.getToscaElement(resourceId);
            if (eitherResource.isRight()) {
                return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, ""));
            }
            Resource resource = eitherResource.left().value();

            // verify that resource is checked-out and the user is the last updater
            if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
                return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
            }

            // verify attribute exist in resource
            Either<AttributeDataDefinition, ResponseFormat> eitherAttributeExist = getAttribute(resourceId, attributeId, userId);
            if (eitherAttributeExist.isRight()) {
                return Either.right(eitherAttributeExist.right().value());
            }
            String attributeName = eitherAttributeExist.left().value().getName();

            // delete attribute of resource from graph
            StorageOperationStatus eitherAttributeDelete = toscaOperationFacade.deleteAttributeOfResource(resource, attributeName);
            if (eitherAttributeDelete != StorageOperationStatus.OK) {
                result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(eitherAttributeDelete), resource.getName()));
                return result;
            }

            result = Either.left(eitherAttributeExist.left().value());
            return result;
        } finally {
            commitOrRollback(result);
            graphLockOperation.unlockComponent(resourceId, NodeTypeEnum.Resource);
        }
    }
}