3e494e20028831545f3684a79d5c8e1e7f530e4c
[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 PackageData getPackageInfoById(String csarId) {
141     PackageData result = new PackageData();
142     ArrayList<PackageData> packageDataList = new ArrayList<PackageData>();
143     try {
144       packageDataList = PackageManager.getInstance().queryPackageByCsarId(csarId);
145       if (packageDataList != null && packageDataList.size() > 0) {
146         result = PackageManager.getInstance().queryPackageByCsarId(csarId).get(0);
147       }
148     } catch (CatalogResourceException e1) {
149       LOG.error("query package by csarId from db error ! " + e1.getMessage());
150     }
151     return result;
152   }
153
154   /**
155    * get package metadata from basic info.
156    * @param fileName package name
157    * @param fileLocation the location of package
158    * @param basic basic infomation of package. include version, type and provider
159    * @return package metadata
160    */
161   public static PackageMeta getPackageMeta(String fileName, String fileLocation,
162       PackageBasicInfo basic) {
163     PackageMeta packageMeta = new PackageMeta();
164     long size = getPacakgeSize(fileLocation);
165     packageMeta.setFormat(basic.getFormat());
166     String packageId = ToolUtil.generateId();
167     packageMeta.setName(fileName.replace(CommonConstant.CSAR_SUFFIX, ""));
168     packageMeta.setCsarId(packageId);
169     packageMeta.setType(basic.getType().toString());
170     packageMeta.setVersion(basic.getVersion());
171     packageMeta.setProvider(basic.getProvider());
172     packageMeta.setDeletionPending(false);
173     String sizeStr = ToolUtil.getFormatFileSize(size);
174     packageMeta.setSize(sizeStr);
175     SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
176     String currentTime = sdf1.format(new Date());
177     packageMeta.setCreateTime(currentTime);
178     packageMeta.setModifyTime(currentTime);
179     packageMeta.setOperationalState(EnumOperationalState.Disabled);
180     packageMeta.setUsageState(EnumUsageState.NotInUse);
181     packageMeta.setOnBoardState(EnumOnboardState.nonOnBoarded.getValue());
182     packageMeta.setProcessState(EnumProcessState.normal);
183     return packageMeta;
184   }
185
186   /**
187    * get downloadUri from package metadata.
188    * @param csarId package id
189    * @return download uri
190    */
191   public static String getPackagePath(String csarId) {
192     ArrayList<PackageData> packageList = new ArrayList<PackageData>();
193     String downloadUri = null;
194     try {
195       packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
196       downloadUri = packageList.get(0).getDownloadUri();
197     } catch (CatalogResourceException e1) {
198       LOG.error("Query CSAR package by ID failed ! csarId = " + csarId);
199     }
200     return downloadUri;
201   }
202
203
204   /**
205    * convert instance to hashset.
206    * @param instancelist instance list
207    * @return HashSet
208    */
209   public static HashSet<String> instanceConvertToHashSet(ArrayList<InstanceEntity> instancelist) {
210     HashSet<String> result = new HashSet<String>();
211     if (instancelist != null) {
212       for (InstanceEntity instance : instancelist) {
213         result.add(instance.getServiceTemplateId());
214       }
215     }
216     return result;
217   }
218
219   /**
220    * get ftp detail information.
221    * @param ftpUrl ftp url
222    * @return ftp detail
223    */
224   public static Ftp getFtpDetail(String ftpUrl) {
225     Ftp ftp = new Ftp();
226     int index1 = ftpUrl.indexOf("ftp://");
227     int index2 = ftpUrl.indexOf("@");
228     String userPassSubString = ftpUrl.substring(index1, index2);
229     int index3 = userPassSubString.indexOf(":");
230     String userName = userPassSubString.substring(0, index3);
231     String pass = userPassSubString.substring(index3 + 1);
232     String subString1 = ftpUrl.substring(index2 + 1);
233     int index4 = subString1.indexOf("/");
234     String ipPortSubString = subString1.substring(0, index4);
235     int index5 = ipPortSubString.indexOf(":");
236     String ip = ipPortSubString.substring(0, index5);
237     String port = ipPortSubString.substring(index5 + 1);
238     int index6 = ftpUrl.lastIndexOf("/");
239     String path = ftpUrl.substring(0, index6);
240     ftp.setIpAddr(ip);
241     ftp.setPath(path);
242     ftp.setPort(Integer.valueOf(port));
243     ftp.setPwd(pass);
244     ftp.setUserName(userName);
245     return ftp;
246   }
247
248   /**
249    * get package name from ftpUrl.
250    * @param ftpUrl ftp url
251    * @return package name
252    */
253   public static String getPackageName(String ftpUrl) {
254     int index = ftpUrl.lastIndexOf("/");
255     String packageName = ftpUrl.substring(index);
256     return packageName;
257   }
258
259   /**
260    * download package from ftp.
261    * @param ftpUrl ftp url
262    * @param tempDirName temp directory
263    */
264   public static void downPackageFromFtp(String ftpUrl, String tempDirName) {
265     Ftp ftp = new Ftp();
266     ftp = PackageWrapperUtil.getFtpDetail(ftpUrl);
267     String remoteBaseDir = ftp.getPath();
268     try {
269       FtpUtil.startDown(ftp, tempDirName, remoteBaseDir);
270     } catch (Exception e1) {
271       LOG.error("Down package from ftp failed !");
272     }
273   }
274
275   /**
276    * translate package data from database to package metadata.
277    * @param dbResult data from database
278    * @return package metadata list
279    */
280   public static ArrayList<PackageMeta> packageDataList2PackageMetaList(
281       ArrayList<PackageData> dbResult) {
282     ArrayList<PackageMeta> metas = new ArrayList<PackageMeta>();
283     PackageMeta meta = new PackageMeta();
284     if (dbResult.size() > 0) {
285       for (int i = 0; i < dbResult.size(); i++) {
286         PackageData data = dbResult.get(i);
287         meta = packageData2PackageMeta(data);
288         metas.add(meta);
289       }
290     }
291     return metas;
292   }
293
294   /**
295    * get onboarded enum value.
296    * @param value onboard value
297    * @return enum
298    */
299   public static EnumOnboardState getEnumByValue(String value) {
300     if (value == "non-onBoarded") {
301       return EnumOnboardState.nonOnBoarded;
302     } else {
303       return EnumOnboardState.onBoarded;
304     }
305   }
306
307   public static PackageMeta packageData2PackageMeta(PackageData packageData) {
308     PackageMeta meta = new PackageMeta();
309     meta.setCsarId(packageData.getCsarId());
310     meta.setCreateTime(packageData.getCreateTime());
311     meta.setDeletionPending(Boolean.getBoolean(packageData.getDeletionPending()));
312     String packageUri =
313         packageData.getDownloadUri() + packageData.getName() + CommonConstant.CSAR_SUFFIX;
314     String packageUrl = getUrl(packageUri);
315     meta.setDownloadUri(packageUrl);
316     meta.setFormat(packageData.getFormat());
317     meta.setModifyTime(packageData.getModifyTime());
318     meta.setName(packageData.getName());
319     meta.setOperationalState(EnumOperationalState.valueOf(packageData.getOperationalState()));
320     meta.setProvider(packageData.getProvider());
321     meta.setSize(packageData.getSize());
322     meta.setType(packageData.getType());
323     meta.setUsageState(EnumUsageState.valueOf(packageData.getUsageState()));
324     meta.setVersion(packageData.getVersion());
325     meta.setOnBoardState(packageData.getOnBoardState());
326     String processState = packageData.getProcessState();
327     if (processState.equals("deletefail")) {
328       processState = "deleteFailed";
329     }
330     meta.setProcessState(EnumProcessState.valueOf(processState));
331     return meta;
332   }
333
334   /**
335    * add msb address as prefix to uri.
336    * @param uri uri
337    * @return url
338    */
339   public static String getUrl(String uri) {
340     String url = null;
341 //    if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) {
342 //      url = MsbAddrConfig.getMsbAddress() + uri.substring(1);
343 //    }
344 //    url = MsbAddrConfig.getMsbAddress() + uri;
345     if ((getDownloadUriHead().endsWith("/")) && uri.startsWith("/")) {
346       url = getDownloadUriHead() + uri.substring(1);
347     }
348     url = getDownloadUriHead() + uri;
349     String urlresult = url.replace("\\", "/");
350     return urlresult;
351   }
352   
353   public static String getDownloadUriHead() {
354     return MsbAddrConfig.getMsbAddress() + "/files/catalog-http";
355   }
356
357   /**
358    * get local path.
359    * @param uri uri
360    * @return local path
361    */
362   public static String getLocalPath(String uri) {
363     File srcDir = new File(uri);
364     String localPath = srcDir.getAbsolutePath();
365     return localPath.replace("\\", "/");
366   }
367
368   /**
369    * get package basic information.
370    * @param fileLocation package location
371    * @return package basic information
372    */
373   public static PackageBasicInfo getPacageBasicInfo(String fileLocation) {
374     PackageBasicInfo basicInfo = new PackageBasicInfo();
375     String unzipDir = ToolUtil.getUnzipDir(fileLocation);
376     boolean isXmlCsar = false;
377     try {
378       String tempfolder = unzipDir;
379       ArrayList<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
380       if (unzipFiles.isEmpty()) {
381         isXmlCsar = true;
382       }
383       for (String unzipFile : unzipFiles) {
384         if (unzipFile.endsWith(CommonConstant.CSAR_META)) {
385           basicInfo = readCsarMeta(unzipFile);
386         }
387         if (ToolUtil.isYamlFile(new File(unzipFile))) {
388           isXmlCsar = false;
389         }
390       }
391     } catch (IOException e1) {
392       LOG.error("judge package type error ! " + e1.getMessage());
393     }
394     if (isXmlCsar) {
395       basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
396     } else {
397       basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
398     }
399     return basicInfo;
400   }
401
402   private static PackageBasicInfo readCsarMeta(String unzipFile) {
403     PackageBasicInfo basicInfo = new PackageBasicInfo();
404     File file = new File(unzipFile);
405     BufferedReader reader = null;
406     try {
407       reader = new BufferedReader(new FileReader(file));
408       String tempString = null;
409       while ((tempString = reader.readLine()) != null) {
410         if (!tempString.equals("")) {
411           int count1 = tempString.indexOf(":");
412           String meta = tempString.substring(0, count1).trim();
413           if (meta.equalsIgnoreCase(CommonConstant.CSAR_TYPE_META)) {
414             int count = tempString.indexOf(":") + 1;
415             basicInfo.setType(EnumType.valueOf(tempString.substring(count).trim()));
416           }
417           if (meta.equalsIgnoreCase(CommonConstant.CSAR_PROVIDER_META)) {
418             int count = tempString.indexOf(":") + 1;
419             basicInfo.setProvider(tempString.substring(count).trim());
420           }
421           if (meta.equalsIgnoreCase(CommonConstant.CSAR_VERSION_META)) {
422             int count = tempString.indexOf(":") + 1;
423             basicInfo.setVersion(tempString.substring(count).trim());
424           }
425         }
426       }
427       reader.close();
428     } catch (IOException e2) {
429       e2.printStackTrace();
430     } finally {
431       if (reader != null) {
432         try {
433           reader.close();
434         } catch (IOException e1) {
435           LOG.error("close reader failed ! " + e1.getMessage());
436         }
437       }
438     }
439     return basicInfo;
440   }
441   
442   /**
443    * get package format enum.
444    * @param format package format
445    * @return package format enum
446    */
447   public static EnumPackageFormat getPackageFormat(String format) {
448     if (format.equals("xml")) {
449       return EnumPackageFormat.TOSCA_XML;
450     } else if (format.equals("yml") || format.equals("yaml")) {
451       return EnumPackageFormat.TOSCA_YAML;
452     } else {
453       return null;
454     }
455   }
456 }