Include custom data types from VSP in csar imports
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / impl / ModelBusinessLogic.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19 package org.openecomp.sdc.be.components.impl;
20
21 import java.io.ByteArrayOutputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Optional;
27 import org.apache.commons.lang3.StringUtils;
28 import org.openecomp.sdc.be.datatypes.enums.ModelTypeEnum;
29 import org.openecomp.sdc.be.model.Model;
30 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.ModelOperationExceptionSupplier;
31 import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
32 import org.openecomp.sdc.common.zip.ZipUtils;
33 import org.openecomp.sdc.common.zip.exception.ZipException;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.stereotype.Component;
38
39 /**
40  * This class is responsible for handling the business logic of a Model.
41  */
42 @Component("modelBusinessLogic")
43 public class ModelBusinessLogic {
44
45     private static final Logger LOGGER = LoggerFactory.getLogger(ModelBusinessLogic.class);
46     private final ModelOperation modelOperation;
47     private final DataTypeImportManager dataTypeImportManager;
48
49     @Autowired
50     public ModelBusinessLogic(final ModelOperation modelOperation, final DataTypeImportManager dataTypeImportManager) {
51         this.modelOperation = modelOperation;
52         this.dataTypeImportManager = dataTypeImportManager;
53     }
54
55     /**
56      * Creates a model along with given data types. The data types must be provided in a yaml format, where each entry is one data type object, for
57      * example:
58      * <pre>
59      * tosca.datatypes.TimeInterval:
60      *   derived_from: tosca.datatypes.Root
61      *   [...]
62      *
63      * tosca.datatypes.network.NetworkInfo:
64      *   derived_from: tosca.datatypes.Root
65      *   [...]
66      * </pre>
67      *
68      * @param model         the model to create
69      * @param datatypesYaml the data types to create in yaml format. It can contain multiple data types entries.
70      * @return the created model.
71      */
72     public Model createModel(final Model model, final String datatypesYaml) {
73         createModel(model);
74         dataTypeImportManager.createDataTypes(datatypesYaml, model.getName(), true);
75         return model;
76     }
77
78     public Model createModel(final Model model) {
79         LOGGER.debug("creating model {}", model);
80         return modelOperation.createModel(model, false);
81     }
82
83     public Optional<Model> findModel(final String modelName) {
84         if (StringUtils.isEmpty(modelName)) {
85             return Optional.empty();
86         }
87         return modelOperation.findModelByName(modelName);
88     }
89
90     /**
91      * Loads the list of models.
92      *
93      * @return the list of models
94      */
95     public List<Model> listModels() {
96         return modelOperation.findAllModels();
97     }
98     
99     public List<Model> listModels(final ModelTypeEnum modelType) {
100         return modelOperation.findModels(modelType);
101     }
102
103     public void createModelImports(final String modelName, final InputStream modelImportsZip) {
104         if (StringUtils.isEmpty(modelName)) {
105             throw ModelOperationExceptionSupplier.invalidModel(modelName).get();
106         }
107         if (modelImportsZip == null) {
108             throw ModelOperationExceptionSupplier.emptyModelImports().get();
109         }
110         if (findModel(modelName).isEmpty()) {
111             throw ModelOperationExceptionSupplier.invalidModel(modelName).get();
112         }
113
114         final var fileBytes = readBytes(modelImportsZip);
115         final Map<String, byte[]> zipFilesPathContentMap = unzipInMemory(fileBytes);
116         if (zipFilesPathContentMap.isEmpty()) {
117             throw ModelOperationExceptionSupplier.emptyModelImports().get();
118         }
119
120         modelOperation.createModelImports(modelName, zipFilesPathContentMap);
121     }
122
123     private Map<String, byte[]> unzipInMemory(final byte[] fileBytes) {
124         try {
125             return ZipUtils.readZip(fileBytes, false);
126         } catch (final ZipException e) {
127             throw ModelOperationExceptionSupplier.couldNotReadImports().get();
128         }
129     }
130
131     private byte[] readBytes(final InputStream modelImportsZip) {
132         try (final InputStream in = modelImportsZip; final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
133             final var buffer = new byte[1024];
134             int len;
135             while ((len = in.read(buffer)) != -1) {
136                 os.write(buffer, 0, len);
137             }
138             return os.toByteArray();
139         } catch (final IOException e) {
140             LOGGER.debug("Could not read the model imports zip", e);
141             throw ModelOperationExceptionSupplier.couldNotReadImports().get();
142         }
143     }
144 }