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