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