Update license; improve coverage; add docs dir
[portal.git] / ecomp-portal-widget-ms / widget-ms / src / main / java / org / openecomp / portalapp / widget / utils / UnzipUtil.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the “License”);
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the “License”);
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
37  */
38 package org.openecomp.portalapp.widget.utils;
39
40 import java.io.BufferedOutputStream;
41 import java.io.File;
42 import java.io.FileInputStream;
43 import java.io.FileOutputStream;
44 import java.io.IOException;
45 import java.nio.file.Files;
46 import java.nio.file.Paths;
47 import java.util.HashMap;
48 import java.util.Map;
49 import java.util.Stack;
50 import java.util.zip.ZipEntry;
51 import java.util.zip.ZipInputStream;
52
53 import org.openecomp.portalapp.widget.constant.WidgetConstant;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 public class UnzipUtil {
58
59         /**
60          * Size of the buffer to read/write data
61          */
62         private static final int BUFFER_SIZE = 4096;
63         private static final Logger logger = LoggerFactory.getLogger(UnzipUtil.class);
64
65         /**
66          * Extracts a zip file specified by the zipFilePath to a directory specified by
67          * destDirectory (will be created if does not exists)
68          * 
69          * @param zipFilePath
70          *            path
71          * @param destDirectory
72          *            directory
73          * @param widgetName
74          *            name
75          * @return Map of contents
76          * @throws IOException
77          *             On error
78          */
79         public Map<String, byte[]> unzip_db(String zipFilePath, String destDirectory, String widgetName)
80                         throws IOException {
81
82                 logger.debug("UnzipUtil.unzip_db: unzip widget file {}", widgetName);
83                 File destDir = new File(destDirectory);
84                 if (!destDir.exists())
85                         destDir.mkdir();
86                 ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
87                 ZipEntry entry = zipIn.getNextEntry();
88                 Map<String, byte[]> map = new HashMap<>();
89
90                 String[] requiredKeys = { WidgetConstant.WIDGET_CONTROLLER_LOCATION, WidgetConstant.WIDGET_MARKUP_LOCATION,
91                                 WidgetConstant.WIDGET_STYLE_LOCATION };
92                 for (String k : requiredKeys)
93                         map.put(k, null);
94
95                 // iterates over entries in the zip file
96                 Stack<File> stack = new Stack<>();
97                 while (entry != null) {
98                         String filePath = destDirectory + File.separator + widgetName + File.separator
99                                         + entry.getName().substring(entry.getName().indexOf("/") + 1);
100                         final String entryShortName = entry.getName().substring(entry.getName().indexOf("/") + 1);
101                         logger.debug("UnzipUtil.unzip_db: file path {}, short name {}", filePath, entryShortName);
102                         if (!entry.isDirectory()) {
103                                 // if the entry is a file, extracts it
104                                 logger.debug("UnzipUtil.unzip_db: unzip and save widget file {}", filePath);
105                                 stack.push(new File(filePath));
106                                 extractFile(zipIn, filePath);
107                         } else {
108                                 // if the entry is a directory, make the directory
109                                 logger.debug("UnzipUtil.unzip_db: unzip and create widget folder {}", filePath);
110                                 File dir = new File(filePath);
111                                 stack.push(new File(filePath));
112                                 dir.mkdir();
113                         }
114                         // Is this one we need?
115                         if (map.containsKey(entryShortName))
116                                 map.put(entryShortName, Files.readAllBytes(Paths.get(filePath)));
117                         zipIn.closeEntry();
118                         entry = zipIn.getNextEntry();
119                 }
120                 zipIn.close();
121                 while (!stack.isEmpty())
122                         stack.pop().delete();
123
124                 for (String k : requiredKeys)
125                         if (!map.containsKey(k))
126                                 logger.warn("UnzipUtil.unzip_db: no zip archive entry found for required key {}", k);
127
128                 return map;
129         }
130
131         /**
132          * Extracts a zip entry (file entry)
133          * 
134          * @param zipIn
135          * @param filePath
136          * @throws IOException
137          */
138         private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
139                 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
140                 byte[] bytesIn = new byte[BUFFER_SIZE];
141                 int read = 0;
142                 while ((read = zipIn.read(bytesIn)) != -1) {
143                         bos.write(bytesIn, 0, read);
144                 }
145                 bos.close();
146         }
147 }