a133490f98594a85cadc7fd224399c10b0e5611b
[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
26 import org.onap.vnfsdk.marketplace.common.CommonConstant;
27 import org.onap.vnfsdk.marketplace.common.FileUtil;
28 import org.onap.vnfsdk.marketplace.common.MsbAddrConfig;
29 import org.onap.vnfsdk.marketplace.common.ToolUtil;
30 import org.onap.vnfsdk.marketplace.db.entity.PackageData;
31 import org.onap.vnfsdk.marketplace.db.exception.MarketplaceResourceException;
32 import org.onap.vnfsdk.marketplace.db.resource.PackageManager;
33 import org.onap.vnfsdk.marketplace.entity.EnumType;
34 import org.onap.vnfsdk.marketplace.entity.request.PackageBasicInfo;
35 import org.onap.vnfsdk.marketplace.entity.response.PackageMeta;
36 import org.onap.vnfsdk.marketplace.model.parser.EnumPackageFormat;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import com.google.gson.internal.LinkedTreeMap;
41
42
43 public class PackageWrapperUtil {
44   private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class);
45
46   public static long getPacakgeSize(String fileLocation) {
47     File file = new File(fileLocation);
48     return file.length();
49   }
50
51   /**
52    * change package metadata to fix database.
53    * @param meta package metadata
54  * @param details 
55    * @return package data in database 
56    */
57   public static PackageData getPackageData(PackageMeta meta) {
58     PackageData packageData = new PackageData();
59     packageData.setCreateTime(meta.getCreateTime());
60     packageData.setDeletionPending(String.valueOf(meta.isDeletionPending()));
61     packageData.setDownloadUri(meta.getDownloadUri());
62     packageData.setFormat(meta.getFormat());
63     packageData.setModifyTime(meta.getModifyTime());
64     packageData.setName(meta.getName());
65     packageData.setCsarId(meta.getCsarId());
66     packageData.setProvider(meta.getProvider());
67     String fileSize = meta.getSize();
68     packageData.setSize(fileSize);
69     packageData.setType(meta.getType());
70     packageData.setVersion(meta.getVersion());
71         packageData.setDetails(meta.getDetails());
72         packageData.setShortDesc(meta.getShortDesc());
73         packageData.setRemarks(meta.getRemarks());
74     return packageData;
75   }
76
77   /**
78    * judge wether is the end of upload package.
79    * @param contentRange package sise range
80    * @param csarName package name
81    * @return boolean
82    */
83   public static boolean isUploadEnd(String contentRange, String csarName) {
84     String range = contentRange;
85     range = range.replace("bytes", "").trim();
86     range = range.substring(0, range.indexOf("/"));
87     String size =
88         contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim();
89     int fileSize = Integer.parseInt(size);
90     String[] ranges = range.split("-");
91     int startPosition = Integer.parseInt(ranges[0]);
92     if (startPosition == 0) {
93       // delPackageBySync(csarName);
94     }
95     // index start from 0
96     int endPosition = Integer.parseInt(ranges[1]) + 1;
97     if (endPosition >= fileSize) {
98       return true;
99     }
100     return false;
101   }
102
103   /**
104    * get package detail by package id.
105    * @param csarId package id
106    * @return package detail
107    */
108   public static PackageData getPackageInfoById(String csarId) {
109     PackageData result = new PackageData();
110     ArrayList<PackageData> packageDataList = new ArrayList<PackageData>();
111     try {
112       packageDataList = PackageManager.getInstance().queryPackageByCsarId(csarId);
113       if (packageDataList != null && packageDataList.size() > 0) {
114         result = PackageManager.getInstance().queryPackageByCsarId(csarId).get(0);
115       }
116     } catch (MarketplaceResourceException e1) {
117       LOG.error("query package by csarId from db error ! " + e1.getMessage());
118     }
119     return result;
120   }
121
122   /**
123    * get package metadata from basic info.
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     
135     if(null == packageId)
136     {
137         packageId = ToolUtil.generateId();
138     }
139     packageMeta.setCsarId(packageId);
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     ArrayList<PackageData> packageList = new ArrayList<PackageData>();
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);
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     String packageName = ftpUrl.substring(index);
188     return packageName;
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 ArrayList<PackageMeta> packageDataList2PackageMetaList(
197       ArrayList<PackageData> dbResult) {
198     ArrayList<PackageMeta> metas = new ArrayList<PackageMeta>();
199     PackageMeta meta = new PackageMeta();
200     if (dbResult.size() > 0) {
201       for (int i = 0; i < dbResult.size(); i++) {
202         PackageData data = dbResult.get(i);
203         meta = packageData2PackageMeta(data);
204         metas.add(meta);
205       }
206     }
207     return metas;
208   }
209
210   public static PackageMeta packageData2PackageMeta(PackageData packageData) {
211     PackageMeta meta = new PackageMeta();
212     meta.setCsarId(packageData.getCsarId());
213     meta.setCreateTime(packageData.getCreateTime());
214     meta.setDeletionPending(Boolean.getBoolean(packageData.getDeletionPending()));
215     String packageUri =
216         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    * @param uri uri
237    * @return url
238    */
239   public static String getUrl(String uri) {
240     String url = null;
241 //    if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) {
242 //      url = MsbAddrConfig.getMsbAddress() + uri.substring(1);
243 //    }
244 //    url = MsbAddrConfig.getMsbAddress() + uri;
245     if ((getDownloadUriHead().endsWith("/")) && uri.startsWith("/")) {
246       url = getDownloadUriHead() + uri.substring(1);
247     }
248     url = getDownloadUriHead() + uri;
249     String urlresult = url.replace("\\", "/");
250     return urlresult;
251   }
252   
253   public static String getDownloadUriHead() {
254     return MsbAddrConfig.getMsbAddress() + "/files/catalog-http";
255   }
256
257   /**
258    * get local path.
259    * @param uri uri
260    * @return local path
261    */
262   public static String getLocalPath(String uri) {
263     File srcDir = new File(uri);
264     String localPath = srcDir.getAbsolutePath();
265     return localPath.replace("\\", "/");
266   }
267
268   /**
269    * get package basic information.
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       ArrayList<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
280       if (unzipFiles.isEmpty()) {
281         isXmlCsar = true;
282       }
283       for (String unzipFile : unzipFiles) {
284         if (unzipFile.endsWith(CommonConstant.CSAR_META)) {
285           basicInfo = readCsarMeta(unzipFile);
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());
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   private static PackageBasicInfo readCsarMeta(String unzipFile) {
303     PackageBasicInfo basicInfo = new PackageBasicInfo();
304     File file = new File(unzipFile);
305     BufferedReader reader = null;
306     try {
307       reader = new BufferedReader(new FileReader(file));
308       String tempString = null;
309       while ((tempString = reader.readLine()) != null) {
310         if (!tempString.equals("")) {
311           int count1 = tempString.indexOf(":");
312           String meta = tempString.substring(0, count1).trim();
313           if (meta.equalsIgnoreCase(CommonConstant.CSAR_TYPE_META)) {
314             int count = tempString.indexOf(":") + 1;
315             basicInfo.setType(EnumType.valueOf(tempString.substring(count).trim()));
316           }
317           if (meta.equalsIgnoreCase(CommonConstant.CSAR_PROVIDER_META)) {
318             int count = tempString.indexOf(":") + 1;
319             basicInfo.setProvider(tempString.substring(count).trim());
320           }
321           if (meta.equalsIgnoreCase(CommonConstant.CSAR_VERSION_META)) {
322             int count = tempString.indexOf(":") + 1;
323             basicInfo.setVersion(tempString.substring(count).trim());
324           }
325         }
326       }
327       reader.close();
328     } catch (IOException e2) {
329       e2.printStackTrace();
330     } finally {
331       if (reader != null) {
332         try {
333           reader.close();
334         } catch (IOException e1) {
335           LOG.error("close reader failed ! " + e1.getMessage());
336         }
337       }
338     }
339     return basicInfo;
340   }
341   
342   /**
343    * get package format enum.
344    * @param format package format
345    * @return package format enum
346    */
347   public static EnumPackageFormat getPackageFormat(String format) {
348     if (format.equals("xml")) {
349       return EnumPackageFormat.TOSCA_XML;
350     } else if (format.equals("yml") || format.equals("yaml")) {
351       return EnumPackageFormat.TOSCA_YAML;
352     } else {
353       return null;
354     }
355   }
356 }