Add collaboration feature
[sdc.git] / openecomp-be / backend / openecomp-sdc-vendor-software-product-manager / src / main / java / org / openecomp / sdc / vendorsoftwareproduct / impl / MonitoringUploadsManagerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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.vendorsoftwareproduct.impl;
22
23 import org.apache.commons.collections4.MapUtils;
24 import org.openecomp.core.enrichment.types.MonitoringUploadType;
25 import org.openecomp.core.utilities.CommonMethods;
26 import org.openecomp.core.utilities.file.FileContentHandler;
27 import org.openecomp.core.utilities.file.FileUtils;
28 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
29 import org.openecomp.sdc.common.errors.CoreException;
30 import org.openecomp.sdc.common.errors.Messages;
31 import org.openecomp.sdc.common.utils.CommonUtil;
32 import org.openecomp.sdc.common.utils.SdcCommon;
33 import org.openecomp.sdc.datatypes.error.ErrorLevel;
34 import org.openecomp.sdc.datatypes.error.ErrorMessage;
35 import org.openecomp.sdc.logging.api.Logger;
36 import org.openecomp.sdc.logging.api.LoggerFactory;
37 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
38 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
39 import org.openecomp.sdc.logging.types.LoggerConstants;
40 import org.openecomp.sdc.logging.types.LoggerErrorCode;
41 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
42 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
43 import org.openecomp.sdc.vendorsoftwareproduct.MonitoringUploadsManager;
44 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductConstants;
45 import org.openecomp.sdc.vendorsoftwareproduct.dao.ComponentArtifactDao;
46 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.ComponentMonitoringUploadEntity;
47 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
48 import org.openecomp.sdc.vendorsoftwareproduct.errors.MonitoringUploadErrorBuilder;
49 import org.openecomp.sdc.vendorsoftwareproduct.types.schemagenerator.MonitoringUploadStatus;
50 import org.openecomp.sdc.vendorsoftwareproduct.utils.VendorSoftwareProductUtils;
51 import org.openecomp.sdc.versioning.dao.types.Version;
52 import org.openecomp.sdc.versioning.errors.VersionableSubEntityNotFoundErrorBuilder;
53
54 import java.io.IOException;
55 import java.io.InputStream;
56 import java.nio.ByteBuffer;
57 import java.util.Collection;
58 import java.util.HashMap;
59 import java.util.List;
60 import java.util.Map;
61 import java.util.Objects;
62 import java.util.Optional;
63
64 public class MonitoringUploadsManagerImpl implements MonitoringUploadsManager {
65   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
66   private ComponentArtifactDao componentArtifactDao;
67   private static final Logger logger =
68       LoggerFactory.getLogger(VendorSoftwareProductManagerImpl.class);
69
70   MonitoringUploadsManagerImpl(ComponentArtifactDao componentArtifactDao) {
71     this.componentArtifactDao = componentArtifactDao;
72
73     componentArtifactDao.registerVersioning(
74         VendorSoftwareProductConstants.VENDOR_SOFTWARE_PRODUCT_VERSIONABLE_TYPE);
75   }
76
77   @Override
78   public void delete(String vspId, Version version, String componentId,
79                      MonitoringUploadType monitoringUploadType) {
80     mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId);
81
82     ComponentMonitoringUploadEntity componentMonitoringUploadEntity =
83         setValuesForComponentArtifactEntityUpload(vspId, version, null, componentId, null,
84             monitoringUploadType, null);
85     Optional<ComponentMonitoringUploadEntity> retrieved = componentArtifactDao.getByType(
86         componentMonitoringUploadEntity);
87
88     if (!retrieved.isPresent()) {
89       throw new CoreException(new VersionableSubEntityNotFoundErrorBuilder(
90           componentMonitoringUploadEntity.getEntityType(),
91           monitoringUploadType.name(),
92           VspDetails.ENTITY_TYPE,
93           componentMonitoringUploadEntity.getFirstClassCitizenId(),
94           version).build());
95     }
96
97     componentArtifactDao.delete(retrieved.get());
98
99     mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId);
100   }
101
102   @Override
103   public void upload(InputStream object, String filename, String vspId,
104                      Version version, String componentId,
105                      MonitoringUploadType type) {
106     mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId);
107
108     if (object == null) {
109       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
110           LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(),
111           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type
112               .toString() + " zip file");
113       throw new CoreException(new MonitoringUploadErrorBuilder(
114           Messages.NO_ZIP_FILE_WAS_UPLOADED_OR_ZIP_NOT_EXIST.getErrorMessage()).build());
115     } else {
116       Map<String, List<ErrorMessage>> errors = new HashMap<>();
117       try {
118         byte[] uploadedFileData = FileUtils.toByteArray(object);
119         final FileContentHandler upload =
120             validateZip(vspId, version, uploadedFileData, errors);
121         if (type.equals(MonitoringUploadType.VES_EVENTS)) {
122           validateVesEventUpload(upload, errors);
123         }
124         if (MapUtils.isNotEmpty(errors)) {
125           MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
126               LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(),
127               LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type
128                   .toString() + " zip file");
129           throw new CoreException(
130               new MonitoringUploadErrorBuilder(
131                   errors.values().iterator().next().get(0).getMessage())
132                   .build());
133         }
134
135         createArtifactInDatabase(vspId, version, filename, componentId, type,
136             uploadedFileData);
137
138       } catch (Exception exception) {
139         MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
140             LoggerTragetServiceName.UPLOAD_MONITORING_FILE, ErrorLevel.ERROR.name(),
141             LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid " + type.toString() + "zip file");
142         throw new CoreException(new MonitoringUploadErrorBuilder(exception.getMessage()).build());
143       }
144     }
145     logger.audit("Uploaded Monitoring File for component id:" + componentId + " ,vspId:" + vspId);
146     mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId);
147   }
148
149   private void validateVesEventUpload(FileContentHandler upload,
150                                       Map<String, List<ErrorMessage>> errors) {
151     if (!CommonUtil.validateAllFilesYml(upload)) {
152       ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.UPLOAD_FILE, errors)
153           .add(new ErrorMessage(ErrorLevel.ERROR,
154               Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage()));
155       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
156           LoggerTragetServiceName.VALIDATE_MONITORING_FILE, ErrorLevel.ERROR.name(),
157           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_VES_FILE);
158       throw new CoreException(
159           new MonitoringUploadErrorBuilder(
160               Messages.VES_ZIP_SHOULD_CONTAIN_YML_ONLY.getErrorMessage())
161               .build());
162     }
163   }
164
165   private void createArtifactInDatabase(String vspId, Version version, String filename,
166                                         String componentId,
167                                         MonitoringUploadType type,
168                                         byte[] uploadedFileData) {
169     String artifactId = CommonMethods.nextUuId();
170     ComponentMonitoringUploadEntity componentMonitoringUploadEntity =
171         setValuesForComponentArtifactEntityUpload(vspId, version, filename, componentId,
172             artifactId, type, uploadedFileData);
173     componentArtifactDao.create(componentMonitoringUploadEntity);
174   }
175
176   @Override
177   public MonitoringUploadStatus listFilenames(String vspId, Version version, String componentId) {
178     mdcDataDebugMessage.debugEntryMessage("VSP id, component id", vspId, componentId);
179
180     ComponentMonitoringUploadEntity current =
181         new ComponentMonitoringUploadEntity(vspId, version, componentId, null);
182
183     mdcDataDebugMessage.debugExitMessage("VSP id, component id", vspId, componentId);
184
185     return setMonitoringUploadStatusValues(current);
186   }
187
188
189   private MonitoringUploadStatus setMonitoringUploadStatusValues(
190       ComponentMonitoringUploadEntity componentMonitoringUploadEntity) {
191     MonitoringUploadStatus monitoringUploadStatus = new MonitoringUploadStatus();
192
193     Collection<ComponentMonitoringUploadEntity> artifactNames =
194         componentArtifactDao.list(componentMonitoringUploadEntity);
195     Map<MonitoringUploadType, String> artifactTypeToFilename =
196         VendorSoftwareProductUtils.mapArtifactsByType(artifactNames);
197
198     if (MapUtils.isNotEmpty(artifactTypeToFilename)) {
199       if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_TRAP)) {
200         monitoringUploadStatus
201             .setSnmpTrap(artifactTypeToFilename.get(MonitoringUploadType.SNMP_TRAP));
202       }
203       if (artifactTypeToFilename.containsKey(MonitoringUploadType.SNMP_POLL)) {
204         monitoringUploadStatus
205             .setSnmpPoll(artifactTypeToFilename.get(MonitoringUploadType.SNMP_POLL));
206       }
207       if (artifactTypeToFilename.containsKey(MonitoringUploadType.VES_EVENTS)) {
208         monitoringUploadStatus
209             .setVesEvent(artifactTypeToFilename.get(MonitoringUploadType.VES_EVENTS));
210       }
211     }
212
213     return monitoringUploadStatus;
214   }
215
216   private ComponentMonitoringUploadEntity setValuesForComponentArtifactEntityUpload(
217       String vspId, Version version, String filename, String componentId, String artifactId,
218       MonitoringUploadType monitoringUploadType, byte[] uploadedFileData) {
219
220     ComponentMonitoringUploadEntity
221         entity = new ComponentMonitoringUploadEntity();
222
223     entity.setVspId(vspId);
224     entity.setVersion(version);
225     entity.setComponentId(componentId);
226     entity.setId(artifactId);
227     entity.setType(monitoringUploadType);
228     entity.setArtifactName(filename);
229
230     if (Objects.nonNull(uploadedFileData)) {
231       entity.setArtifact(ByteBuffer.wrap(uploadedFileData));
232     }
233
234     return entity;
235   }
236
237   private FileContentHandler validateZip(String vspId, Version version, byte[] uploadedFileData,
238                                          Map<String, List<ErrorMessage>> errors) {
239     FileContentHandler contentMap;
240     try {
241       contentMap =
242           CommonUtil.validateAndUploadFileContent(OnboardingTypesEnum.ZIP, uploadedFileData);
243       VendorSoftwareProductUtils.validateContentZipData(contentMap, errors);
244     } catch (IOException exception) {
245       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB,
246           LoggerTragetServiceName.VALIDATE_MONITORING_FILE, ErrorLevel.ERROR.name(),
247           LoggerErrorCode.DATA_ERROR.getErrorCode(), "Invalid Monitoring zip file");
248       throw new CoreException(
249           new MonitoringUploadErrorBuilder(vspId, version,
250               Messages.INVALID_ZIP_FILE.getErrorMessage())
251               .build());
252     }
253     return contentMap;
254   }
255 }