push addional code
[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.core.validation.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.AsdcCommon;
33 import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList;
34 import org.openecomp.sdc.heat.services.tree.HeatTreeManager;
35 import org.openecomp.sdc.heat.services.tree.HeatTreeManagerUtil;
36 import org.openecomp.sdc.validation.UploadValidationManager;
37 import org.openecomp.sdc.validation.types.ValidationFileResponse;
38 import org.openecomp.sdc.validation.utils.ValidationManagerUtil;
39
40 import java.io.ByteArrayInputStream;
41 import java.io.File;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.util.ArrayList;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.zip.ZipEntry;
48 import java.util.zip.ZipInputStream;
49
50 public class UploadValidationManagerImpl implements UploadValidationManager {
51
52   private static FileContentHandler getFileContentMapFromZip(byte[] uploadFileData)
53       throws IOException, CoreException {
54     ZipEntry zipEntry;
55     List<String> folderList = new ArrayList<>();
56     FileContentHandler mapFileContent = new FileContentHandler();
57     try {
58       ZipInputStream inputZipStream;
59
60       byte[] fileByteContent;
61       String currentEntryName;
62       inputZipStream = new ZipInputStream(new ByteArrayInputStream(uploadFileData));
63
64       while ((zipEntry = inputZipStream.getNextEntry()) != null) {
65         currentEntryName = zipEntry.getName();
66         // else, get the file content (as byte array) and save it in a map.
67         fileByteContent = FileUtils.toByteArray(inputZipStream);
68
69         int index = lastIndexFileSeparatorIndex(currentEntryName);
70         String currSubstringWithoutSeparator =
71             currentEntryName.substring(index + 1, currentEntryName.length());
72         if (index != -1) {
73           if (currSubstringWithoutSeparator.length() > 0) {
74             mapFileContent.addFile(currentEntryName.substring(index + 1, currentEntryName.length()),
75                 fileByteContent);
76           } else {
77             folderList.add(currentEntryName);
78           }
79         } else {
80           mapFileContent.addFile(currentEntryName, fileByteContent);
81         }
82       }
83     } catch (RuntimeException exception) {
84       throw new IOException(exception);
85     }
86
87     if (CollectionUtils.isNotEmpty(folderList)) {
88       throw new CoreException((new ErrorCode.ErrorCodeBuilder())
89           .withMessage(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
90           .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
91           .withCategory(ErrorCategory.APPLICATION).build());
92
93     }
94
95     return mapFileContent;
96   }
97
98   private static int lastIndexFileSeparatorIndex(String filePath) {
99     int length = filePath.length() - 1;
100
101     for (int i = length; i >= 0; i--) {
102       char currChar = filePath.charAt(i);
103       if (currChar == '/' || currChar == File.separatorChar || currChar == File.pathSeparatorChar) {
104         return i;
105       }
106     }
107     // if we've reached to the start of the string and didn't find file separator - return -1
108     return -1;
109   }
110
111   @Override
112   public ValidationFileResponse validateFile(String type, InputStream fileToValidate)
113       throws IOException {
114
115     ValidationFileResponse validationFileResponse = new ValidationFileResponse();
116
117     HeatTreeManager tree;
118     ValidationStructureList validationStructureList = new ValidationStructureList();
119     if (type.toLowerCase().equals("heat")) {
120       FileContentHandler content = getFileContent(fileToValidate);
121       if (!content.containsFile(AsdcCommon.MANIFEST_NAME)) {
122         throw new CoreException((new ErrorCode.ErrorCodeBuilder())
123             .withMessage(Messages.MANIFEST_NOT_EXIST.getErrorMessage())
124             .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
125             .withCategory(ErrorCategory.APPLICATION).build());
126       }
127       Map<String, List<org.openecomp.sdc.datatypes.error.ErrorMessage>> errors =
128           validateHeatUploadData(content);
129       tree = HeatTreeManagerUtil.initHeatTreeManager(content);
130       tree.createTree();
131       if (MapUtils.isNotEmpty(errors)) {
132
133
134         tree.addErrors(errors);
135         validationStructureList.setImportStructure(tree.getTree());
136         //validationFileResponse.setStatus(ValidationFileStatus.Failure);
137       } else {
138         //validationFileResponse.setStatus(ValidationFileStatus.Success);
139       }
140     } else {
141       throw new RuntimeException("invalid type:" + type);
142     }
143     validationFileResponse.setValidationData(validationStructureList);
144     return validationFileResponse;
145   }
146
147   private Map<String, List<org.openecomp.sdc.datatypes.error.ErrorMessage>> validateHeatUploadData(
148       FileContentHandler fileContentMap)
149       throws IOException {
150     ValidationManager validationManager =
151         ValidationManagerUtil.initValidationManager(fileContentMap);
152     return validationManager.validate();
153   }
154
155   private FileContentHandler getFileContent(InputStream is) throws IOException {
156     return getFileContentMapFromZip(FileUtils.toByteArray(is));
157
158
159   }
160
161 }