2 * Copyright 2016 [ZTE] and others.
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.
17 package org.openo.commontosca.catalog.wrapper;
19 import com.google.gson.Gson;
20 import com.google.gson.reflect.TypeToken;
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;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 import java.io.BufferedReader;
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;
59 import javax.ws.rs.NotFoundException;
61 public class PackageWrapperUtil {
62 private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class);
66 * change json to object list.
67 * @param packageJson json
68 * @return package list
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");
79 public static long getPacakgeSize(String fileLocation) {
80 File file = new File(fileLocation);
85 * change package metadata to fix database.
86 * @param meta package metadata
87 * @return package data in database
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());
111 * judge wether is the end of upload package.
112 * @param contentRange package sise range
113 * @param csarName package name
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("/"));
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);
128 // index start from 0
129 int endPosition = Integer.parseInt(ranges[1]) + 1;
130 if (endPosition >= fileSize) {
137 * get package detail by package id.
138 * @param csarId package id
139 * @return package detail
141 public static ArrayList<PackageData> getPackageInfoById(String csarId) {
142 ArrayList<PackageData> result = new ArrayList<PackageData>();
144 result = PackageManager.getInstance().queryPackageByCsarId(csarId);
145 } catch (CatalogResourceException e1) {
146 LOG.error("query package by csarId from db error ! " + e1.getMessage());
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
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);
184 * get downloadUri from package metadata.
185 * @param csarId package id
186 * @return download uri
188 public static String getPackagePath(String csarId) {
189 ArrayList<PackageData> packageList = new ArrayList<PackageData>();
190 String downloadUri = null;
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);
202 * convert instance to hashset.
203 * @param instancelist instance list
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());
217 * get ftp detail information.
218 * @param ftpUrl ftp url
221 public static Ftp getFtpDetail(String ftpUrl) {
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);
239 ftp.setPort(Integer.valueOf(port));
241 ftp.setUserName(userName);
246 * get package name from ftpUrl.
247 * @param ftpUrl ftp url
248 * @return package name
250 public static String getPackageName(String ftpUrl) {
251 int index = ftpUrl.lastIndexOf("/");
252 String packageName = ftpUrl.substring(index);
257 * download package from ftp.
258 * @param ftpUrl ftp url
259 * @param tempDirName temp directory
261 public static void downPackageFromFtp(String ftpUrl, String tempDirName) {
263 ftp = PackageWrapperUtil.getFtpDetail(ftpUrl);
264 String remoteBaseDir = ftp.getPath();
266 FtpUtil.startDown(ftp, tempDirName, remoteBaseDir);
267 } catch (Exception e1) {
268 LOG.error("Down package from ftp failed !");
273 * translate package data from database to package metadata.
274 * @param dbResult data from database
275 * @return package metadata list
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);
292 * get onboarded enum value.
293 * @param value onboard value
296 public static EnumOnboardState getEnumByValue(String value) {
297 if (value == "non-onBoarded") {
298 return EnumOnboardState.nonOnBoarded;
300 return EnumOnboardState.onBoarded;
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()));
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";
327 meta.setProcessState(EnumProcessState.valueOf(processState));
332 * add msb address as prefix to uri.
336 public static String getUrl(String uri) {
338 // if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) {
339 // url = MsbAddrConfig.getMsbAddress() + uri.substring(1);
341 // url = MsbAddrConfig.getMsbAddress() + uri;
342 if ((HttpServerAddrConfig.getHttpServerAddress().endsWith("/")) && uri.startsWith("/")) {
343 url = HttpServerAddrConfig.getHttpServerAddress() + uri.substring(1);
345 url = MsbAddrConfig.getMsbAddress() + uri;
346 String urlresult = url.replace("\\", "/");
355 public static String getLocalPath(String uri) {
356 File srcDir = new File(uri);
357 String localPath = srcDir.getAbsolutePath();
358 return localPath.replace("\\", "/");
362 * get package basic information.
363 * @param fileLocation package location
364 * @return package basic information
366 public static PackageBasicInfo getPacageBasicInfo(String fileLocation) {
367 PackageBasicInfo basicInfo = new PackageBasicInfo();
368 String unzipDir = ToolUtil.getUnzipDir(fileLocation);
369 boolean isXmlCsar = false;
371 String tempfolder = unzipDir;
372 ArrayList<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
373 if (unzipFiles.isEmpty()) {
376 for (String unzipFile : unzipFiles) {
377 if (unzipFile.endsWith(CommonConstant.CSAR_META)) {
378 basicInfo = readCsarMeta(unzipFile);
380 if (ToolUtil.isYamlFile(new File(unzipFile))) {
384 } catch (IOException e1) {
385 LOG.error("judge package type error !");
388 basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
390 basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
395 private static PackageBasicInfo readCsarMeta(String unzipFile) {
396 PackageBasicInfo basicInfo = new PackageBasicInfo();
397 File file = new File(unzipFile);
398 BufferedReader reader = null;
400 reader = new BufferedReader(new FileReader(file));
401 String tempString = null;
402 while ((tempString = reader.readLine()) != null) {
403 if (tempString.startsWith(CommonConstant.CSAR_TYPE_META)) {
404 int count = tempString.indexOf(":") + 1;
405 basicInfo.setType(EnumType.valueOf(tempString.substring(count)));
407 if (tempString.startsWith(CommonConstant.CSAR_PROVIDER_META)) {
408 int count = tempString.indexOf(":") + 1;
409 basicInfo.setProvider(tempString.substring(count));
411 if (tempString.startsWith(CommonConstant.CSAR_VERSION_META)) {
412 int count = tempString.indexOf(":") + 1;
413 basicInfo.setVersion(tempString.substring(count));
417 } catch (IOException e2) {
418 e2.printStackTrace();
420 if (reader != null) {
423 } catch (IOException e1) {
424 LOG.error("close reader failed ! " + e1.getMessage());
432 * get package format enum.
433 * @param format package format
434 * @return package format enum
436 public static EnumPackageFormat getPackageFormat(String format) {
437 if (format.equals("xml")) {
438 return EnumPackageFormat.TOSCA_XML;
439 } else if (format.equals("yml") || format.equals("yaml")) {
440 return EnumPackageFormat.TOSCA_YAML;