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