Update gvnfm-driver .gitreview file
[vfc/nfvo/driver/vnfm/gvnfm.git] / juju / juju-vnfmadapter / Juju-vnfmadapterService / service / src / main / java / org / onap / vfc / nfvo / vnfm / gvnfm / jujuvnfmadapter / common / DownloadCsarManager.java
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             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             is.close();
102             fileout.flush();
103             fileout.close();
104             status = Constant.DOWNLOADCSAR_SUCCESS;
105
106         } catch (Exception e) {
107             status = Constant.DOWNLOADCSAR_FAIL;
108             LOG.error("Download csar file failed! "+ e.getMessage(), e);
109         }
110         return status;
111     }
112
113     /**
114      * Retrieve file path from given response.
115      * @param response HttpResponse
116      * @return
117      */
118     public static String getFilePath(HttpResponse response) {
119         String filepath = System.getProperty("java.home");
120         String filename = getFileName(response);
121
122         if (filename != null) {
123             filepath += filename;
124         } else {
125             filepath += getRandomFileName();
126         }
127         return filepath;
128     }
129
130     /**
131      * Retrieve file name from given response.
132      * @param response HttpResponse
133      * @return
134      */
135     public static String getFileName(HttpResponse response) {
136         Header contentHeader = response.getFirstHeader("Content-Disposition");
137         String filename = null;
138         if (contentHeader != null) {
139             HeaderElement[] values = contentHeader.getElements();
140             if (values.length == 1) {
141                 NameValuePair param = values[0].getParameterByName("filename");
142                 if (param != null) {
143                     try {
144                         filename = param.getValue();
145                     } catch (Exception e) {
146                         LOG.error("getting filename failed! "+ e.getMessage(), e);
147                     }
148                 }
149             }
150         }
151         return filename;
152     }
153
154     /**
155      * Provides random file name.
156      * @return
157      */
158     public static String getRandomFileName() {
159         return String.valueOf(System.currentTimeMillis());
160     }
161     
162     /**
163      * unzip CSAR packge
164      * @param fileName filePath
165      * @return
166      */
167     public static int unzipCSAR(String fileName,String filePath){
168         final int BUFFER = 2048;
169         int status=0;
170         
171         try {
172             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                 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                 bos.flush();
201                 bos.close();
202                 bis.close();
203
204                 if(entry.getName().endsWith(".zip")){
205                     File subFile = new File(filePath+entry.getName());
206                     if(subFile.exists()){
207                         int subStatus = unzipCSAR(filePath+entry.getName(),subFile.getParent()+"/");
208                         if(subStatus != 0){
209                             LOG.error("sub file unzip fail!"+subFile.getName());
210                             status=Constant.UNZIP_FAIL;
211                             return status;
212                         }
213                     }
214                 }
215             }
216             status=Constant.UNZIP_SUCCESS;
217             zipFile.close();
218         } catch (Exception e) {
219                 status=Constant.UNZIP_FAIL;
220             e.printStackTrace();
221         }
222         return status;
223     }
224
225     private static  String getImagesPath(String csarfilepath){
226         File imageFile = new File(csarfilepath+"SoftwareImages");
227         if(imageFile.exists()){
228             File[] charmFiles = imageFile.listFiles();
229             for(File file : charmFiles){
230                 if(!file.getName().endsWith(".zip")){
231                     return file.getAbsolutePath();
232                 }
233             }
234         }
235         return csarfilepath;
236     }
237     public static void main(String[] args) {
238         System.out.println(getImagesPath("e:/juju/csar2/"));
239     }
240 }