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