110d170b632cf0a5055086c4d134688ae586e3f3
[vfc/nfvo/driver/vnfm/svnfm.git] / huawei / vnfmadapter / VnfmadapterService / service / src / main / java / org / onap / vfc / nfvo / vnfm / svnfm / vnfmadapter / common / DownloadCsarManager.java
1 /*
2  * Copyright 2016-2017 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common;
18
19 import java.io.BufferedInputStream;
20 import java.io.BufferedOutputStream;
21 import java.io.File;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.util.Enumeration;
26 import java.util.zip.ZipEntry;
27 import java.util.zip.ZipFile;
28
29 import org.apache.http.Header;
30 import org.apache.http.HeaderElement;
31 import org.apache.http.HttpEntity;
32 import org.apache.http.HttpResponse;
33 import org.apache.http.NameValuePair;
34 import org.apache.http.client.methods.CloseableHttpResponse;
35 import org.apache.http.client.methods.HttpGet;
36 import org.apache.http.impl.client.CloseableHttpClient;
37 import org.apache.http.impl.client.HttpClients;
38 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.service.constant.Constant;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Utility class to download CSAR
44  *
45  * @author
46  * @version VFC 1.0 Sep 5, 2016
47  */
48 public class DownloadCsarManager {
49
50     private static final Logger LOG = LoggerFactory.getLogger(DownloadCsarManager.class);
51
52     public static final int CACHE = 100 * 1024;
53
54     private DownloadCsarManager() {
55         // private constructor
56     }
57
58     /**
59      * Download from given URL.
60      * 
61      * @param url String
62      * @return
63      */
64     public static String download(String url) {
65         return download(url, null);
66     }
67
68     /**
69      * Download from given URL to given file location.
70      * 
71      * @param url String
72      * @param filepath String
73      * @return
74      */
75     public static String download(String url, String filepath) {
76         String status = "";
77         try {
78             CloseableHttpClient client = HttpClients.createDefault();
79             HttpGet httpget = new HttpGet(url);
80             CloseableHttpResponse response = client.execute(httpget);
81
82             HttpEntity entity = response.getEntity();
83             InputStream is = entity.getContent();
84             if(filepath == null) {
85                 filepath = getFilePath(response); // NOSONAR
86             }
87
88             File file = new File(filepath);
89             file.getParentFile().mkdirs();
90             FileOutputStream fileout = new FileOutputStream(file);
91
92             byte[] buffer = new byte[CACHE];
93             int ch;
94             while((ch = is.read(buffer)) != -1) {
95                 fileout.write(buffer, 0, ch);
96             }
97             is.close();
98             fileout.flush();
99             fileout.close();
100             client.close();
101             status = Constant.DOWNLOADCSAR_SUCCESS;
102
103         } catch(Exception e) {
104             status = Constant.DOWNLOADCSAR_FAIL;
105             LOG.error("Download csar file failed! " + e.getMessage(), e);
106         }
107         return status;
108     }
109
110     /**
111      * Retrieve file path from given response.
112      * 
113      * @param response HttpResponse
114      * @return
115      */
116     public static String getFilePath(HttpResponse response) {
117         String filepath = System.getProperty("java.home");
118         String filename = getFileName(response);
119
120         if(filename != null) {
121             filepath += filename;
122         } else {
123             filepath += getRandomFileName();
124         }
125         return filepath;
126     }
127
128     /**
129      * Retrieve file name from given response.
130      * 
131      * @param response HttpResponse
132      * @return
133      */
134     public static String getFileName(HttpResponse response) {
135         Header contentHeader = response.getFirstHeader("Content-Disposition");
136         String filename = null;
137         if(contentHeader != null) {
138             HeaderElement[] values = contentHeader.getElements();
139             if(values.length == 1) {
140                 NameValuePair param = values[0].getParameterByName("filename");
141                 if(param != null) {
142                     try {
143                         filename = param.getValue();
144                     } catch(Exception e) {
145                         LOG.error("getting filename failed! " + e.getMessage(), e);
146                     }
147                 }
148             }
149         }
150         return filename;
151     }
152
153     /**
154      * Provides random file name.
155      * 
156      * @return
157      */
158     public static String getRandomFileName() {
159         return String.valueOf(System.currentTimeMillis());
160     }
161
162     /**
163      * unzip CSAR packge
164      * 
165      * @param fileName filePath
166      * @return
167      * @throws IOException
168      */
169     public static int unzipCSAR(String fileName, String filePath) {
170         final int BUFFER = 2048;
171         int status = 0;
172         ZipFile zipFile = null;
173         try {
174             zipFile = new ZipFile(fileName);
175             Enumeration emu = zipFile.entries();
176             while(emu.hasMoreElements()) {
177                 ZipEntry entry = (ZipEntry)emu.nextElement();
178                 // read directory as file first,so only need to create directory
179                 if(entry.isDirectory()) {
180                     new File(filePath + entry.getName()).mkdirs();
181                     continue;
182                 }
183                 BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
184                 File file = new File(filePath + entry.getName());
185                 // Because that is random to read zipfile,maybe the file is read first
186                 // before the directory is read,so we need to create directory first.
187                 File parent = file.getParentFile();
188                 if(parent != null && (!parent.exists())) {
189                     parent.mkdirs();
190                 }
191                 FileOutputStream fos = new FileOutputStream(file);
192                 BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
193
194                 int count;
195                 byte data[] = new byte[BUFFER];
196                 while((count = bis.read(data, 0, BUFFER)) != -1) {
197                     bos.write(data, 0, count);
198                 }
199                 bos.flush();
200                 bos.close();
201                 bis.close();
202             }
203
204             status = Constant.UNZIP_SUCCESS;
205
206         } catch(Exception e) {
207             status = Constant.UNZIP_FAIL;
208             LOG.error("Exception: " + e);
209         } finally {
210             if(zipFile != null) {
211                 try {
212                     zipFile.close();
213                 } catch(IOException e) {
214                     LOG.error("IOException: " + e);
215                 }
216             }
217         }
218         return status;
219     }
220 }