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