ab94e9839625b42907c23b89a1703bd0bd018b5e
[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 package org.onap.vnfsdk.marketplace.wrapper;
17
18 import java.io.BufferedReader;
19 import java.io.File;
20 import java.io.FileReader;
21 import java.io.IOException;
22 import java.text.SimpleDateFormat;
23 import java.util.ArrayList;
24 import java.util.Date;
25 import java.util.List;
26
27 import org.onap.vnfsdk.marketplace.common.CommonConstant;
28 import org.onap.vnfsdk.marketplace.common.FileUtil;
29 import org.onap.vnfsdk.marketplace.common.MsbAddrConfig;
30 import org.onap.vnfsdk.marketplace.common.ToolUtil;
31 import org.onap.vnfsdk.marketplace.db.entity.PackageData;
32 import org.onap.vnfsdk.marketplace.db.exception.MarketplaceResourceException;
33 import org.onap.vnfsdk.marketplace.db.resource.PackageManager;
34 import org.onap.vnfsdk.marketplace.entity.EnumType;
35 import org.onap.vnfsdk.marketplace.entity.request.PackageBasicInfo;
36 import org.onap.vnfsdk.marketplace.entity.response.PackageMeta;
37 import org.onap.vnfsdk.marketplace.model.parser.EnumPackageFormat;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import com.google.gson.internal.LinkedTreeMap;
42
43
44 public class PackageWrapperUtil {
45   private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class);
46
47   private PackageWrapperUtil() {
48   }
49
50   public static long getPacakgeSize(String fileLocation) {
51     File file = new File(fileLocation);
52     return file.length();
53   }
54
55   /**
56    * change package metadata to fix database.
57    * @param meta package metadata
58  * @param details
59    * @return package data in database
60    */
61   public static PackageData getPackageData(PackageMeta meta) {
62     PackageData packageData = new PackageData();
63     packageData.setCreateTime(meta.getCreateTime());
64     packageData.setDeletionPending(String.valueOf(meta.isDeletionPending()));
65     packageData.setDownloadUri(meta.getDownloadUri());
66     packageData.setFormat(meta.getFormat());
67     packageData.setModifyTime(meta.getModifyTime());
68     packageData.setName(meta.getName());
69     packageData.setCsarId(meta.getCsarId());
70     packageData.setProvider(meta.getProvider());
71     String fileSize = meta.getSize();
72     packageData.setSize(fileSize);
73     packageData.setType(meta.getType());
74     packageData.setVersion(meta.getVersion());
75     packageData.setDetails(meta.getDetails());
76     packageData.setShortDesc(meta.getShortDesc());
77     packageData.setRemarks(meta.getRemarks());
78     return packageData;
79   }
80
81   /**
82    * judge wether is the end of upload package.
83    * @param contentRange package sise range
84    * @param csarName package name
85    * @return boolean
86    */
87   public static boolean isUploadEnd(String contentRange) {
88     String range = contentRange;
89     range = range.replace("bytes", "").trim();
90     range = range.substring(0, range.indexOf("/"));
91     String size =
92         contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim();
93     int fileSize = Integer.parseInt(size);
94     String[] ranges = range.split("-");
95     int endPosition = Integer.parseInt(ranges[1]) + 1;
96     if (endPosition >= fileSize) {
97       return true;
98     }
99     return false;
100   }
101
102   /**
103    * get package detail by package id.
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 = PackageManager.getInstance().queryPackageByCsarId(csarId).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    * @param fileName package name
124    * @param fileLocation the location of package
125    * @param basic basic infomation of package. include version, type and provider
126    * @return package metadata
127    */
128   public static PackageMeta getPackageMeta(String packageId, String fileName, String fileLocation,
129     PackageBasicInfo basic, String details) {
130     PackageMeta packageMeta = new PackageMeta();
131     long size = getPacakgeSize(fileLocation);
132     packageMeta.setFormat(basic.getFormat());
133     String usedPackageId = packageId;
134     if(null == packageId)
135     {
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     {
154     LinkedTreeMap<String,String> csarDetails = ToolUtil.fromJson(details, LinkedTreeMap.class);
155     packageMeta.setDetails(csarDetails.get("details"));
156     packageMeta.setShortDesc(csarDetails.get("shortDesc"));
157     packageMeta.setRemarks(csarDetails.get("remarks"));
158     }
159     return packageMeta;
160   }
161
162   /**
163    * get downloadUri from package metadata.
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   /**
181    * get package name from ftpUrl.
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    * @param dbResult data from database
194    * @return package metadata list
195    */
196   public static List<PackageMeta> packageDataList2PackageMetaList(
197       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 =
215         packageData.getDownloadUri() + packageData.getName() + CommonConstant.CSAR_SUFFIX;
216     String packageUrl = getUrl(packageUri);
217     meta.setDownloadUri(packageUrl);
218     meta.setReport(packageData.getReport());
219     meta.setFormat(packageData.getFormat());
220     meta.setModifyTime(packageData.getModifyTime());
221     meta.setName(packageData.getName());
222     meta.setDetails(packageData.getDetails());
223     meta.setProvider(packageData.getProvider());
224     meta.setSize(packageData.getSize());
225     meta.setType(packageData.getType());
226     meta.setShortDesc(packageData.getShortDesc());
227     meta.setVersion(packageData.getVersion());
228     meta.setRemarks(packageData.getRemarks());
229     meta.setDownloadCount(packageData.getDownloadCount());
230     return meta;
231   }
232
233   /**
234    * add msb address as prefix to uri.
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    * @param uri uri
255    * @return local path
256    */
257   public static String getLocalPath(String uri) {
258     File srcDir = new File(uri);
259     String localPath = srcDir.getAbsolutePath();
260     return localPath.replace("\\", "/");
261   }
262
263   /**
264    * get package basic information.
265    * @param fileLocation package location
266    * @return package basic information
267    */
268   public static PackageBasicInfo getPacageBasicInfo(String fileLocation) {
269     PackageBasicInfo basicInfo = new PackageBasicInfo();
270     String unzipDir = ToolUtil.getUnzipDir(fileLocation);
271     boolean isXmlCsar = false;
272     try {
273       String tempfolder = unzipDir;
274       List<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
275       if (unzipFiles.isEmpty()) {
276         isXmlCsar = true;
277       }
278       for (String unzipFile : unzipFiles) {
279         if (unzipFile.endsWith(CommonConstant.MANIFEST)) {
280           basicInfo = readManifest(unzipFile);
281         }
282         
283         if (unzipFile.endsWith(CommonConstant.CSAR_META)) {
284             basicInfo = readMetaData(unzipFile);
285         }
286         
287         if (ToolUtil.isYamlFile(new File(unzipFile))) {
288           isXmlCsar = false;
289         }
290       }
291     } catch (IOException e1) {
292       LOG.error("judge package type error ! " + e1.getMessage(), e1);
293     }
294     if (isXmlCsar) {
295       basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
296     } else {
297       basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
298     }
299     return basicInfo;
300   }
301
302   /**
303    * Reads the manifest file in the package and fills the basic infor about package
304    * @param unzipFile
305    * @return basic infor about package
306    */
307   private static PackageBasicInfo readMetaData(String unzipFile) {
308
309     // Fix the package type to CSAR, temporary
310     PackageBasicInfo basicInfo = new PackageBasicInfo();
311     basicInfo.setType(EnumType.CSAR);
312
313     File file = new File(unzipFile);
314     try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
315
316       for(String tempString; (tempString = reader.readLine()) != null;)
317       {
318           // If line is empty, ignore
319           if ("".equals(tempString)) {
320             continue;
321           }
322
323           int count1 = tempString.indexOf(":");
324           String meta = tempString.substring(0, count1).trim();
325
326           // Check for the package provider name
327           if (meta.equalsIgnoreCase(CommonConstant.CSAR_PROVIDER_META)) {
328             int count = tempString.indexOf(":") + 1;
329             basicInfo.setProvider(tempString.substring(count).trim());
330           }
331
332           // Check for package version
333           if (meta.equalsIgnoreCase(CommonConstant.CSAR_VERSION_META)) {
334             int count = tempString.indexOf(":") + 1;
335             basicInfo.setVersion(tempString.substring(count).trim());
336           }
337           
338        // Check for package type
339           if (meta.equalsIgnoreCase(CommonConstant.CSAR_TYPE_META)) {
340             int count = tempString.indexOf(":") + 1;
341            
342             basicInfo.setType(getEnumType(tempString.substring(count).trim()));
343           }
344       }
345
346       reader.close();
347     } catch (IOException e) {
348       LOG.error("Exception while parsing manifest file" + e, e);
349     }
350
351     return basicInfo;
352   }
353   
354   private static EnumType getEnumType (String type)
355   {
356           EnumType vnfType = EnumType.CSAR;
357           if (type == "CSAR")
358           {
359                   vnfType = EnumType.CSAR;
360           }
361           
362           if (type == "GSAR")
363           {
364                   vnfType = EnumType.GSAR;
365           }
366           
367           if (type == "NSAR")
368           {
369                   vnfType = EnumType.NSAR;
370           }
371           
372           if (type == "SSAR")
373           {
374                   vnfType = EnumType.SSAR;
375           }
376           
377           if (type == "NFAR")
378           {
379                   vnfType = EnumType.NFAR;
380           }
381           
382           return vnfType;
383   }
384   
385   private static PackageBasicInfo readManifest(String unzipFile) {
386
387             // Fix the package type to CSAR, temporary
388             PackageBasicInfo basicInfo = new PackageBasicInfo();
389             basicInfo.setType(EnumType.CSAR);
390
391             File file = new File(unzipFile);
392             try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
393
394               for(String tempString; (tempString = reader.readLine()) != null;)
395               {
396                   // If line is empty, ignore
397                   if ("".equals(tempString)) {
398                     continue;
399                   }
400
401                   int count1 = tempString.indexOf(":");
402                   String meta = tempString.substring(0, count1).trim();
403
404                   // Check for the package provider name
405                   if (meta.equalsIgnoreCase(CommonConstant.MF_PROVIDER_META)) {
406                     int count = tempString.indexOf(":") + 1;
407                     basicInfo.setProvider(tempString.substring(count).trim());
408                   }
409
410                   // Check for package version
411                   if (meta.equalsIgnoreCase(CommonConstant.MF_VERSION_META)) {
412                     int count = tempString.indexOf(":") + 1;
413                     basicInfo.setVersion(tempString.substring(count).trim());
414                   }
415               }
416
417               reader.close();
418             } catch (IOException e) {
419               LOG.error("Exception while parsing manifest file" + e, e);
420             }
421
422             return basicInfo;
423           }
424   /**
425    * get package format enum.
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 }
439