aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-be/src/main/java/org/openecomp/sdc/be/components/impl/InterfaceLifecycleTypeImportManager.java
blob: 49b1b741cdd99c08e269ca4d239739c1699464e4 (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
/*-
 * ============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 java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Resource;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.openecomp.sdc.be.dao.api.ActionStatus;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.impl.ComponentsUtils;
import org.openecomp.sdc.be.model.InterfaceDefinition;
import org.openecomp.sdc.be.model.Model;
import org.openecomp.sdc.be.model.Operation;
import org.openecomp.sdc.be.model.normatives.ElementTypeEnum;
import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.exception.ResponseFormat;
import org.springframework.stereotype.Component;

@Component("interfaceLifecycleTypeImportManager")
public class InterfaceLifecycleTypeImportManager {

    private static final Logger log = Logger.getLogger(InterfaceLifecycleTypeImportManager.class);
    @Resource
    private IInterfaceLifecycleOperation interfaceLifecycleOperation;
    @Resource
    private ComponentsUtils componentsUtils;
    @Resource
    private CommonImportManager commonImportManager;
    @Resource
    private ModelOperation modelOperation;

    public Either<List<InterfaceDefinition>, ResponseFormat> createLifecycleTypes(String interfaceLifecycleTypesYml, final String modelName,
                                                                                  final boolean includeToModelDefaultImports) {
        Either<List<InterfaceDefinition>, ActionStatus> interfaces =
            createInterfaceTypeFromYml(interfaceLifecycleTypesYml, modelName, !includeToModelDefaultImports);
        if (interfaces.isRight()) {
            ActionStatus status = interfaces.right().value();
            ResponseFormat responseFormat = componentsUtils.getResponseFormatByGroupType(status, null);
            return Either.right(responseFormat);
        }
        final Either<List<InterfaceDefinition>, ResponseFormat> elementTypes = createInterfacesByDao(interfaces.left().value());
        if (includeToModelDefaultImports && StringUtils.isNotEmpty(modelName)) {
            commonImportManager.addTypesToDefaultImports(ElementTypeEnum.INTERFACE_LIFECYCLE_TYPE, interfaceLifecycleTypesYml, modelName);
        }
        return elementTypes;
    }

    private Either<List<InterfaceDefinition>, ActionStatus> createInterfaceTypeFromYml(final String interfaceTypesYml, final String modelName,
                                                                                       final boolean normative) {
        final Either<List<InterfaceDefinition>, ActionStatus> interfaceTypesEither =
            commonImportManager.createElementTypesFromYml(interfaceTypesYml, this::createInterfaceDefinition);
        if (interfaceTypesEither.isRight()) {
            return interfaceTypesEither;
        }
        final List<InterfaceDefinition> interfaceTypes = interfaceTypesEither.left().value();
        if (StringUtils.isNotEmpty(modelName)) {
            final Optional<Model> modelOptional = modelOperation.findModelByName(modelName);
            if (modelOptional.isPresent()) {
                interfaceTypes.forEach(interfaceType -> {
                    interfaceType.setModel(modelName);
                    interfaceType.setUserCreated(!normative);
                });
                return Either.left(interfaceTypes);
            }
            return Either.right(ActionStatus.INVALID_MODEL);
        } else {
            interfaceTypes.forEach(interfaceType -> interfaceType.setUserCreated(!normative));
        }
        return Either.left(interfaceTypes);
    }

    private Either<List<InterfaceDefinition>, ResponseFormat> createInterfacesByDao(List<InterfaceDefinition> interfacesToCreate) {
        List<InterfaceDefinition> createdInterfaces = new ArrayList<>();
        Either<List<InterfaceDefinition>, ResponseFormat> eitherResult = Either.left(createdInterfaces);
        Iterator<InterfaceDefinition> interfaceItr = interfacesToCreate.iterator();
        boolean stopDao = false;
        while (interfaceItr.hasNext() && !stopDao) {
            InterfaceDefinition interfaceDef = interfaceItr.next();
            log.info("send interfaceDefinition {} to dao for create", interfaceDef.getType());
            Either<InterfaceDefinition, StorageOperationStatus> dataModelResponse = interfaceLifecycleOperation.createInterfaceType(interfaceDef);
            if (dataModelResponse.isRight()) {
                log.info("failed to create interface : {}  error: {}", interfaceDef.getType(), dataModelResponse.right().value().name());
                if (dataModelResponse.right().value() != StorageOperationStatus.SCHEMA_VIOLATION) {
                    ResponseFormat responseFormat = componentsUtils
                        .getResponseFormat(componentsUtils.convertFromStorageResponseForLifecycleType(dataModelResponse.right().value()),
                            interfaceDef.getType());
                    eitherResult = Either.right(responseFormat);
                    stopDao = true;
                }
            } else {
                createdInterfaces.add(dataModelResponse.left().value());
            }
            if (!interfaceItr.hasNext()) {
                log.info("lifecycle types were created successfully!!!");
            }
        }
        return eitherResult;
    }

    private InterfaceDefinition createInterfaceDefinition(final String interfaceDefinition, final Map<String, Object> toscaJson) {
        final InterfaceDefinition interfaceDef = new InterfaceDefinition();
        interfaceDef.setType(interfaceDefinition);
        final Object descriptionObj = toscaJson.get(ToscaTagNamesEnum.DESCRIPTION.getElementName());
        if (descriptionObj instanceof String) {
            interfaceDef.setDescription((String) descriptionObj);
        }
        final Object derivedFromObj = toscaJson.get(ToscaTagNamesEnum.DERIVED_FROM.getElementName());
        if (derivedFromObj instanceof String) {
            interfaceDef.setDerivedFrom((String) derivedFromObj);
        }
        final Object versionObj = toscaJson.get(ToscaTagNamesEnum.VERSION.getElementName());
        if (versionObj instanceof String) {
            interfaceDef.setVersion((String) versionObj);
        }
        final Object metadataObj = toscaJson.get(ToscaTagNamesEnum.METADATA.getElementName());
        if (metadataObj instanceof Map) {
            interfaceDef.setToscaPresentationValue(JsonPresentationFields.METADATA, metadataObj);
        }
        final Map<String, Object> operationsMap;
        if (toscaJson.containsKey(ToscaTagNamesEnum.OPERATIONS.getElementName())) {
            operationsMap = (Map<String, Object>) toscaJson.get(ToscaTagNamesEnum.OPERATIONS.getElementName());
        } else {
            final List<String> entitySchemaEntryList = Arrays
                .asList(ToscaTagNamesEnum.DERIVED_FROM.getElementName(), ToscaTagNamesEnum.DESCRIPTION.getElementName(),
                    ToscaTagNamesEnum.VERSION.getElementName(), ToscaTagNamesEnum.METADATA.getElementName(),
                    ToscaTagNamesEnum.INPUTS.getElementName(), ToscaTagNamesEnum.NOTIFICATIONS.getElementName());

            Stream<Entry<String, Object>> oldFormatOperations =
                toscaJson.entrySet().stream().filter(interfaceEntry -> !entitySchemaEntryList.contains(interfaceEntry.getKey()));
            operationsMap = new HashMap<>();
            oldFormatOperations.forEach(entry -> operationsMap.put(entry.getKey(), entry.getValue()));
        }
        interfaceDef.setOperationsMap(handleOperations(operationsMap));
        return interfaceDef;
    }

    private Map<String, Operation> handleOperations(final Map<String, Object> operationsToscaEntry) {
        if (MapUtils.isEmpty(operationsToscaEntry)) {
            return Collections.emptyMap();
        }
        return operationsToscaEntry.entrySet().stream()
            .collect(Collectors.toMap(Entry::getKey, operationEntry -> createOperation((Map<String, Object>) operationEntry.getValue())));
    }

    private Operation createOperation(final Map<String, Object> toscaOperationMap) {
        if (toscaOperationMap == null) {
            return new Operation();
        }
        final Operation operation = new Operation();
        operation.setDescription((String) toscaOperationMap.get(ToscaTagNamesEnum.DESCRIPTION.getElementName()));
        return operation;
    }
}