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