2 * Copyright 2016-2017 ZTE Corporation.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.openo.commontosca.catalog.wrapper;
18 import com.google.gson.Gson;
19 import com.google.gson.reflect.TypeToken;
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;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 import java.io.BufferedReader;
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;
58 import javax.ws.rs.NotFoundException;
60 public class PackageWrapperUtil {
61 private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class);
65 * change json to object list.
66 * @param packageJson json
67 * @return package list
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");
78 public static long getPacakgeSize(String fileLocation) {
79 File file = new File(fileLocation);
84 * change package metadata to fix database.
85 * @param meta package metadata
86 * @return package data in database
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());
110 * judge wether is the end of upload package.
111 * @param contentRange package sise range
112 * @param csarName package name
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("/"));
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);
127 // index start from 0
128 int endPosition = Integer.parseInt(ranges[1]) + 1;
129 if (endPosition >= fileSize) {
136 * get package detail by package id.
137 * @param csarId package id
138 * @return package detail
140 public static PackageData getPackageInfoById(String csarId) {
141 PackageData result = new PackageData();
142 ArrayList<PackageData> packageDataList = new ArrayList<PackageData>();
144 packageDataList = PackageManager.getInstance().queryPackageByCsarId(csarId);
145 if (packageDataList != null && packageDataList.size() > 0) {
146 result = PackageManager.getInstance().queryPackageByCsarId(csarId).get(0);
148 } catch (CatalogResourceException e1) {
149 LOG.error("query package by csarId from db error ! " + e1.getMessage());
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
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);
187 * get downloadUri from package metadata.
188 * @param csarId package id
189 * @return download uri
191 public static String getPackagePath(String csarId) {
192 ArrayList<PackageData> packageList = new ArrayList<PackageData>();
193 String downloadUri = null;
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);
205 * convert instance to hashset.
206 * @param instancelist instance list
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());
220 * get ftp detail information.
221 * @param ftpUrl ftp url
224 public static Ftp getFtpDetail(String ftpUrl) {
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);
242 ftp.setPort(Integer.valueOf(port));
244 ftp.setUserName(userName);
249 * get package name from ftpUrl.
250 * @param ftpUrl ftp url
251 * @return package name
253 public static String getPackageName(String ftpUrl) {
254 int index = ftpUrl.lastIndexOf("/");
255 String packageName = ftpUrl.substring(index);
260 * download package from ftp.
261 * @param ftpUrl ftp url
262 * @param tempDirName temp directory
264 public static void downPackageFromFtp(String ftpUrl, String tempDirName) {
266 ftp = PackageWrapperUtil.getFtpDetail(ftpUrl);
267 String remoteBaseDir = ftp.getPath();
269 FtpUtil.startDown(ftp, tempDirName, remoteBaseDir);
270 } catch (Exception e1) {
271 LOG.error("Down package from ftp failed !");
276 * translate package data from database to package metadata.
277 * @param dbResult data from database
278 * @return package metadata list
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);
295 * get onboarded enum value.
296 * @param value onboard value
299 public static EnumOnboardState getEnumByValue(String value) {
300 if (value == "non-onBoarded") {
301 return EnumOnboardState.nonOnBoarded;
303 return EnumOnboardState.onBoarded;
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.valueOf(packageData.getDeletionPending()));
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";
330 meta.setProcessState(EnumProcessState.valueOf(processState));
335 * add msb address as prefix to uri.
339 public static String getUrl(String uri) {
341 // if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) {
342 // url = MsbAddrConfig.getMsbAddress() + uri.substring(1);
344 // url = MsbAddrConfig.getMsbAddress() + uri;
345 if ((getDownloadUriHead().endsWith("/")) && uri.startsWith("/")) {
346 url = getDownloadUriHead() + uri.substring(1);
348 url = getDownloadUriHead() + uri;
349 String urlresult = url.replace("\\", "/");
353 public static String getDownloadUriHead() {
354 return MsbAddrConfig.getMsbAddress() + "/files/catalog-http";
362 public static String getLocalPath(String uri) {
363 File srcDir = new File(uri);
364 String localPath = srcDir.getAbsolutePath();
365 return localPath.replace("\\", "/");
369 * get package basic information.
370 * @param fileLocation package location
371 * @return package basic information
373 public static PackageBasicInfo getPacageBasicInfo(String fileLocation) {
374 PackageBasicInfo basicInfo = new PackageBasicInfo();
375 String unzipDir = ToolUtil.getUnzipDir(fileLocation);
376 boolean isXmlCsar = false;
378 String tempfolder = unzipDir;
379 ArrayList<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
380 if (unzipFiles.isEmpty()) {
383 for (String unzipFile : unzipFiles) {
384 if (unzipFile.endsWith(CommonConstant.CSAR_META)) {
385 basicInfo = readCsarMeta(unzipFile);
387 if (ToolUtil.isYamlFile(new File(unzipFile))) {
391 } catch (IOException e1) {
392 LOG.error("judge package type error ! " + e1.getMessage());
395 basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
397 basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
402 private static PackageBasicInfo readCsarMeta(String unzipFile) {
403 PackageBasicInfo basicInfo = new PackageBasicInfo();
404 File file = new File(unzipFile);
405 BufferedReader reader = null;
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()));
417 if (meta.equalsIgnoreCase(CommonConstant.CSAR_PROVIDER_META)) {
418 int count = tempString.indexOf(":") + 1;
419 basicInfo.setProvider(tempString.substring(count).trim());
421 if (meta.equalsIgnoreCase(CommonConstant.CSAR_VERSION_META)) {
422 int count = tempString.indexOf(":") + 1;
423 basicInfo.setVersion(tempString.substring(count).trim());
428 } catch (IOException e2) {
429 e2.printStackTrace();
431 if (reader != null) {
434 } catch (IOException e1) {
435 LOG.error("close reader failed ! " + e1.getMessage());
443 * get package format enum.
444 * @param format package format
445 * @return package format enum
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;