Create new VSP, onboard from TOSCA file - UI
[sdc.git] / openecomp-be / lib / openecomp-common-lib / src / main / java / org / openecomp / sdc / common / utils / CommonUtil.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.common.utils;
22
23 import org.apache.commons.collections4.CollectionUtils;
24 import org.apache.commons.io.FilenameUtils;
25 import org.apache.commons.lang3.tuple.ImmutablePair;
26 import org.apache.commons.lang3.tuple.Pair;
27 import org.openecomp.core.utilities.file.FileContentHandler;
28 import org.openecomp.core.utilities.file.FileUtils;
29 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
30 import org.openecomp.sdc.common.errors.CoreException;
31 import org.openecomp.sdc.common.errors.ErrorCategory;
32 import org.openecomp.sdc.common.errors.ErrorCode;
33 import org.openecomp.sdc.common.errors.Messages;
34 import org.openecomp.sdc.logging.types.LoggerConstants;
35 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
36 import org.slf4j.MDC;
37
38 import java.io.ByteArrayInputStream;
39 import java.io.File;
40 import java.io.IOException;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.HashSet;
44 import java.util.List;
45 import java.util.Set;
46 import java.util.zip.ZipEntry;
47 import java.util.zip.ZipInputStream;
48
49 public class CommonUtil {
50
51   public static FileContentHandler validateAndUploadFileContent(OnboardingTypesEnum type,
52                                                                 byte[] uploadedFileData)
53       throws IOException {
54     return getFileContentMapFromOrchestrationCandidateZipAndValidateNoFolders(type, uploadedFileData);
55   }
56
57   /**
58    * Gets files out of the zip AND validates zip is flat (no folders)
59    *
60    *
61    * @param type
62    * @param uploadFileData zip file
63    * @return FileContentHandler if input is valid and has no folders
64    */
65   private static FileContentHandler getFileContentMapFromOrchestrationCandidateZipAndValidateNoFolders(
66       OnboardingTypesEnum type, byte[] uploadFileData)
67       throws IOException {
68     Pair<FileContentHandler,List<String> > pair = getFileContentMapFromOrchestrationCandidateZip(uploadFileData);
69
70     if(type.equals(OnboardingTypesEnum.ZIP)) {
71       validateNoFolders(pair.getRight());
72     }
73
74     return pair.getLeft();
75   }
76
77   public static Pair<FileContentHandler,List<String> > getFileContentMapFromOrchestrationCandidateZip(
78           byte[] uploadFileData)
79           throws IOException {
80     ZipEntry zipEntry;
81     List<String> folderList = new ArrayList<>();
82     FileContentHandler mapFileContent = new FileContentHandler();
83      try ( ByteArrayInputStream in = new ByteArrayInputStream(uploadFileData);
84           ZipInputStream inputZipStream = new ZipInputStream(in)){
85       byte[] fileByteContent;
86       String currentEntryName;
87
88       while ((zipEntry = inputZipStream.getNextEntry()) != null) {
89         currentEntryName = zipEntry.getName();
90         // else, get the file content (as byte array) and save it in a map.
91         fileByteContent = FileUtils.toByteArray(inputZipStream);
92
93         int index = lastIndexFileSeparatorIndex(currentEntryName);
94         if (index != -1) { //todo ?
95           folderList.add(currentEntryName);
96         }
97         if(isFile(currentEntryName)) {
98           mapFileContent.addFile(currentEntryName, fileByteContent);
99         }
100       }
101
102     } catch (RuntimeException exception) {
103       throw new IOException(exception);
104     }
105
106     return new ImmutablePair<>(mapFileContent,folderList);
107   }
108
109   private static boolean isFile(String currentEntryName) {
110     return !(currentEntryName.endsWith("\\") || currentEntryName.endsWith("/"));
111   }
112
113   private static void validateNoFolders(List<String> folderList) {
114     if (CollectionUtils.isNotEmpty(folderList)) {
115       MDC.put(LoggerConstants.ERROR_DESCRIPTION, LoggerErrorDescription.INVALID_ZIP);
116       throw new CoreException((new ErrorCode.ErrorCodeBuilder())
117           .withMessage(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
118           .withId(Messages.ZIP_SHOULD_NOT_CONTAIN_FOLDERS.getErrorMessage())
119           .withCategory(ErrorCategory.APPLICATION).build());
120     }
121   }
122
123   private static int lastIndexFileSeparatorIndex(String filePath) {
124     int length = filePath.length() - 1;
125
126     for (int i = length; i >= 0; i--) {
127       char currChar = filePath.charAt(i);
128       if (currChar == '/' || currChar == File.separatorChar || currChar == File.pathSeparatorChar) {
129         return i;
130       }
131     }
132     // if we've reached to the start of the string and didn't find file separator - return -1
133     return -1;
134   }
135
136   public static boolean validateFilesExtensions(Set<String> allowedExtensions, FileContentHandler
137       files) {
138     for (String fileName : files.getFileList()) {
139       if (!allowedExtensions.contains(FilenameUtils.getExtension(fileName))) {
140         return false;
141       }
142     }
143     return true;
144   }
145
146   public static boolean validateAllFilesYml(FileContentHandler files) {
147     Set<String> allowedExtensions = new HashSet<>(Arrays.asList("yml", "yaml"));
148     return validateFilesExtensions(allowedExtensions, files);
149   }
150 }