a763a361650f649b62a720082e0775a66f862156
[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     ArrayList<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());
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 = null;
134     if(null == packageId)
135     {
136         usedPackageId = ToolUtil.generateId();
137     } else {
138         usedPackageId = packageId;
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     {
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    * @param csarId package id
167    * @return download uri
168    */
169   public static String getPackagePath(String csarId) {
170     ArrayList<PackageData> packageList = new ArrayList<PackageData>();
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);
177     }
178     return downloadUri;
179   }
180
181
182   /**
183    * get package name from ftpUrl.
184    * @param ftpUrl ftp url
185    * @return package name
186    */
187   public static String getPackageName(String ftpUrl) {
188     int index = ftpUrl.lastIndexOf("/");
189     String packageName = ftpUrl.substring(index);
190     return packageName;
191   }
192
193   /**
194    * translate package data from database to package metadata.
195    * @param dbResult data from database
196    * @return package metadata list
197    */
198   public static List<PackageMeta> packageDataList2PackageMetaList(
199       List<PackageData> dbResult) {
200     ArrayList<PackageMeta> metas = new ArrayList<>();
201     PackageMeta meta = null;
202     if (! dbResult.isEmpty()) {
203       for (int i = 0; i < dbResult.size(); i++) {
204         PackageData data = dbResult.get(i);
205         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 =
218         packageData.getDownloadUri() + packageData.getName() + CommonConstant.CSAR_SUFFIX;
219     String packageUrl = getUrl(packageUri);
220     meta.setDownloadUri(packageUrl);
221     meta.setReport(packageData.getReport());
222     meta.setFormat(packageData.getFormat());
223     meta.setModifyTime(packageData.getModifyTime());
224     meta.setName(packageData.getName());
225     meta.setDetails(packageData.getDetails());
226     meta.setProvider(packageData.getProvider());
227     meta.setSize(packageData.getSize());
228     meta.setType(packageData.getType());
229     meta.setShortDesc(packageData.getShortDesc());
230     meta.setVersion(packageData.getVersion());
231     meta.setRemarks(packageData.getRemarks());
232     meta.setDownloadCount(packageData.getDownloadCount());
233     return meta;
234   }
235
236   /**
237    * add msb address as prefix to uri.
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     String urlresult = url.replace("\\", "/");
249     return urlresult;
250   }
251
252   public static String getDownloadUriHead() {
253     return MsbAddrConfig.getMsbAddress() + "/files/catalog-http";
254   }
255
256   /**
257    * get local path.
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    * @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       ArrayList<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         if (ToolUtil.isYamlFile(new File(unzipFile))) {
287           isXmlCsar = false;
288         }
289       }
290     } catch (IOException e1) {
291       LOG.error("judge package type error ! " + e1.getMessage());
292     }
293     if (isXmlCsar) {
294       basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
295     } else {
296       basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
297     }
298     return basicInfo;
299   }
300
301   private static PackageBasicInfo readCsarMeta(String unzipFile) {
302     PackageBasicInfo basicInfo = new PackageBasicInfo();
303     File file = new File(unzipFile);
304     try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
305       String tempString = null;
306       while ((tempString = reader.readLine()) != null) {
307         if (tempString.equals("")) {
308           continue;
309         }
310         int count1 = tempString.indexOf(":");
311         String meta = tempString.substring(0, count1).trim();
312         if (CommonConstant.CSAR_TYPE_META.equalsIgnoreCase(meta)) {
313           int count = tempString.indexOf(":") + 1;
314           basicInfo.setType(EnumType.valueOf(tempString.substring(count).trim()));
315         }
316         if (CommonConstant.CSAR_PROVIDER_META.equalsIgnoreCase(meta)) {
317           int count = tempString.indexOf(":") + 1;
318           basicInfo.setProvider(tempString.substring(count).trim());
319         }
320         if (CommonConstant.CSAR_VERSION_META.equalsIgnoreCase(meta)) {
321           int count = tempString.indexOf(":") + 1;
322           basicInfo.setVersion(tempString.substring(count).trim());
323         }
324       }
325       reader.close();
326     } catch (IOException e2) {
327       e2.printStackTrace();
328     }
329     return basicInfo;
330   }
331         /**
332          * Reads the manifest file in the package and fills the basic infor about package
333          * @param unzipFile
334          * @return basic infor about package
335          */     
336         private static PackageBasicInfo readManifest(String unzipFile) {
337
338                 // Fix the package type to CSAR, temporary
339                 PackageBasicInfo basicInfo = new PackageBasicInfo();
340                 basicInfo.setType(EnumType.CSAR);
341
342                 File file = new File(unzipFile);
343                 try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
344
345                         String tempString = null;
346                         while ((tempString = reader.readLine()) != null) {
347                                 
348                                 // If line is empty, ignore
349                                 if (tempString.equals("")) {
350                                         continue;
351                                 }
352
353                                 int count1 = tempString.indexOf(":");
354                                 String meta = tempString.substring(0, count1).trim();
355                                 
356                                 // Check for the package provider name
357                                 if (meta.equalsIgnoreCase(CommonConstant.MF_PROVIDER_META)) {
358                                         int count = tempString.indexOf(":") + 1;
359                                         basicInfo.setProvider(tempString.substring(count).trim());
360                                 }
361                                 
362                                 // Check for package version
363                                 if (meta.equalsIgnoreCase(CommonConstant.MF_VERSION_META)) {
364                                         int count = tempString.indexOf(":") + 1;
365                                         basicInfo.setVersion(tempString.substring(count).trim());
366                                 }
367                         }
368
369                         reader.close();
370                 } catch (IOException e) {
371                         LOG.error("Exception while parsing manifest file" + e);                 
372                 }
373
374                 return basicInfo;
375         }
376   /**
377    * get package format enum.
378    * @param format package format
379    * @return package format enum
380    */
381   public static EnumPackageFormat getPackageFormat(String format) {
382     if ("xml".equals(format)) {
383       return EnumPackageFormat.TOSCA_XML;
384     } else if ("yml".equals(format) || "yaml".equals(format)) {
385       return EnumPackageFormat.TOSCA_YAML;
386     } else {
387       return null;
388     }
389   }
390 }