d246705c4bc134b2515a57ca538e0168a2aafe7b
[vfc/nfvo/driver/vnfm/gvnfm.git] /
1 /*
2  * Copyright 2016 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.gvnfm.jujuvnfmadapter.common;
18
19 import java.io.BufferedInputStream;
20 import java.io.BufferedOutputStream;
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.FileNotFoundException;
24 import java.io.FileOutputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.util.Enumeration;
28 import java.util.zip.ZipEntry;
29 import java.util.zip.ZipFile;
30
31 import org.apache.http.Header;
32 import org.apache.http.HeaderElement;
33 import org.apache.http.HttpEntity;
34 import org.apache.http.HttpResponse;
35 import org.apache.http.NameValuePair;
36 import org.apache.http.client.methods.CloseableHttpResponse;
37 import org.apache.http.client.methods.HttpGet;
38 import org.apache.http.impl.client.CloseableHttpClient;
39 import org.apache.http.impl.client.HttpClients;
40 import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.service.constant.Constant;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import net.sf.json.JSONArray;
45 import net.sf.json.JSONObject;
46
47 /**
48  * Utility class to download CSAR
49  *
50  * @author
51  * @version      NFVO 0.5  Sep 5, 2016
52  *
53  */
54 public class DownloadCsarManager {
55
56     private static final Logger LOG = LoggerFactory.getLogger(DownloadCsarManager.class);
57
58     public static final int CACHE = 100 * 1024;
59
60     private DownloadCsarManager(){
61         //private constructor
62     }
63
64     /**
65      * Download from given URL.
66      * @param url String
67      * @return
68      */
69     public static String download(String url) {
70         return download(url, null);
71     }
72
73     /**
74      * Download from given URL to given file location.
75      * @param url String
76      * @param filepath String
77      * @return
78      */
79     public static String download(String url, String filepath) {
80         String status = "";
81         try( 
82             CloseableHttpClient client = HttpClients.createDefault()){
83             HttpGet httpget = new HttpGet(url);
84             CloseableHttpResponse response = client.execute(httpget);
85
86             HttpEntity entity = response.getEntity();
87             InputStream is = entity.getContent();
88             if (filepath == null){
89                 filepath = getFilePath(response); //NOSONAR
90             }
91
92             File file = new File(filepath);
93             file.getParentFile().mkdirs();
94             try(FileOutputStream fileout = new FileOutputStream(file)){
95
96             byte[] buffer = new byte[CACHE];
97             int ch;
98             while ((ch = is.read(buffer)) != -1) {
99                 fileout.write(buffer,0,ch);
100             }
101             }
102             is.close();
103             //fileout.flush();
104             //fileout.close();
105             status = Constant.DOWNLOADCSAR_SUCCESS;
106
107         } catch (Exception e) {
108             status = Constant.DOWNLOADCSAR_FAIL;
109             LOG.error("Download csar file failed! "+ e.getMessage(), e);
110         }
111         return status;
112     }
113
114     /**
115      * Retrieve file path from given response.
116      * @param response HttpResponse
117      * @return
118      */
119     public static String getFilePath(HttpResponse response) {
120         String filepath = System.getProperty("java.home");
121         String filename = getFileName(response);
122
123         if (filename != null) {
124             filepath += filename;
125         } else {
126             filepath += getRandomFileName();
127         }
128         return filepath;
129     }
130
131     /**
132      * Retrieve file name from given response.
133      * @param response HttpResponse
134      * @return
135      */
136     public static String getFileName(HttpResponse response) {
137         Header contentHeader = response.getFirstHeader("Content-Disposition");
138         String filename = null;
139         if (contentHeader != null) {
140             HeaderElement[] values = contentHeader.getElements();
141             if (values.length == 1) {
142                 NameValuePair param = values[0].getParameterByName("filename");
143                 if (param != null) {
144                     try {
145                         filename = param.getValue();
146                     } catch (Exception e) {
147                         LOG.error("getting filename failed! "+ e.getMessage(), e);
148                     }
149                 }
150             }
151         }
152         return filename;
153     }
154
155     /**
156      * Provides random file name.
157      * @return
158      */
159     public static String getRandomFileName() {
160         return String.valueOf(System.currentTimeMillis());
161     }
162     
163     /**
164      * unzip CSAR packge
165      * @param fileName filePath
166      * @return
167      */
168     public static int unzipCSAR(String fileName,String filePath){
169         final int BUFFER = 2048;
170         int status=0;
171         
172         try ( ZipFile zipFile = new ZipFile(fileName)){
173             Enumeration emu = zipFile.entries();
174             int i=0;
175             while(emu.hasMoreElements()){
176                 ZipEntry entry = (ZipEntry)emu.nextElement();
177                 //read directory as file first,so only need to create directory
178                 if (entry.isDirectory())
179                 {
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                 try(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                 {
198                     bos.write(data, 0, count);
199                 }
200                 }
201                 //bos.flush();
202                 //bos.close();
203                 bis.close();
204
205                 if(entry.getName().endsWith(".zip")){
206                     File subFile = new File(filePath+entry.getName());
207                     if(subFile.exists()){
208                         int subStatus = unzipCSAR(filePath+entry.getName(),subFile.getParent()+"/");
209                         if(subStatus != 0){
210                             LOG.error("sub file unzip fail!"+subFile.getName());
211                             status=Constant.UNZIP_FAIL;
212                             return status;
213                         }
214                     }
215                 }
216             }
217             status=Constant.UNZIP_SUCCESS;
218             zipFile.close();
219         } catch (Exception e) {
220                 status=Constant.UNZIP_FAIL;
221             //e.printStackTrace();
222                 LOG.error("unzipCSAR Exception: ",e);
223
224         }
225         return status;
226     }
227
228     private static  String getImagesPath(String csarfilepath){
229         File imageFile = new File(csarfilepath+"SoftwareImages");
230         if(imageFile.exists()){
231             File[] charmFiles = imageFile.listFiles();
232             for(File file : charmFiles){
233                 if(!file.getName().endsWith(".zip")){
234                     return file.getAbsolutePath();
235                 }
236             }
237         }
238         return csarfilepath;
239     }
240     public static void main(String[] args) {
241         System.out.println(getImagesPath("e:/juju/csar2/"));
242     }
243 }