daa580312a2be661436c7ee8cb7b2746780f33f1
[vnfsdk/refrepo.git] /
1 /**
2  * Copyright 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.vnfsdk.marketplace.wrapper;
18
19 import java.io.BufferedReader;
20 import java.io.File;
21 import java.io.FileReader;
22 import java.io.IOException;
23 import java.text.SimpleDateFormat;
24 import java.util.ArrayList;
25 import java.util.Date;
26 import java.util.List;
27
28 import org.onap.vnfsdk.marketplace.common.CommonConstant;
29 import org.onap.vnfsdk.marketplace.common.FileUtil;
30 import org.onap.vnfsdk.marketplace.common.MsbAddrConfig;
31 import org.onap.vnfsdk.marketplace.common.ToolUtil;
32 import org.onap.vnfsdk.marketplace.db.entity.PackageData;
33 import org.onap.vnfsdk.marketplace.db.exception.MarketplaceResourceException;
34 import org.onap.vnfsdk.marketplace.db.resource.PackageManager;
35 import org.onap.vnfsdk.marketplace.entity.EnumType;
36 import org.onap.vnfsdk.marketplace.entity.request.PackageBasicInfo;
37 import org.onap.vnfsdk.marketplace.entity.response.PackageMeta;
38 import org.onap.vnfsdk.marketplace.model.parser.EnumPackageFormat;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import com.google.gson.internal.LinkedTreeMap;
43
44 public class PackageWrapperUtil {
45
46     private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class);
47
48     private PackageWrapperUtil() {
49     }
50
51     public static long getPacakgeSize(String fileLocation) {
52         File file = new File(fileLocation);
53         return file.length();
54     }
55
56     /**
57      * change package metadata to fix database.
58      * 
59      * @param meta package metadata
60      * @param details
61      * @return package data in database
62      */
63     public static PackageData getPackageData(PackageMeta meta) {
64         PackageData packageData = new PackageData();
65         packageData.setCreateTime(meta.getCreateTime());
66         packageData.setDeletionPending(String.valueOf(meta.isDeletionPending()));
67         packageData.setDownloadUri(meta.getDownloadUri());
68         packageData.setFormat(meta.getFormat());
69         packageData.setModifyTime(meta.getModifyTime());
70         packageData.setName(meta.getName());
71         packageData.setCsarId(meta.getCsarId());
72         packageData.setProvider(meta.getProvider());
73         String fileSize = meta.getSize();
74         packageData.setSize(fileSize);
75         packageData.setType(meta.getType());
76         packageData.setVersion(meta.getVersion());
77         packageData.setDetails(meta.getDetails());
78         packageData.setShortDesc(meta.getShortDesc());
79         packageData.setRemarks(meta.getRemarks());
80         return packageData;
81     }
82
83     /**
84      * judge wether is the end of upload package.
85      * 
86      * @param contentRange package sise range
87      * @param csarName package name
88      * @return boolean
89      */
90     public static boolean isUploadEnd(String contentRange) {
91         String range = contentRange;
92         range = range.replace("bytes", "").trim();
93         range = range.substring(0, range.indexOf("/"));
94         String size = contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim();
95         int fileSize = Integer.parseInt(size);
96         String[] ranges = range.split("-");
97         int endPosition = Integer.parseInt(ranges[1]) + 1;
98         return endPosition >= fileSize;
99     }
100
101     /**
102      * get package detail by package id.
103      * 
104      * @param csarId package id
105      * @return package detail
106      */
107     public static PackageData getPackageInfoById(String csarId) {
108         PackageData result = new PackageData();
109         List<PackageData> packageDataList = new ArrayList<>();
110         try {
111             packageDataList = PackageManager.getInstance().queryPackageByCsarId(csarId);
112             if(packageDataList != null && !packageDataList.isEmpty()) {
113                 result = packageDataList.get(0);
114             }
115         } catch(MarketplaceResourceException e1) {
116             LOG.error("query package by csarId from db error ! " + e1.getMessage(), e1);
117         }
118         return result;
119     }
120
121     /**
122      * get package metadata from basic info.
123      * 
124      * @param fileName package name
125      * @param fileLocation the location of package
126      * @param basic basic infomation of package. include version, type and provider
127      * @return package metadata
128      */
129     public static PackageMeta getPackageMeta(String packageId, String fileName, String fileLocation,
130             PackageBasicInfo basic, String details) {
131         PackageMeta packageMeta = new PackageMeta();
132         long size = getPacakgeSize(fileLocation);
133         packageMeta.setFormat(basic.getFormat());
134         String usedPackageId = packageId;
135         if(null == packageId) {
136             usedPackageId = ToolUtil.generateId();
137         }
138
139         packageMeta.setCsarId(usedPackageId);
140
141         packageMeta.setName(fileName.replace(CommonConstant.CSAR_SUFFIX, ""));
142         packageMeta.setType(basic.getType().toString());
143         packageMeta.setVersion(basic.getVersion());
144         packageMeta.setProvider(basic.getProvider());
145         packageMeta.setDeletionPending(false);
146         String sizeStr = ToolUtil.getFormatFileSize(size);
147         packageMeta.setSize(sizeStr);
148         SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
149         String currentTime = sdf1.format(new Date());
150         packageMeta.setCreateTime(currentTime);
151         packageMeta.setModifyTime(currentTime);
152         if(null != details) {
153             LinkedTreeMap<String, String> csarDetails = ToolUtil.fromJson(details, LinkedTreeMap.class);
154             packageMeta.setDetails(csarDetails.get("details"));
155             packageMeta.setShortDesc(csarDetails.get("shortDesc"));
156             packageMeta.setRemarks(csarDetails.get("remarks"));
157         }
158         return packageMeta;
159     }
160
161     /**
162      * get downloadUri from package metadata.
163      * 
164      * @param csarId package id
165      * @return download uri
166      */
167     public static String getPackagePath(String csarId) {
168         List<PackageData> packageList = new ArrayList<>();
169         String downloadUri = null;
170         try {
171             packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
172             downloadUri = packageList.get(0).getDownloadUri();
173         } catch(MarketplaceResourceException e1) {
174             LOG.error("Query CSAR package by ID failed ! csarId = " + csarId, e1);
175         }
176         return downloadUri;
177     }
178
179     /**
180      * get package name from ftpUrl.
181      * 
182      * @param ftpUrl ftp url
183      * @return package name
184      */
185     public static String getPackageName(String ftpUrl) {
186         int index = ftpUrl.lastIndexOf("/");
187
188         return ftpUrl.substring(index);
189     }
190
191     /**
192      * translate package data from database to package metadata.
193      * 
194      * @param dbResult data from database
195      * @return package metadata list
196      */
197     public static List<PackageMeta> packageDataList2PackageMetaList(List<PackageData> dbResult) {
198         ArrayList<PackageMeta> metas = new ArrayList<>();
199         if(!dbResult.isEmpty()) {
200             for(int i = 0; i < dbResult.size(); i++) {
201                 PackageData data = dbResult.get(i);
202                 PackageMeta meta = packageData2PackageMeta(data);
203                 metas.add(meta);
204             }
205         }
206         return metas;
207     }
208
209     public static PackageMeta packageData2PackageMeta(PackageData packageData) {
210         PackageMeta meta = new PackageMeta();
211         meta.setCsarId(packageData.getCsarId());
212         meta.setCreateTime(packageData.getCreateTime());
213         meta.setDeletionPending(Boolean.getBoolean(packageData.getDeletionPending()));
214         String packageUri = packageData.getDownloadUri() + packageData.getName() + CommonConstant.CSAR_SUFFIX;
215         String packageUrl = getUrl(packageUri);
216         meta.setDownloadUri(packageUrl);
217         meta.setReport(packageData.getReport());
218         meta.setFormat(packageData.getFormat());
219         meta.setModifyTime(packageData.getModifyTime());
220         meta.setName(packageData.getName());
221         meta.setDetails(packageData.getDetails());
222         meta.setProvider(packageData.getProvider());
223         meta.setSize(packageData.getSize());
224         meta.setType(packageData.getType());
225         meta.setShortDesc(packageData.getShortDesc());
226         meta.setVersion(packageData.getVersion());
227         meta.setRemarks(packageData.getRemarks());
228         meta.setDownloadCount(packageData.getDownloadCount());
229         return meta;
230     }
231
232     /**
233      * add msb address as prefix to uri.
234      * 
235      * @param uri uri
236      * @return url
237      */
238     public static String getUrl(String uri) {
239         String url = getDownloadUriHead();
240         if(url.endsWith("/") && uri.startsWith("/")) {
241             url += uri.substring(1);
242         } else {
243             url += uri;
244         }
245         return url.replace("\\", "/");
246     }
247
248     public static String getDownloadUriHead() {
249         return MsbAddrConfig.getMsbAddress() + "/files/catalog-http";
250     }
251
252     /**
253      * get local path.
254      * 
255      * @param uri uri
256      * @return local path
257      */
258     public static String getLocalPath(String uri) {
259         File srcDir = new File(uri);
260         String localPath = srcDir.getAbsolutePath();
261         return localPath.replace("\\", "/");
262     }
263
264     /**
265      * get package basic information.
266      * 
267      * @param fileLocation package location
268      * @return package basic information
269      */
270     public static PackageBasicInfo getPacageBasicInfo(String fileLocation) {
271         PackageBasicInfo basicInfo = new PackageBasicInfo();
272         String unzipDir = ToolUtil.getUnzipDir(fileLocation);
273         boolean isXmlCsar = false;
274         try {
275             String tempfolder = unzipDir;
276             List<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
277             if(unzipFiles.isEmpty()) {
278                 isXmlCsar = true;
279             }
280             for(String unzipFile : unzipFiles) {
281                 if(unzipFile.endsWith(CommonConstant.MANIFEST)) {
282                     basicInfo = readManifest(unzipFile);
283                 }
284
285                 if(unzipFile.endsWith(CommonConstant.CSAR_META)) {
286                     basicInfo = readMetaData(unzipFile);
287                 }
288
289                 if(ToolUtil.isYamlFile(new File(unzipFile))) {
290                     isXmlCsar = false;
291                 }
292             }
293         } catch(IOException e1) {
294             LOG.error("judge package type error ! " + e1.getMessage(), e1);
295         }
296         if(isXmlCsar) {
297             basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
298         } else {
299             basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
300         }
301         return basicInfo;
302     }
303
304     /**
305      * Reads the manifest file in the package and fills the basic infor about package
306      * 
307      * @param unzipFile
308      * @return basic infor about package
309      */
310     private static PackageBasicInfo readMetaData(String unzipFile) {
311
312         // Fix the package type to CSAR, temporary
313         PackageBasicInfo basicInfo = new PackageBasicInfo();
314         basicInfo.setType(EnumType.CSAR);
315
316         File file = new File(unzipFile);
317         try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
318
319             for(String tempString; (tempString = reader.readLine()) != null;) {
320                 // If line is empty, ignore
321                 if("".equals(tempString)) {
322                     continue;
323                 }
324
325                 int count1 = tempString.indexOf(":");
326                 String meta = tempString.substring(0, count1).trim();
327
328                 // Check for the package provider name
329                 if(meta.equalsIgnoreCase(CommonConstant.CSAR_PROVIDER_META)) {
330                     int count = tempString.indexOf(":") + 1;
331                     basicInfo.setProvider(tempString.substring(count).trim());
332                 }
333
334                 // Check for package version
335                 if(meta.equalsIgnoreCase(CommonConstant.CSAR_VERSION_META)) {
336                     int count = tempString.indexOf(":") + 1;
337                     basicInfo.setVersion(tempString.substring(count).trim());
338                 }
339
340                 // Check for package type
341                 if(meta.equalsIgnoreCase(CommonConstant.CSAR_TYPE_META)) {
342                     int count = tempString.indexOf(":") + 1;
343
344                     basicInfo.setType(getEnumType(tempString.substring(count).trim()));
345                 }
346             }
347
348             reader.close();
349         } catch(IOException e) {
350             LOG.error("Exception while parsing manifest file" + e, e);
351         }
352
353         return basicInfo;
354     }
355
356     private static EnumType getEnumType(String type) {
357         EnumType vnfType = EnumType.CSAR;
358         if(type == "CSAR") {
359             vnfType = EnumType.CSAR;
360         }
361
362         if(type == "GSAR") {
363             vnfType = EnumType.GSAR;
364         }
365
366         if(type == "NSAR") {
367             vnfType = EnumType.NSAR;
368         }
369
370         if(type == "SSAR") {
371             vnfType = EnumType.SSAR;
372         }
373
374         if(type == "NFAR") {
375             vnfType = EnumType.NFAR;
376         }
377
378         return vnfType;
379     }
380
381     private static PackageBasicInfo readManifest(String unzipFile) {
382
383         // Fix the package type to CSAR, temporary
384         PackageBasicInfo basicInfo = new PackageBasicInfo();
385         basicInfo.setType(EnumType.CSAR);
386
387         File file = new File(unzipFile);
388         try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
389
390             for(String tempString; (tempString = reader.readLine()) != null;) {
391                 // If line is empty, ignore
392                 if("".equals(tempString)) {
393                     continue;
394                 }
395
396                 int count1 = tempString.indexOf(":");
397                 String meta = tempString.substring(0, count1).trim();
398
399                 // Check for the package provider name
400                 if(meta.equalsIgnoreCase(CommonConstant.MF_PROVIDER_META)) {
401                     int count = tempString.indexOf(":") + 1;
402                     basicInfo.setProvider(tempString.substring(count).trim());
403                 }
404
405                 // Check for package version
406                 if(meta.equalsIgnoreCase(CommonConstant.MF_VERSION_META)) {
407                     int count = tempString.indexOf(":") + 1;
408                     basicInfo.setVersion(tempString.substring(count).trim());
409                 }
410             }
411
412             reader.close();
413         } catch(IOException e) {
414             LOG.error("Exception while parsing manifest file" + e, e);
415         }
416
417         return basicInfo;
418     }
419
420     /**
421      * get package format enum.
422      * 
423      * @param format package format
424      * @return package format enum
425      */
426     public static EnumPackageFormat getPackageFormat(String format) {
427         if("xml".equals(format)) {
428             return EnumPackageFormat.TOSCA_XML;
429         } else if("yml".equals(format) || "yaml".equals(format)) {
430             return EnumPackageFormat.TOSCA_YAML;
431         } else {
432             return null;
433         }
434     }
435 }