Add collaboration feature
[sdc.git] / openecomp-be / backend / openecomp-sdc-validation-manager / src / main / java / org / openecomp / sdc / validation / impl / UploadValidationManagerImpl.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.validation.impl;
22
23 import org.apache.commons.collections4.CollectionUtils;
24 import org.apache.commons.collections4.MapUtils;
25 import org.openecomp.core.utilities.file.FileContentHandler;
26 import org.openecomp.core.utilities.file.FileUtils;
27 import org.openecomp.core.validation.api.ValidationManager;
28 import org.openecomp.sdc.common.errors.CoreException;
29 import org.openecomp.sdc.common.errors.ErrorCategory;
30 import org.openecomp.sdc.common.errors.ErrorCode;
31 import org.openecomp.sdc.common.errors.Messages;
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.heat.datatypes.structure.ValidationStructureList;
36 import org.openecomp.sdc.heat.services.tree.HeatTreeManager;
37 import org.openecomp.sdc.heat.services.tree.HeatTreeManagerUtil;
38 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
39 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
40 import org.openecomp.sdc.logging.types.LoggerConstants;
41 import org.openecomp.sdc.logging.types.LoggerErrorCode;
42 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
43 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
44 import org.openecomp.sdc.validation.UploadValidationManager;
45 import org.openecomp.sdc.validation.types.ValidationFileResponse;
46 import org.openecomp.sdc.validation.util.ValidationManagerUtil;
47 import org.slf4j.MDC;
48
49 import java.io.ByteArrayInputStream;
50 import java.io.File;
51 import java.io.IOException;
52 import java.io.InputStream;
53 import java.util.ArrayList;
54 import java.util.List;
55 import java.util.Map;
56 import java.util.zip.ZipEntry;
57 import java.util.zip.ZipInputStream;
58
59
60 /**
61  * Created by TALIO on 4/20/2016.
62  */
63 public class UploadValidationManagerImpl implements UploadValidationManager {
64
65   private static final MdcDataDebugMessage MDC_DATA_DEBUG_MESSAGE = new MdcDataDebugMessage();
66
67
68   private static FileContentHandler getFileContentMapFromZip(byte[] uploadFileData)
69       throws IOException, CoreException {
70
71     ZipEntry zipEntry;
72     List<String> folderList = new ArrayList<>();
73     FileContentHandler mapFileContent = new FileContentHandler();
74     try (ZipInputStream inputZipStream = new ZipInputStream(new ByteArrayInputStream(uploadFileData))) {
75
76       byte[] fileByteContent;
77       String currentEntryName;
78
79       while ((zipEntry = inputZipStream.getNextEntry()) != null) {
80         currentEntryName = zipEntry.getName();
81         // else, get the file content (as byte array) and save it in a map.
82         fileByteContent = FileUtils.toByteArray(inputZipStream);
83
84         int index = lastIndexFileSeparatorIndex(currentEntryName);
85         String currSubstringWithoutSeparator =
86             currentEntryName.substring(index + 1, currentEntryName.length());
87         if (index != -1) {
88           if (currSubstringWithoutSeparator.length() > 0) {
89             mapFileContent.addFile(currentEntryName.substring(index + 1, currentEntryName.length()),
90                 fileByteContent);
91           } else {
92             folderList.add(currentEntryName);
93           }
94         } else {
95           mapFileContent.addFile(currentEntryName, fileByteContent);
96         }
97       }
98     } catch (RuntimeException exception) {
99       throw new IOException(exception);
100     }
101
102     if (CollectionUtils.isNotEmpty(folderList)) {
103       MDC.put(LoggerConstants.ERROR_DESCRIPTION, LoggerErrorDescription.INVALID_ZIP);
104       throw new CoreException((new ErrorCode.ErrorCodeBuilder())
105           .withMessage(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
106           .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
107           .withCategory(ErrorCategory.APPLICATION).build());
108
109     }
110
111     return mapFileContent;
112   }
113
114   private static int lastIndexFileSeparatorIndex(String filePath) {
115     int length = filePath.length() - 1;
116
117     for (int i = length; i >= 0; i--) {
118       char currChar = filePath.charAt(i);
119       if (currChar == '/' || currChar == File.separatorChar || currChar == File.pathSeparatorChar) {
120         return i;
121       }
122     }
123     // if we've reached to the start of the string and didn't find file separator - return -1
124     return -1;
125   }
126
127   @Override
128   public ValidationFileResponse validateFile(String type, InputStream fileToValidate)
129       throws IOException {
130
131
132     MDC_DATA_DEBUG_MESSAGE.debugEntryMessage(null, (String[]) null);
133
134     ValidationFileResponse validationFileResponse = new ValidationFileResponse();
135
136     HeatTreeManager tree;
137     ValidationStructureList validationStructureList = new ValidationStructureList();
138     if (type.toLowerCase().equals("heat")) {
139       FileContentHandler content = getFileContent(fileToValidate);
140       if (!content.containsFile(SdcCommon.MANIFEST_NAME)) {
141         MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
142             LoggerTragetServiceName.VALIDATE_MANIFEST_CONTENT, ErrorLevel.ERROR.name(),
143             LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ZIP);
144         throw new CoreException((new ErrorCode.ErrorCodeBuilder())
145             .withMessage(Messages.MANIFEST_NOT_EXIST.getErrorMessage())
146             .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
147             .withCategory(ErrorCategory.APPLICATION).build());
148       }
149       Map<String, List<ErrorMessage>> errors = validateHeatUploadData(content);
150       tree = HeatTreeManagerUtil.initHeatTreeManager(content);
151       tree.createTree();
152
153       if (MapUtils.isNotEmpty(errors)) {
154         tree.addErrors(errors);
155         validationStructureList.setImportStructure(tree.getTree());
156       }
157
158     } else {
159       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
160           LoggerTragetServiceName.VALIDATE_FILE_TYPE, ErrorLevel.ERROR.name(),
161           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_FILE_TYPE);
162       throw new RuntimeException("invalid type:" + type);
163     }
164     validationFileResponse.setValidationData(validationStructureList);
165
166     MDC_DATA_DEBUG_MESSAGE.debugExitMessage(null, (String[]) null);
167     return validationFileResponse;
168   }
169
170   private Map<String, List<ErrorMessage>> validateHeatUploadData(FileContentHandler fileContentMap) {
171     ValidationManager validationManager =
172         ValidationManagerUtil.initValidationManager(fileContentMap);
173     return validationManager.validate();
174   }
175
176   private FileContentHandler getFileContent(InputStream is) throws IOException {
177     return getFileContentMapFromZip(FileUtils.toByteArray(is));
178
179
180   }
181
182 }