[SDC-29] Amdocs OnBoard 1707 initial commit.
[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.Messages;
29 import org.openecomp.sdc.common.errors.CoreException;
30 import org.openecomp.sdc.common.errors.ErrorCategory;
31 import org.openecomp.sdc.common.errors.ErrorCode;
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 MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
66
67
68   private static FileContentHandler getFileContentMapFromZip(byte[] uploadFileData)
69       throws IOException, CoreException {
70     ZipEntry zipEntry;
71     List<String> folderList = new ArrayList<>();
72     FileContentHandler mapFileContent = new FileContentHandler();
73     try {
74       ZipInputStream inputZipStream;
75
76       byte[] fileByteContent;
77       String currentEntryName;
78       inputZipStream = new ZipInputStream(new ByteArrayInputStream(uploadFileData));
79
80       while ((zipEntry = inputZipStream.getNextEntry()) != null) {
81         currentEntryName = zipEntry.getName();
82         // else, get the file content (as byte array) and save it in a map.
83         fileByteContent = FileUtils.toByteArray(inputZipStream);
84
85         int index = lastIndexFileSeparatorIndex(currentEntryName);
86         String currSubstringWithoutSeparator =
87             currentEntryName.substring(index + 1, currentEntryName.length());
88         if (index != -1) {
89           if (currSubstringWithoutSeparator.length() > 0) {
90             mapFileContent.addFile(currentEntryName.substring(index + 1, currentEntryName.length()),
91                 fileByteContent);
92           } else {
93             folderList.add(currentEntryName);
94           }
95         } else {
96           mapFileContent.addFile(currentEntryName, fileByteContent);
97         }
98       }
99     } catch (RuntimeException exception) {
100       throw new IOException(exception);
101     }
102
103     if (CollectionUtils.isNotEmpty(folderList)) {
104       MDC.put(LoggerConstants.ERROR_DESCRIPTION, LoggerErrorDescription.INVALID_ZIP);
105       throw new CoreException((new ErrorCode.ErrorCodeBuilder())
106           .withMessage(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
107           .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
108           .withCategory(ErrorCategory.APPLICATION).build());
109
110     }
111
112     return mapFileContent;
113   }
114
115   private static int lastIndexFileSeparatorIndex(String filePath) {
116     int length = filePath.length() - 1;
117
118     for (int i = length; i >= 0; i--) {
119       char currChar = filePath.charAt(i);
120       if (currChar == '/' || currChar == File.separatorChar || currChar == File.pathSeparatorChar) {
121         return i;
122       }
123     }
124     // if we've reached to the start of the string and didn't find file separator - return -1
125     return -1;
126   }
127
128   @Override
129   public ValidationFileResponse validateFile(String type, InputStream fileToValidate)
130       throws IOException {
131
132
133     mdcDataDebugMessage.debugEntryMessage(null, null);
134
135     ValidationFileResponse validationFileResponse = new ValidationFileResponse();
136
137     HeatTreeManager tree;
138     ValidationStructureList validationStructureList = new ValidationStructureList();
139     if (type.toLowerCase().equals("heat")) {
140       FileContentHandler content = getFileContent(fileToValidate);
141       if (!content.containsFile(SdcCommon.MANIFEST_NAME)) {
142         MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
143             LoggerTragetServiceName.VALIDATE_MANIFEST_CONTENT, ErrorLevel.ERROR.name(),
144             LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_ZIP);
145         throw new CoreException((new ErrorCode.ErrorCodeBuilder())
146             .withMessage(Messages.MANIFEST_NOT_EXIST.getErrorMessage())
147             .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
148             .withCategory(ErrorCategory.APPLICATION).build());
149       }
150       Map<String, List<ErrorMessage>> errors = validateHeatUploadData(content);
151       tree = HeatTreeManagerUtil.initHeatTreeManager(content);
152       tree.createTree();
153       if (MapUtils.isNotEmpty(errors)) {
154
155
156         tree.addErrors(errors);
157         validationStructureList.setImportStructure(tree.getTree());
158         //validationFileResponse.setStatus(ValidationFileStatus.Failure);
159       } else {
160         //validationFileResponse.setStatus(ValidationFileStatus.Success);
161       }
162     } else {
163       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
164           LoggerTragetServiceName.VALIDATE_FILE_TYPE, ErrorLevel.ERROR.name(),
165           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_FILE_TYPE);
166       throw new RuntimeException("invalid type:" + type);
167     }
168     validationFileResponse.setValidationData(validationStructureList);
169
170     mdcDataDebugMessage.debugExitMessage(null, null);
171     return validationFileResponse;
172   }
173
174   private Map<String, List<ErrorMessage>> validateHeatUploadData(FileContentHandler fileContentMap)
175       throws IOException {
176     ValidationManager validationManager =
177         ValidationManagerUtil.initValidationManager(fileContentMap);
178     return validationManager.validate();
179   }
180
181   private FileContentHandler getFileContent(InputStream is) throws IOException {
182     return getFileContentMapFromZip(FileUtils.toByteArray(is));
183
184
185   }
186
187 }