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