3ae5fef19d6963a7d5ccdf5f36ea5d45369d5475
[vfc/nfvo/catalog.git] /
1 /**
2  * Copyright 2016 ZTE Corporation.
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.openo.commontosca.catalog.wrapper;
17
18 import com.google.gson.Gson;
19 import com.google.gson.reflect.TypeToken;
20
21 import org.openo.commontosca.catalog.common.CommonConstant;
22 import org.openo.commontosca.catalog.common.FileUtil;
23 import org.openo.commontosca.catalog.common.HttpServerAddrConfig;
24 import org.openo.commontosca.catalog.common.MsbAddrConfig;
25 import org.openo.commontosca.catalog.common.ToolUtil;
26 import org.openo.commontosca.catalog.db.entity.PackageData;
27 import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
28 import org.openo.commontosca.catalog.db.resource.PackageManager;
29 import org.openo.commontosca.catalog.entity.CsarPackage;
30 import org.openo.commontosca.catalog.entity.EnumOnboardState;
31 import org.openo.commontosca.catalog.entity.EnumOperationalState;
32 import org.openo.commontosca.catalog.entity.EnumProcessState;
33 import org.openo.commontosca.catalog.entity.EnumType;
34 import org.openo.commontosca.catalog.entity.EnumUsageState;
35 import org.openo.commontosca.catalog.entity.request.PackageBasicInfo;
36 import org.openo.commontosca.catalog.entity.response.PackageMeta;
37 import org.openo.commontosca.catalog.ftp.Ftp;
38 import org.openo.commontosca.catalog.ftp.FtpUtil;
39 import org.openo.commontosca.catalog.model.entity.ServiceTemplate;
40 import org.openo.commontosca.catalog.model.externalservice.entity.lifecycle.InstanceEntity;
41 import org.openo.commontosca.catalog.model.externalservice.lifecycle.LifeCycleServiceConsumer;
42 import org.openo.commontosca.catalog.model.parser.EnumPackageFormat;
43
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47
48 import java.io.BufferedReader;
49 import java.io.File;
50 import java.io.FileReader;
51 import java.io.IOException;
52 import java.text.SimpleDateFormat;
53 import java.util.ArrayList;
54 import java.util.Date;
55 import java.util.HashSet;
56 import java.util.List;
57
58 import javax.ws.rs.NotFoundException;
59
60 public class PackageWrapperUtil {
61   private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class);
62
63
64   /**
65    * change json to object list.
66    * @param packageJson json
67    * @return package list
68    */
69   public static List<CsarPackage> formJson2Packages(String packageJson) {
70     List<CsarPackage> packageList =
71         new Gson().fromJson(packageJson, new TypeToken<List<CsarPackage>>() {}.getType());
72     if (null == packageList || packageList.size() == 0) {
73       throw new NotFoundException("Package do not exist");
74     }
75     return packageList;
76   }
77
78   public static long getPacakgeSize(String fileLocation) {
79     File file = new File(fileLocation);
80     return file.length();
81   }
82
83   /**
84    * change package metadata to fix database.
85    * @param meta package metadata
86    * @return package data in database 
87    */
88   public static PackageData getPackageData(PackageMeta meta) {
89     PackageData packageData = new PackageData();
90     packageData.setCreateTime(meta.getCreateTime());
91     packageData.setDeletionPending(String.valueOf(meta.isDeletionPending()));
92     packageData.setDownloadUri(meta.getDownloadUri());
93     packageData.setFormat(meta.getFormat());
94     packageData.setModifyTime(meta.getModifyTime());
95     packageData.setName(meta.getName());
96     packageData.setCsarId(meta.getCsarId());
97     packageData.setOperationalState(meta.getOperationalState().toString());
98     packageData.setProvider(meta.getProvider());
99     String fileSize = meta.getSize();
100     packageData.setSize(fileSize);
101     packageData.setType(meta.getType());
102     packageData.setUsageState(meta.getUsageState().toString());
103     packageData.setVersion(meta.getVersion());
104     packageData.setOnBoardState(meta.getOnBoardState());
105     packageData.setProcessState(meta.getProcessState().toString());
106     return packageData;
107   }
108
109   /**
110    * judge wether is the end of upload package.
111    * @param contentRange package sise range
112    * @param csarName package name
113    * @return boolean
114    */
115   public static boolean isUploadEnd(String contentRange, String csarName) {
116     String range = contentRange;
117     range = range.replace("bytes", "").trim();
118     range = range.substring(0, range.indexOf("/"));
119     String size =
120         contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim();
121     int fileSize = Integer.parseInt(size);
122     String[] ranges = range.split("-");
123     int startPosition = Integer.parseInt(ranges[0]);
124     if (startPosition == 0) {
125       // delPackageBySync(csarName);
126     }
127     // index start from 0
128     int endPosition = Integer.parseInt(ranges[1]) + 1;
129     if (endPosition >= fileSize) {
130       return true;
131     }
132     return false;
133   }
134
135   /**
136    * get package detail by package id.
137    * @param csarId package id
138    * @return package detail
139    */
140   public static ArrayList<PackageData> getPackageInfoById(String csarId) {
141     ArrayList<PackageData> result = new ArrayList<PackageData>();
142     try {
143       result = PackageManager.getInstance().queryPackageByCsarId(csarId);
144     } catch (CatalogResourceException e1) {
145       LOG.error("query package by csarId from db error ! " + e1.getMessage());
146     }
147     return result;
148   }
149
150   /**
151    * get package metadata from basic info.
152    * @param fileName package name
153    * @param fileLocation the location of package
154    * @param basic basic infomation of package. include version, type and provider
155    * @return package metadata
156    */
157   public static PackageMeta getPackageMeta(String fileName, String fileLocation,
158       PackageBasicInfo basic) {
159     PackageMeta packageMeta = new PackageMeta();
160     long size = getPacakgeSize(fileLocation);
161     packageMeta.setFormat(basic.getFormat());
162     String packageId = ToolUtil.generateId();
163     packageMeta.setName(fileName.replace(CommonConstant.CSAR_SUFFIX, ""));
164     packageMeta.setCsarId(packageId);
165     packageMeta.setType(basic.getType().toString());
166     packageMeta.setVersion(basic.getVersion());
167     packageMeta.setProvider(basic.getProvider());
168     packageMeta.setDeletionPending(false);
169     String sizeStr = ToolUtil.getFormatFileSize(size);
170     packageMeta.setSize(sizeStr);
171     SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
172     String currentTime = sdf1.format(new Date());
173     packageMeta.setCreateTime(currentTime);
174     packageMeta.setModifyTime(currentTime);
175     packageMeta.setOperationalState(EnumOperationalState.Disabled);
176     packageMeta.setUsageState(EnumUsageState.NotInUse);
177     packageMeta.setOnBoardState(EnumOnboardState.nonOnBoarded.getValue());
178     packageMeta.setProcessState(EnumProcessState.normal);
179     return packageMeta;
180   }
181
182   /**
183    * get downloadUri from package metadata.
184    * @param csarId package id
185    * @return download uri
186    */
187   public static String getPackagePath(String csarId) {
188     ArrayList<PackageData> packageList = new ArrayList<PackageData>();
189     String downloadUri = null;
190     try {
191       packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
192       downloadUri = packageList.get(0).getDownloadUri();
193     } catch (CatalogResourceException e1) {
194       LOG.error("Query CSAR package by ID failed ! csarId = " + csarId);
195     }
196     return downloadUri;
197   }
198
199
200   /**
201    * convert instance to hashset.
202    * @param instancelist instance list
203    * @return HashSet
204    */
205   public static HashSet<String> instanceConvertToHashSet(ArrayList<InstanceEntity> instancelist) {
206     HashSet<String> result = new HashSet<String>();
207     if (instancelist != null) {
208       for (InstanceEntity instance : instancelist) {
209         result.add(instance.getServiceTemplateId());
210       }
211     }
212     return result;
213   }
214
215   /**
216    * get ftp detail information.
217    * @param ftpUrl ftp url
218    * @return ftp detail
219    */
220   public static Ftp getFtpDetail(String ftpUrl) {
221     Ftp ftp = new Ftp();
222     int index1 = ftpUrl.indexOf("ftp://");
223     int index2 = ftpUrl.indexOf("@");
224     String userPassSubString = ftpUrl.substring(index1, index2);
225     int index3 = userPassSubString.indexOf(":");
226     String userName = userPassSubString.substring(0, index3);
227     String pass = userPassSubString.substring(index3 + 1);
228     String subString1 = ftpUrl.substring(index2 + 1);
229     int index4 = subString1.indexOf("/");
230     String ipPortSubString = subString1.substring(0, index4);
231     int index5 = ipPortSubString.indexOf(":");
232     String ip = ipPortSubString.substring(0, index5);
233     String port = ipPortSubString.substring(index5 + 1);
234     int index6 = ftpUrl.lastIndexOf("/");
235     String path = ftpUrl.substring(0, index6);
236     ftp.setIpAddr(ip);
237     ftp.setPath(path);
238     ftp.setPort(Integer.valueOf(port));
239     ftp.setPwd(pass);
240     ftp.setUserName(userName);
241     return ftp;
242   }
243
244   /**
245    * get package name from ftpUrl.
246    * @param ftpUrl ftp url
247    * @return package name
248    */
249   public static String getPackageName(String ftpUrl) {
250     int index = ftpUrl.lastIndexOf("/");
251     String packageName = ftpUrl.substring(index);
252     return packageName;
253   }
254
255   /**
256    * download package from ftp.
257    * @param ftpUrl ftp url
258    * @param tempDirName temp directory
259    */
260   public static void downPackageFromFtp(String ftpUrl, String tempDirName) {
261     Ftp ftp = new Ftp();
262     ftp = PackageWrapperUtil.getFtpDetail(ftpUrl);
263     String remoteBaseDir = ftp.getPath();
264     try {
265       FtpUtil.startDown(ftp, tempDirName, remoteBaseDir);
266     } catch (Exception e1) {
267       LOG.error("Down package from ftp failed !");
268     }
269   }
270
271   /**
272    * translate package data from database to package metadata.
273    * @param dbResult data from database
274    * @return package metadata list
275    */
276   public static ArrayList<PackageMeta> packageDataList2PackageMetaList(
277       ArrayList<PackageData> dbResult) {
278     ArrayList<PackageMeta> metas = new ArrayList<PackageMeta>();
279     PackageMeta meta = new PackageMeta();
280     if (dbResult.size() > 0) {
281       for (int i = 0; i < dbResult.size(); i++) {
282         PackageData data = dbResult.get(i);
283         meta = packageData2PackageMeta(data);
284         metas.add(meta);
285       }
286     }
287     return metas;
288   }
289
290   /**
291    * get onboarded enum value.
292    * @param value onboard value
293    * @return enum
294    */
295   public static EnumOnboardState getEnumByValue(String value) {
296     if (value == "non-onBoarded") {
297       return EnumOnboardState.nonOnBoarded;
298     } else {
299       return EnumOnboardState.onBoarded;
300     }
301   }
302
303   private static PackageMeta packageData2PackageMeta(PackageData packageData) {
304     PackageMeta meta = new PackageMeta();
305     meta.setCsarId(packageData.getCsarId());
306     meta.setCreateTime(packageData.getCreateTime());
307     meta.setDeletionPending(Boolean.getBoolean(packageData.getDeletionPending()));
308     String packageUri =
309         packageData.getDownloadUri() + packageData.getName() + CommonConstant.CSAR_SUFFIX;
310     String packageUrl = getUrl(packageUri);
311     meta.setDownloadUri(packageUrl);
312     meta.setFormat(packageData.getFormat());
313     meta.setModifyTime(packageData.getModifyTime());
314     meta.setName(packageData.getName());
315     meta.setOperationalState(EnumOperationalState.valueOf(packageData.getOperationalState()));
316     meta.setProvider(packageData.getProvider());
317     meta.setSize(packageData.getSize());
318     meta.setType(packageData.getType());
319     meta.setUsageState(EnumUsageState.valueOf(packageData.getUsageState()));
320     meta.setVersion(packageData.getVersion());
321     meta.setOnBoardState(packageData.getOnBoardState());
322     String processState = packageData.getProcessState();
323     if (processState.equals("deletefail")) {
324       processState = "deleteFailed";
325     }
326     meta.setProcessState(EnumProcessState.valueOf(processState));
327     return meta;
328   }
329
330   /**
331    * add msb address as prefix to uri.
332    * @param uri uri
333    * @return url
334    */
335   public static String getUrl(String uri) {
336     String url = null;
337 //    if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) {
338 //      url = MsbAddrConfig.getMsbAddress() + uri.substring(1);
339 //    }
340 //    url = MsbAddrConfig.getMsbAddress() + uri;
341     if ((getDownloadUriHead().endsWith("/")) && uri.startsWith("/")) {
342       url = getDownloadUriHead() + uri.substring(1);
343     }
344     url = getDownloadUriHead() + uri;
345     String urlresult = url.replace("\\", "/");
346     return urlresult;
347   }
348   
349   public static String getDownloadUriHead() {
350     return MsbAddrConfig.getMsbAddress() + "/files/catalog-http";
351   }
352
353   /**
354    * get local path.
355    * @param uri uri
356    * @return local path
357    */
358   public static String getLocalPath(String uri) {
359     File srcDir = new File(uri);
360     String localPath = srcDir.getAbsolutePath();
361     return localPath.replace("\\", "/");
362   }
363
364   /**
365    * get package basic information.
366    * @param fileLocation package location
367    * @return package basic information
368    */
369   public static PackageBasicInfo getPacageBasicInfo(String fileLocation) {
370     PackageBasicInfo basicInfo = new PackageBasicInfo();
371     String unzipDir = ToolUtil.getUnzipDir(fileLocation);
372     boolean isXmlCsar = false;
373     try {
374       String tempfolder = unzipDir;
375       ArrayList<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
376       if (unzipFiles.isEmpty()) {
377         isXmlCsar = true;
378       }
379       for (String unzipFile : unzipFiles) {
380         if (unzipFile.endsWith(CommonConstant.CSAR_META)) {
381           basicInfo = readCsarMeta(unzipFile);
382         }
383         if (ToolUtil.isYamlFile(new File(unzipFile))) {
384           isXmlCsar = false;
385         }
386       }
387     } catch (IOException e1) {
388       LOG.error("judge package type error !");
389     }
390     if (isXmlCsar) {
391       basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
392     } else {
393       basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
394     }
395     return basicInfo;
396   }
397
398   private static PackageBasicInfo readCsarMeta(String unzipFile) {
399     PackageBasicInfo basicInfo = new PackageBasicInfo();
400     File file = new File(unzipFile);
401     BufferedReader reader = null;
402     try {
403       reader = new BufferedReader(new FileReader(file));
404       String tempString = null;
405       while ((tempString = reader.readLine()) != null) {
406         if (!tempString.equals("")) {
407           int count1 = tempString.indexOf(":");
408           String meta = tempString.substring(0, count1).trim();
409           if (meta.equalsIgnoreCase(CommonConstant.CSAR_TYPE_META)) {
410             int count = tempString.indexOf(":") + 1;
411             basicInfo.setType(EnumType.valueOf(tempString.substring(count).trim()));
412           }
413           if (meta.equalsIgnoreCase(CommonConstant.CSAR_PROVIDER_META)) {
414             int count = tempString.indexOf(":") + 1;
415             basicInfo.setProvider(tempString.substring(count).trim());
416           }
417           if (meta.equalsIgnoreCase(CommonConstant.CSAR_VERSION_META)) {
418             int count = tempString.indexOf(":") + 1;
419             basicInfo.setVersion(tempString.substring(count).trim());
420           }
421         }
422       }
423       reader.close();
424     } catch (IOException e2) {
425       e2.printStackTrace();
426     } finally {
427       if (reader != null) {
428         try {
429           reader.close();
430         } catch (IOException e1) {
431           LOG.error("close reader failed ! " + e1.getMessage());
432         }
433       }
434     }
435     return basicInfo;
436   }
437   
438   /**
439    * get package format enum.
440    * @param format package format
441    * @return package format enum
442    */
443   public static EnumPackageFormat getPackageFormat(String format) {
444     if (format.equals("xml")) {
445       return EnumPackageFormat.TOSCA_XML;
446     } else if (format.equals("yml") || format.equals("yaml")) {
447       return EnumPackageFormat.TOSCA_YAML;
448     } else {
449       return null;
450     }
451   }
452 }