2 * Copyright 2016 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 ArrayList<PackageData> getPackageInfoById(String csarId) {
141 ArrayList<PackageData> result = new ArrayList<PackageData>();
143 result = PackageManager.getInstance().queryPackageByCsarId(csarId);
144 } catch (CatalogResourceException e1) {
145 LOG.error("query package by csarId from db error ! " + e1.getMessage());
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
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);
183 * get downloadUri from package metadata.
184 * @param csarId package id
185 * @return download uri
187 public static String getPackagePath(String csarId) {
188 ArrayList<PackageData> packageList = new ArrayList<PackageData>();
189 String downloadUri = null;
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);
201 * convert instance to hashset.
202 * @param instancelist instance list
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());
216 * get ftp detail information.
217 * @param ftpUrl ftp url
220 public static Ftp getFtpDetail(String ftpUrl) {
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);
238 ftp.setPort(Integer.valueOf(port));
240 ftp.setUserName(userName);
245 * get package name from ftpUrl.
246 * @param ftpUrl ftp url
247 * @return package name
249 public static String getPackageName(String ftpUrl) {
250 int index = ftpUrl.lastIndexOf("/");
251 String packageName = ftpUrl.substring(index);
256 * download package from ftp.
257 * @param ftpUrl ftp url
258 * @param tempDirName temp directory
260 public static void downPackageFromFtp(String ftpUrl, String tempDirName) {
262 ftp = PackageWrapperUtil.getFtpDetail(ftpUrl);
263 String remoteBaseDir = ftp.getPath();
265 FtpUtil.startDown(ftp, tempDirName, remoteBaseDir);
266 } catch (Exception e1) {
267 LOG.error("Down package from ftp failed !");
272 * translate package data from database to package metadata.
273 * @param dbResult data from database
274 * @return package metadata list
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);
291 * get onboarded enum value.
292 * @param value onboard value
295 public static EnumOnboardState getEnumByValue(String value) {
296 if (value == "non-onBoarded") {
297 return EnumOnboardState.nonOnBoarded;
299 return EnumOnboardState.onBoarded;
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()));
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";
326 meta.setProcessState(EnumProcessState.valueOf(processState));
331 * add msb address as prefix to uri.
335 public static String getUrl(String uri) {
337 // if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) {
338 // url = MsbAddrConfig.getMsbAddress() + uri.substring(1);
340 // url = MsbAddrConfig.getMsbAddress() + uri;
341 if ((getDownloadUriHead().endsWith("/")) && uri.startsWith("/")) {
342 url = getDownloadUriHead() + uri.substring(1);
344 url = getDownloadUriHead() + uri;
345 String urlresult = url.replace("\\", "/");
349 public static String getDownloadUriHead() {
350 return MsbAddrConfig.getMsbAddress() + "/files/catalog-http";
358 public static String getLocalPath(String uri) {
359 File srcDir = new File(uri);
360 String localPath = srcDir.getAbsolutePath();
361 return localPath.replace("\\", "/");
365 * get package basic information.
366 * @param fileLocation package location
367 * @return package basic information
369 public static PackageBasicInfo getPacageBasicInfo(String fileLocation) {
370 PackageBasicInfo basicInfo = new PackageBasicInfo();
371 String unzipDir = ToolUtil.getUnzipDir(fileLocation);
372 boolean isXmlCsar = false;
374 String tempfolder = unzipDir;
375 ArrayList<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
376 if (unzipFiles.isEmpty()) {
379 for (String unzipFile : unzipFiles) {
380 if (unzipFile.endsWith(CommonConstant.CSAR_META)) {
381 basicInfo = readCsarMeta(unzipFile);
383 if (ToolUtil.isYamlFile(new File(unzipFile))) {
387 } catch (IOException e1) {
388 LOG.error("judge package type error !");
391 basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
393 basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
398 private static PackageBasicInfo readCsarMeta(String unzipFile) {
399 PackageBasicInfo basicInfo = new PackageBasicInfo();
400 File file = new File(unzipFile);
401 BufferedReader reader = null;
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()));
413 if (meta.equalsIgnoreCase(CommonConstant.CSAR_PROVIDER_META)) {
414 int count = tempString.indexOf(":") + 1;
415 basicInfo.setProvider(tempString.substring(count).trim());
417 if (meta.equalsIgnoreCase(CommonConstant.CSAR_VERSION_META)) {
418 int count = tempString.indexOf(":") + 1;
419 basicInfo.setVersion(tempString.substring(count).trim());
424 } catch (IOException e2) {
425 e2.printStackTrace();
427 if (reader != null) {
430 } catch (IOException e1) {
431 LOG.error("close reader failed ! " + e1.getMessage());
439 * get package format enum.
440 * @param format package format
441 * @return package format enum
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;