aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper
diff options
context:
space:
mode:
Diffstat (limited to 'catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper')
-rw-r--r--catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java1033
-rw-r--r--catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java847
2 files changed, 951 insertions, 929 deletions
diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java
index 36b229b8..a7d9fcca 100644
--- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java
+++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapper.java
@@ -1,516 +1,517 @@
-/**
- * Copyright 2016 [ZTE] and others.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.openo.commontosca.catalog.wrapper;
-
-import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
-import org.openo.commontosca.catalog.common.CommonConstant;
-import org.openo.commontosca.catalog.common.HttpServerPathConfig;
-import org.openo.commontosca.catalog.common.RestUtil;
-import org.openo.commontosca.catalog.common.ToolUtil;
-import org.openo.commontosca.catalog.common.ZipCompressor;
-import org.openo.commontosca.catalog.db.entity.PackageData;
-import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
-import org.openo.commontosca.catalog.db.resource.PackageManager;
-import org.openo.commontosca.catalog.db.resource.TemplateManager;
-import org.openo.commontosca.catalog.entity.EnumType;
-import org.openo.commontosca.catalog.entity.request.PackageBasicInfo;
-import org.openo.commontosca.catalog.entity.request.UploadPackageFromFtpRequest;
-import org.openo.commontosca.catalog.entity.response.CsarFileUriResponse;
-import org.openo.commontosca.catalog.entity.response.PackageMeta;
-import org.openo.commontosca.catalog.entity.response.UploadPackageResponse;
-import org.openo.commontosca.catalog.filemanage.FileManagerFactory;
-import org.openo.commontosca.catalog.filemanage.entity.FileLink;
-import org.openo.commontosca.catalog.model.parser.EnumPackageFormat;
-import org.openo.commontosca.catalog.model.parser.ModelParserFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-
-public class PackageWrapper {
- private static PackageWrapper packageWrapper;
- private static final Logger LOG = LoggerFactory.getLogger(PackageWrapper.class);
-
- /**
- * get PackageWrapper instance.
- * @return package wrapper instance
- */
- public static PackageWrapper getInstance() {
- if (packageWrapper == null) {
- packageWrapper = new PackageWrapper();
- }
- return packageWrapper;
- }
-
- /**
- * query package by id.
- * @param csarId package id
- * @return Response
- */
- public Response queryPackageById(String csarId) {
- ArrayList<PackageData> dbResult = new ArrayList<PackageData>();
- ArrayList<PackageMeta> result = new ArrayList<PackageMeta>();
- dbResult = PackageWrapperUtil.getPackageInfoById(csarId);
- if (dbResult.size() != 0) {
- result = PackageWrapperUtil.packageDataList2PackageMetaList(dbResult);
- return Response.ok(result).build();
- } else {
- String errorMsg = "get package info by Id error !";
- return RestUtil.getRestException(errorMsg);
- }
- }
-
- /**
- * upload package.
- * @param uploadedInputStream inputStream
- * @param fileDetail package detail
- * @param head http header
- * @return Response
- * @throws Exception e
- */
- public Response uploadPackage(InputStream uploadedInputStream,
- FormDataContentDisposition fileDetail, HttpHeaders head) throws Exception {
- PackageBasicInfo basicInfo = new PackageBasicInfo();
- String tempDirName = null;
- int fileSize = 0;
- String fileName = "";
- UploadPackageResponse result = new UploadPackageResponse();
- PackageMeta packageMeta = new PackageMeta();
- if (uploadedInputStream == null) {
- LOG.info("the uploadStream is null");
- return Response.serverError().build();
- }
- if (fileDetail == null) {
- LOG.info("the fileDetail is null");
- return Response.serverError().build();
- }
-
- try {
- String contentRange = null;
- fileName = ToolUtil.processFileName(fileDetail.getFileName());
- tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName);
- if (head != null) {
- contentRange = head.getHeaderString(CommonConstant.HTTP_HEADER_CONTENT_RANGE);
- }
- LOG.debug("store package chunk file, fileName:" + fileName + ",contentRange:" + contentRange);
- if (ToolUtil.isEmptyString(contentRange)) {
- fileSize = uploadedInputStream.available();
- contentRange = "0-" + fileSize + "/" + fileSize;
- }
- String fileLocation =
- ToolUtil.storeChunkFileInLocal(tempDirName, fileName, uploadedInputStream);
- LOG.info("the fileLocation when upload package is :" + fileLocation);
- uploadedInputStream.close();
-
- basicInfo = PackageWrapperUtil.getPacageBasicInfo(fileLocation);
- String path =
- basicInfo.getType().toString() + File.separator + basicInfo.getProvider()
- + File.separator + fileName.replace(".csar", "") + File.separator
- + basicInfo.getVersion();
- LOG.info("dest path is : " + path);
- packageMeta = PackageWrapperUtil.getPackageMeta(fileName, fileLocation, basicInfo);
- String dowloadUri = File.separator + path + File.separator;
- String destPath = File.separator + path;
- packageMeta.setDownloadUri(dowloadUri);
- LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta));
- Boolean isEnd = PackageWrapperUtil.isUploadEnd(contentRange, fileName);
- if (isEnd) {
- boolean uploadResult = FileManagerFactory.createFileManager().upload(tempDirName, destPath);
- if (uploadResult == true) {
- // 调袁虎的接口,将fileLocation 和 packageId传给他,由他去解析包,并向数据库存储数据
- // String parseResult =
- // ModelParserFactory.getInstance().parse(packageMeta.getCsarId(),
- // fileLocation , EnumPackageFormat.valueOf(packageMeta.getFormat()));
- PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta);
- PackageManager.getInstance().addPackage(packageData);
- }
- LOG.info("upload package file end, fileName:" + fileName);
- }
- result.setCsarId(packageMeta.getCsarId());
- return Response.ok(result).build();
- } catch (Exception e1) {
- LOG.error("upload package fail.", e1);
- String csarId = packageMeta.getCsarId();
- if (csarId != null) {
- PackageManager.getInstance().deletePackage(csarId);
- }
- return RestUtil.getRestException(e1.getMessage());
- } finally {
- if (tempDirName != null) {
- ToolUtil.deleteDir(new File(tempDirName));
- }
- }
- }
-
- /**
- * delete package by package id.
- * @param csarId package id
- * @return Response
- */
- public Response delPackage(String csarId) {
- LOG.info("delete package info.csarId:" + csarId);
- if (ToolUtil.isEmptyString(csarId)) {
- LOG.error("delete package fail, csarid is null");
- return Response.serverError().build();
- }
- try {
- DelCsarThread thread = new DelCsarThread(csarId, false);
- new Thread(thread).start();
- return Response.noContent().build();
- } catch (Exception e1) {
- LOG.error("delete fail.", e1);
- return RestUtil.getRestException(e1.getMessage());
- }
- }
-
- // public Response delPackageByServiceTemplateId(String serviceTemplateId) {
- // LOG.info("delete package info.serviceTemplateId:" + serviceTemplateId);
- // if (ToolUtil.isEmptyString(serviceTemplateId)) {
- // LOG.error("delete package fail, serviceTemplateId is null");
- // return Response.serverError().build();
- // }
- // ArrayList<PackageData> result = new ArrayList<PackageData>();
- // try {
- // result = PackageManager.getInstance().queryPackageByServiceTemplateId(serviceTemplateId);
- //
- // } catch (CatalogResourceException e) {
- // LOG.error("query package by csarId from db error ! " + e.getMessage());
- // return RestUtil.getRestException(e.getMessage());
- // }
- // if (result.size() <= 0) {
- // LOG.warn("not exist package by serviceTemplateId");
- // return Response.status(Status.NOT_FOUND).build();
- // }
- // if ("true".equals(result.get(0).getDeletionPending())) {
- // LOG.info("start delete package.csarId:" + result.get(0).getCsarId());
- // delCsarThread thread = new delCsarThread(result.get(0).getCsarId(), true);
- // new Thread(thread).start();
- // }
- // return Response.noContent().build();
- // }
-
- class DelCsarThread implements Runnable {
- private String csarid;
- private boolean isInstanceTemplate = false;
-
- public DelCsarThread(String csarid, boolean isInstanceTemplate) {
- this.csarid = csarid;
- this.isInstanceTemplate = isInstanceTemplate;
- }
-
- @Override
- public void run() {
- try {
- if (!ToolUtil.isEmptyString(csarid)) {
- delCsarData(csarid);
- }
- } catch (Exception e1) {
- LOG.error("del instance csar fail.", e1);
- updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETE_FAIL,
- null);
- // publishDelFinishCometdMessage(csarid, "false");
- }
- }
-
- private void delCsarData(String csarId) {
- updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETING, null);
- String packagePath = PackageWrapperUtil.getPackagePath(csarId);
- if (packagePath == null) {
- LOG.error("package path is null! ");
- return;
- }
- FileManagerFactory.createFileManager().delete(packagePath);
- try {
- PackageManager.getInstance().deletePackage(csarId);
- } catch (CatalogResourceException e1) {
- LOG.error("delete package by csarId from db error ! " + e1.getMessage());
- }
- // delete template data from db
- PackageData packageData = new PackageData();
- packageData.setCsarId(csarId);
- try {
- TemplateManager.getInstance().deleteServiceTemplateByCsarPackageInfo(packageData);
- } catch (CatalogResourceException e2) {
- LOG.error("delete template data from db error! csarId = " + csarId);
- }
- // publishDelFinishCometdMessage(csarid, "true");
- }
-
- // private void publishDelFinishCometdMessage(String csarid, String csarDelStatus) {
- // if (isInstanceTemplate) {
- // LOG.info("delete instance Template finish. csarid:{}", csarid);
- // return;
- // }
- // try {
- // Map<String, Object> cometdMessage = new HashMap<String, Object>();
- // cometdMessage.put("csarid", csarid);
- // cometdMessage.put("status", csarDelStatus);
- // CometdService.getInstance().publish(CommonConstant.COMETD_CHANNEL_PACKAGE_DELETE,
- // cometdMessage);
- // } catch (CometdException e) {
- // LOG.error("publish delfinish cometdmsg fail.", e);
- // }
- // }
- }
-
- /**
- * update package status.
- * @param csarId package id
- * @param operationalState package operational state
- * @param usageState package usage state
- * @param onBoardState package onboard state
- * @param processState package process state
- * @param deletionPending package deletionPending status
- * @return Response
- */
- public Response updatePackageStatus(String csarId, String operationalState, String usageState,
- String onBoardState, String processState, String deletionPending) {
- LOG.info("update package status info.csarId:" + csarId + " operationalState:"
- + operationalState);
- if (ToolUtil.isEmptyString(csarId)) {
- LOG.error("update csar status fail, csarid is null");
- return Response.serverError().build();
- }
- try {
- // UpdatePackageResponse result = new UpdatePackageResponse();
- PackageData packageInfo = new PackageData();
- if (operationalState != null) {
- packageInfo.setOperationalState(operationalState);
- }
- if (usageState != null) {
- packageInfo.setUsageState(usageState);
- }
- if (onBoardState != null) {
- packageInfo.setOnBoardState(onBoardState);
- }
- if (processState != null) {
- packageInfo.setProcessState(processState);
- }
- if (deletionPending != null) {
- packageInfo.setDeletionPending(deletionPending);
- }
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String currentTime = sdf1.format(new Date());
- packageInfo.setModifyTime(currentTime);
- PackageManager.getInstance().updatePackage(packageInfo, csarId);
- // ArrayList<PackageData> pacackgeList = PackageWrapperUtil.getPackageInfoById(csarId);
- // String finalUsageState = pacackgeList.get(0).getUsageState();
- // result.setUsageState(finalUsageState);
- return Response.ok().build();
- } catch (CatalogResourceException e1) {
- LOG.error("update package status by csarId from db error ! " + e1.getMessage());
- return RestUtil.getRestException(e1.getMessage());
- }
- }
-
- /**
- * download package by package id.
- * @param csarId package id
- * @return Response
- */
- public Response downloadCsarPackagesById(String csarId) {
- ArrayList<PackageData> packageList = PackageWrapperUtil.getPackageInfoById(csarId);
- String packageName = null;
- if (null != packageList && packageList.size() > 0) {
- packageName = packageList.get(0).getName();
- }
- String path = ToolUtil.getCatalogueCsarPath() + File.separator + packageName;
- File csarFile = new File(path);
- if (!csarFile.exists()) {
- return Response.status(Status.NOT_FOUND).build();
- }
-
- try {
- InputStream fis = new BufferedInputStream(new FileInputStream(path));
- return Response.ok(fis)
- .header("Content-Disposition", "attachment; filename=\"" + csarFile.getName() + "\"")
- .build();
- } catch (Exception e1) {
- LOG.error("download vnf package fail.", e1);
- return RestUtil.getRestException(e1.getMessage());
- }
- }
-
- /**
- * query package list by condition.
- * @param name package name
- * @param provider package provider
- * @param version package version
- * @param deletionPending package deletionPending
- * @param type package type
- * @return Response
- */
- public Response queryPackageListByCond(String name, String provider, String version,
- String deletionPending, String type) {
- ArrayList<PackageData> dbresult = new ArrayList<PackageData>();
- ArrayList<PackageMeta> result = new ArrayList<PackageMeta>();
- LOG.info("query package info.name:" + name + " provider:" + provider + " version" + version
- + " deletionPending" + deletionPending + " type:" + type);
- try {
- dbresult =
- PackageManager.getInstance().queryPackage(name, provider, version, deletionPending, type);
- result = PackageWrapperUtil.packageDataList2PackageMetaList(dbresult);
- return Response.ok(result).build();
- } catch (CatalogResourceException e1) {
- LOG.error("query package by csarId from db error ! " + e1.getMessage());
- return RestUtil.getRestException(e1.getMessage());
- }
- }
-
- /**
- * get package file uri.
- * @param csarId package id
- * @param relativePath file relative path
- * @return Response
- */
- public Response getCsarFileUri(String csarId, String relativePath) {
- try {
- CsarFileUriResponse result = getCsarFileDownloadUri(csarId, relativePath);
- return Response.ok(result).build();
- } catch (CatalogResourceException e1) {
- LOG.error("Query CSAR package by ID failed ! csarId = " + csarId);
- }
-
- return Response.serverError().build();
- }
-
- /**
- * get package file download uri.
- * @param csarId package id
- * @param relativePath package file relative path
- * @return CsarFileUriResponse
- * @throws CatalogResourceException
- */
- public CsarFileUriResponse getCsarFileDownloadUri(String csarId, String relativePath)
- throws CatalogResourceException {
- CsarFileUriResponse result = new CsarFileUriResponse();
- String downloadUrl = null;
- String downloadUri = null;
- String localPath = null;
- ArrayList<PackageData> packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
- if (packageList != null && packageList.size() != 0) {
- String packageName = packageList.get(0).getName();
- String relativeUri = packageList.get(0).getDownloadUri() + packageName;
- downloadUri = relativeUri + relativePath;
- downloadUrl = PackageWrapperUtil.getUrl(downloadUri);
- String httpUri = HttpServerPathConfig.getHttpServerPath() + downloadUri;
- localPath = PackageWrapperUtil.getLocalPath(httpUri);
- }
- result.setDownloadUri(downloadUrl);
- result.setLocalPath(localPath);
- return result;
- }
-
- /**
- * upload package from ftp.
- * @param request package basic information
- * @return Response
- */
- public Response uploadPackageFromFtp(UploadPackageFromFtpRequest request) {
- PackageBasicInfo basicInfo = new PackageBasicInfo();
- String tempDirName = null;
- String fileName = "";
- UploadPackageResponse result = new UploadPackageResponse();
- basicInfo.setProvider("zte");
- basicInfo.setType(EnumType.NSAR);
- basicInfo.setVersion("v1.0");
- PackageMeta packageMeta = new PackageMeta();
-
- try {
- String ftpUrl = request.getFtpUrl();
- String packageName = PackageWrapperUtil.getPackageName(ftpUrl);
- fileName = ToolUtil.processFileName(packageName);
- tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName);
- PackageWrapperUtil.downPackageFromFtp(ftpUrl, tempDirName);
- String path =
- basicInfo.getType().toString() + File.separator + basicInfo.getProvider()
- + File.separator + fileName.replace(".csar", "") + File.separator
- + basicInfo.getVersion();
- LOG.info("dest path is : " + path);
- packageMeta = PackageWrapperUtil.getPackageMeta(fileName, tempDirName, basicInfo);
- String dowloadUri = File.separator + path + File.separator + fileName;
- packageMeta.setDownloadUri(dowloadUri);
- LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta));
- String destPath = File.separator + path;
- boolean uploadResult = FileManagerFactory.createFileManager().upload(tempDirName, destPath);
- if (uploadResult == true) {
- String newZipPath = tempDirName + fileName.replace(".csar", ".zip");
- ZipCompressor zc = new ZipCompressor(newZipPath);
- String metadataPath = tempDirName + File.separator + CommonConstant.TOSCA_METADATA;
- String definitions = tempDirName + File.separator + CommonConstant.DEFINITIONS;
- zc.compress(metadataPath, definitions);
- // 调袁虎的接口,将fileLocation 和 packageId传给他,由他去解析包,并向数据库存储数据
-// String parseResult =
- ModelParserFactory.getInstance().parse(packageMeta.getCsarId(), newZipPath,
- EnumPackageFormat.valueOf(packageMeta.getFormat()));
- PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta);
- PackageManager.getInstance().addPackage(packageData);
- }
- LOG.info("upload package file end, fileName:" + fileName);
- result.setCsarId(packageMeta.getCsarId());
- return Response.ok(result).build();
- } catch (Exception e1) {
- LOG.error("upload package fail.", e1);
- String csarId = packageMeta.getCsarId();
- if (csarId != null) {
- try {
- PackageManager.getInstance().deletePackage(csarId);
- } catch (CatalogResourceException e2) {
- LOG.error("delete package failed !");
- }
- }
- return RestUtil.getRestException(e1.getMessage());
- } finally {
- if (tempDirName != null) {
- ToolUtil.deleteDir(new File(tempDirName));
- }
- }
- }
-
- /**
- * get csar plan uri.
- * @param csarId package id
- * @return Response
- */
- public Response getCsarPlansUri(String csarId) {
- ArrayList<FileLink> fileLinks = new ArrayList<FileLink>();
- LOG.info("start query plans of package.csarId:" + csarId);
- ArrayList<PackageData> packageList = new ArrayList<PackageData>();
- try {
- packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
- if (packageList != null && packageList.size() != 0) {
- String downloadUri = packageList.get(0).getDownloadUri();
- fileLinks = FileManagerFactory.createFileManager().queryWorkFlow(downloadUri);
- }
- return Response.ok(fileLinks).build();
- } catch (CatalogResourceException e1) {
- LOG.error("Query plans of package by ID failed ! csarId = " + csarId);
- return RestUtil.getRestException(e1.getMessage());
- }
- // return Response.serverError().build();
- }
-}
+/**
+ * Copyright 2016 [ZTE] and others.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.commontosca.catalog.wrapper;
+
+import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
+import org.openo.commontosca.catalog.common.CommonConstant;
+import org.openo.commontosca.catalog.common.HttpServerPathConfig;
+import org.openo.commontosca.catalog.common.RestUtil;
+import org.openo.commontosca.catalog.common.ToolUtil;
+import org.openo.commontosca.catalog.common.ZipCompressor;
+import org.openo.commontosca.catalog.db.entity.PackageData;
+import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
+import org.openo.commontosca.catalog.db.resource.PackageManager;
+import org.openo.commontosca.catalog.db.resource.TemplateManager;
+import org.openo.commontosca.catalog.entity.EnumType;
+import org.openo.commontosca.catalog.entity.request.PackageBasicInfo;
+import org.openo.commontosca.catalog.entity.request.UploadPackageFromFtpRequest;
+import org.openo.commontosca.catalog.entity.response.CsarFileUriResponse;
+import org.openo.commontosca.catalog.entity.response.PackageMeta;
+import org.openo.commontosca.catalog.entity.response.UploadPackageResponse;
+import org.openo.commontosca.catalog.filemanage.FileManagerFactory;
+import org.openo.commontosca.catalog.filemanage.entity.FileLink;
+import org.openo.commontosca.catalog.model.parser.EnumPackageFormat;
+import org.openo.commontosca.catalog.model.parser.ModelParserFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+
+public class PackageWrapper {
+ private static PackageWrapper packageWrapper;
+ private static final Logger LOG = LoggerFactory.getLogger(PackageWrapper.class);
+
+ /**
+ * get PackageWrapper instance.
+ * @return package wrapper instance
+ */
+ public static PackageWrapper getInstance() {
+ if (packageWrapper == null) {
+ packageWrapper = new PackageWrapper();
+ }
+ return packageWrapper;
+ }
+
+ /**
+ * query package by id.
+ * @param csarId package id
+ * @return Response
+ */
+ public Response queryPackageById(String csarId) {
+ ArrayList<PackageData> dbResult = new ArrayList<PackageData>();
+ ArrayList<PackageMeta> result = new ArrayList<PackageMeta>();
+ dbResult = PackageWrapperUtil.getPackageInfoById(csarId);
+ if (dbResult.size() != 0) {
+ result = PackageWrapperUtil.packageDataList2PackageMetaList(dbResult);
+ return Response.ok(result).build();
+ } else {
+ String errorMsg = "get package info by Id error !";
+ return RestUtil.getRestException(errorMsg);
+ }
+ }
+
+ /**
+ * upload package.
+ * @param uploadedInputStream inputStream
+ * @param fileDetail package detail
+ * @param head http header
+ * @return Response
+ * @throws Exception e
+ */
+ public Response uploadPackage(InputStream uploadedInputStream,
+ FormDataContentDisposition fileDetail, HttpHeaders head) throws Exception {
+ PackageBasicInfo basicInfo = new PackageBasicInfo();
+ String tempDirName = null;
+ int fileSize = 0;
+ String fileName = "";
+ UploadPackageResponse result = new UploadPackageResponse();
+ PackageMeta packageMeta = new PackageMeta();
+ if (uploadedInputStream == null) {
+ LOG.info("the uploadStream is null");
+ return Response.serverError().build();
+ }
+ if (fileDetail == null) {
+ LOG.info("the fileDetail is null");
+ return Response.serverError().build();
+ }
+
+ try {
+ String contentRange = null;
+ fileName = ToolUtil.processFileName(fileDetail.getFileName());
+ tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName);
+ if (head != null) {
+ contentRange = head.getHeaderString(CommonConstant.HTTP_HEADER_CONTENT_RANGE);
+ }
+ LOG.debug("store package chunk file, fileName:" + fileName + ",contentRange:" + contentRange);
+ if (ToolUtil.isEmptyString(contentRange)) {
+ fileSize = uploadedInputStream.available();
+ contentRange = "0-" + fileSize + "/" + fileSize;
+ }
+ String fileLocation =
+ ToolUtil.storeChunkFileInLocal(tempDirName, fileName, uploadedInputStream);
+ LOG.info("the fileLocation when upload package is :" + fileLocation);
+ uploadedInputStream.close();
+
+ basicInfo = PackageWrapperUtil.getPacageBasicInfo(fileLocation);
+ String path =
+ basicInfo.getType().toString() + File.separator + basicInfo.getProvider()
+ + File.separator + fileName.replace(".csar", "") + File.separator
+ + basicInfo.getVersion();
+ LOG.info("dest path is : " + path);
+ packageMeta = PackageWrapperUtil.getPackageMeta(fileName, fileLocation, basicInfo);
+ String dowloadUri = File.separator + path + File.separator;
+ String destPath = File.separator + path;
+ packageMeta.setDownloadUri(dowloadUri);
+ LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta));
+ Boolean isEnd = PackageWrapperUtil.isUploadEnd(contentRange, fileName);
+ if (isEnd) {
+ boolean uploadResult = FileManagerFactory.createFileManager().upload(tempDirName, destPath);
+ if (uploadResult == true) {
+ try {
+ String tempCsarPath = tempDirName + File.separator + fileName;
+ ModelParserFactory.getInstance().parse(packageMeta.getCsarId(),
+ tempCsarPath , PackageWrapperUtil.getPackageFormat(packageMeta.getFormat()));
+ } catch (CatalogResourceException e1) {
+ LOG.error("parse package error ! " + e1.getMessage());
+ }
+ PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta);
+ PackageManager.getInstance().addPackage(packageData);
+ }
+ LOG.info("upload package file end, fileName:" + fileName);
+ }
+ result.setCsarId(packageMeta.getCsarId());
+ return Response.ok(result).build();
+ } catch (Exception e1) {
+ LOG.error("upload package fail.", e1);
+ String csarId = packageMeta.getCsarId();
+ if (csarId != null) {
+ PackageManager.getInstance().deletePackage(csarId);
+ }
+ return RestUtil.getRestException(e1.getMessage());
+ } finally {
+ if (tempDirName != null) {
+ ToolUtil.deleteDir(new File(tempDirName));
+ }
+ }
+ }
+
+ /**
+ * delete package by package id.
+ * @param csarId package id
+ * @return Response
+ */
+ public Response delPackage(String csarId) {
+ LOG.info("delete package info.csarId:" + csarId);
+ if (ToolUtil.isEmptyString(csarId)) {
+ LOG.error("delete package fail, csarid is null");
+ return Response.serverError().build();
+ }
+ try {
+ DelCsarThread thread = new DelCsarThread(csarId, false);
+ new Thread(thread).start();
+ return Response.noContent().build();
+ } catch (Exception e1) {
+ LOG.error("delete fail.", e1);
+ return RestUtil.getRestException(e1.getMessage());
+ }
+ }
+
+ // public Response delPackageByServiceTemplateId(String serviceTemplateId) {
+ // LOG.info("delete package info.serviceTemplateId:" + serviceTemplateId);
+ // if (ToolUtil.isEmptyString(serviceTemplateId)) {
+ // LOG.error("delete package fail, serviceTemplateId is null");
+ // return Response.serverError().build();
+ // }
+ // ArrayList<PackageData> result = new ArrayList<PackageData>();
+ // try {
+ // result = PackageManager.getInstance().queryPackageByServiceTemplateId(serviceTemplateId);
+ //
+ // } catch (CatalogResourceException e) {
+ // LOG.error("query package by csarId from db error ! " + e.getMessage());
+ // return RestUtil.getRestException(e.getMessage());
+ // }
+ // if (result.size() <= 0) {
+ // LOG.warn("not exist package by serviceTemplateId");
+ // return Response.status(Status.NOT_FOUND).build();
+ // }
+ // if ("true".equals(result.get(0).getDeletionPending())) {
+ // LOG.info("start delete package.csarId:" + result.get(0).getCsarId());
+ // delCsarThread thread = new delCsarThread(result.get(0).getCsarId(), true);
+ // new Thread(thread).start();
+ // }
+ // return Response.noContent().build();
+ // }
+
+ class DelCsarThread implements Runnable {
+ private String csarid;
+ private boolean isInstanceTemplate = false;
+
+ public DelCsarThread(String csarid, boolean isInstanceTemplate) {
+ this.csarid = csarid;
+ this.isInstanceTemplate = isInstanceTemplate;
+ }
+
+ @Override
+ public void run() {
+ try {
+ if (!ToolUtil.isEmptyString(csarid)) {
+ delCsarData(csarid);
+ }
+ } catch (Exception e1) {
+ LOG.error("del instance csar fail.", e1);
+ updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETE_FAIL,
+ null);
+ // publishDelFinishCometdMessage(csarid, "false");
+ }
+ }
+
+ private void delCsarData(String csarId) {
+ updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETING, null);
+ String packagePath = PackageWrapperUtil.getPackagePath(csarId);
+ if (packagePath == null) {
+ LOG.error("package path is null! ");
+ return;
+ }
+ FileManagerFactory.createFileManager().delete(packagePath);
+ try {
+ PackageManager.getInstance().deletePackage(csarId);
+ } catch (CatalogResourceException e1) {
+ LOG.error("delete package by csarId from db error ! " + e1.getMessage());
+ }
+ // delete template data from db
+ PackageData packageData = new PackageData();
+ packageData.setCsarId(csarId);
+ try {
+ TemplateManager.getInstance().deleteServiceTemplateByCsarPackageInfo(packageData);
+ } catch (CatalogResourceException e2) {
+ LOG.error("delete template data from db error! csarId = " + csarId);
+ }
+ // publishDelFinishCometdMessage(csarid, "true");
+ }
+
+ // private void publishDelFinishCometdMessage(String csarid, String csarDelStatus) {
+ // if (isInstanceTemplate) {
+ // LOG.info("delete instance Template finish. csarid:{}", csarid);
+ // return;
+ // }
+ // try {
+ // Map<String, Object> cometdMessage = new HashMap<String, Object>();
+ // cometdMessage.put("csarid", csarid);
+ // cometdMessage.put("status", csarDelStatus);
+ // CometdService.getInstance().publish(CommonConstant.COMETD_CHANNEL_PACKAGE_DELETE,
+ // cometdMessage);
+ // } catch (CometdException e) {
+ // LOG.error("publish delfinish cometdmsg fail.", e);
+ // }
+ // }
+ }
+
+ /**
+ * update package status.
+ * @param csarId package id
+ * @param operationalState package operational state
+ * @param usageState package usage state
+ * @param onBoardState package onboard state
+ * @param processState package process state
+ * @param deletionPending package deletionPending status
+ * @return Response
+ */
+ public Response updatePackageStatus(String csarId, String operationalState, String usageState,
+ String onBoardState, String processState, String deletionPending) {
+ LOG.info("update package status info.csarId:" + csarId + " operationalState:"
+ + operationalState);
+ if (ToolUtil.isEmptyString(csarId)) {
+ LOG.error("update csar status fail, csarid is null");
+ return Response.serverError().build();
+ }
+ try {
+ // UpdatePackageResponse result = new UpdatePackageResponse();
+ PackageData packageInfo = new PackageData();
+ if (operationalState != null) {
+ packageInfo.setOperationalState(operationalState);
+ }
+ if (usageState != null) {
+ packageInfo.setUsageState(usageState);
+ }
+ if (onBoardState != null) {
+ packageInfo.setOnBoardState(onBoardState);
+ }
+ if (processState != null) {
+ packageInfo.setProcessState(processState);
+ }
+ if (deletionPending != null) {
+ packageInfo.setDeletionPending(deletionPending);
+ }
+ SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ String currentTime = sdf1.format(new Date());
+ packageInfo.setModifyTime(currentTime);
+ PackageManager.getInstance().updatePackage(packageInfo, csarId);
+ // ArrayList<PackageData> pacackgeList = PackageWrapperUtil.getPackageInfoById(csarId);
+ // String finalUsageState = pacackgeList.get(0).getUsageState();
+ // result.setUsageState(finalUsageState);
+ return Response.ok().build();
+ } catch (CatalogResourceException e1) {
+ LOG.error("update package status by csarId from db error ! " + e1.getMessage());
+ return RestUtil.getRestException(e1.getMessage());
+ }
+ }
+
+ /**
+ * download package by package id.
+ * @param csarId package id
+ * @return Response
+ */
+ public Response downloadCsarPackagesById(String csarId) {
+ ArrayList<PackageData> packageList = PackageWrapperUtil.getPackageInfoById(csarId);
+ String packageName = null;
+ if (null != packageList && packageList.size() > 0) {
+ packageName = packageList.get(0).getName();
+ }
+ String path = ToolUtil.getCatalogueCsarPath() + File.separator + packageName;
+ File csarFile = new File(path);
+ if (!csarFile.exists()) {
+ return Response.status(Status.NOT_FOUND).build();
+ }
+
+ try {
+ InputStream fis = new BufferedInputStream(new FileInputStream(path));
+ return Response.ok(fis)
+ .header("Content-Disposition", "attachment; filename=\"" + csarFile.getName() + "\"")
+ .build();
+ } catch (Exception e1) {
+ LOG.error("download vnf package fail.", e1);
+ return RestUtil.getRestException(e1.getMessage());
+ }
+ }
+
+ /**
+ * query package list by condition.
+ * @param name package name
+ * @param provider package provider
+ * @param version package version
+ * @param deletionPending package deletionPending
+ * @param type package type
+ * @return Response
+ */
+ public Response queryPackageListByCond(String name, String provider, String version,
+ String deletionPending, String type) {
+ ArrayList<PackageData> dbresult = new ArrayList<PackageData>();
+ ArrayList<PackageMeta> result = new ArrayList<PackageMeta>();
+ LOG.info("query package info.name:" + name + " provider:" + provider + " version" + version
+ + " deletionPending" + deletionPending + " type:" + type);
+ try {
+ dbresult =
+ PackageManager.getInstance().queryPackage(name, provider, version, deletionPending, type);
+ result = PackageWrapperUtil.packageDataList2PackageMetaList(dbresult);
+ return Response.ok(result).build();
+ } catch (CatalogResourceException e1) {
+ LOG.error("query package by csarId from db error ! " + e1.getMessage());
+ return RestUtil.getRestException(e1.getMessage());
+ }
+ }
+
+ /**
+ * get package file uri.
+ * @param csarId package id
+ * @param relativePath file relative path
+ * @return Response
+ */
+ public Response getCsarFileUri(String csarId, String relativePath) {
+ try {
+ CsarFileUriResponse result = getCsarFileDownloadUri(csarId, relativePath);
+ return Response.ok(result).build();
+ } catch (CatalogResourceException e1) {
+ LOG.error("Query CSAR package by ID failed ! csarId = " + csarId);
+ }
+
+ return Response.serverError().build();
+ }
+
+ /**
+ * get package file download uri.
+ * @param csarId package id
+ * @param relativePath package file relative path
+ * @return CsarFileUriResponse
+ * @throws CatalogResourceException e
+ */
+ public CsarFileUriResponse getCsarFileDownloadUri(String csarId, String relativePath)
+ throws CatalogResourceException {
+ CsarFileUriResponse result = new CsarFileUriResponse();
+ String downloadUrl = null;
+ String downloadUri = null;
+ String localPath = null;
+ ArrayList<PackageData> packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
+ if (packageList != null && packageList.size() != 0) {
+ String packageName = packageList.get(0).getName();
+ String relativeUri = packageList.get(0).getDownloadUri() + packageName;
+ downloadUri = relativeUri + relativePath;
+ downloadUrl = PackageWrapperUtil.getUrl(downloadUri);
+ String httpUri = HttpServerPathConfig.getHttpServerPath() + downloadUri;
+ localPath = PackageWrapperUtil.getLocalPath(httpUri);
+ }
+ result.setDownloadUri(downloadUrl);
+ result.setLocalPath(localPath);
+ return result;
+ }
+
+ /**
+ * upload package from ftp.
+ * @param request package basic information
+ * @return Response
+ */
+ public Response uploadPackageFromFtp(UploadPackageFromFtpRequest request) {
+ PackageBasicInfo basicInfo = new PackageBasicInfo();
+ String tempDirName = null;
+ String fileName = "";
+ UploadPackageResponse result = new UploadPackageResponse();
+ basicInfo.setProvider("zte");
+ basicInfo.setType(EnumType.NSAR);
+ basicInfo.setVersion("v1.0");
+ PackageMeta packageMeta = new PackageMeta();
+
+ try {
+ String ftpUrl = request.getFtpUrl();
+ String packageName = PackageWrapperUtil.getPackageName(ftpUrl);
+ fileName = ToolUtil.processFileName(packageName);
+ tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName);
+ PackageWrapperUtil.downPackageFromFtp(ftpUrl, tempDirName);
+ String path =
+ basicInfo.getType().toString() + File.separator + basicInfo.getProvider()
+ + File.separator + fileName.replace(".csar", "") + File.separator
+ + basicInfo.getVersion();
+ LOG.info("dest path is : " + path);
+ packageMeta = PackageWrapperUtil.getPackageMeta(fileName, tempDirName, basicInfo);
+ String dowloadUri = File.separator + path + File.separator + fileName;
+ packageMeta.setDownloadUri(dowloadUri);
+ LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta));
+ String destPath = File.separator + path;
+ boolean uploadResult = FileManagerFactory.createFileManager().upload(tempDirName, destPath);
+ if (uploadResult == true) {
+ String newZipPath = tempDirName + fileName.replace(".csar", ".zip");
+ ZipCompressor zc = new ZipCompressor(newZipPath);
+ String metadataPath = tempDirName + File.separator + CommonConstant.TOSCA_METADATA;
+ String definitions = tempDirName + File.separator + CommonConstant.DEFINITIONS;
+ zc.compress(metadataPath, definitions);
+ String parseResult = ModelParserFactory.getInstance().parse(packageMeta.getCsarId(),
+ newZipPath, EnumPackageFormat.valueOf(packageMeta.getFormat()));
+ PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta);
+ PackageManager.getInstance().addPackage(packageData);
+ }
+ LOG.info("upload package file end, fileName:" + fileName);
+ result.setCsarId(packageMeta.getCsarId());
+ return Response.ok(result).build();
+ } catch (Exception e1) {
+ LOG.error("upload package fail.", e1);
+ String csarId = packageMeta.getCsarId();
+ if (csarId != null) {
+ try {
+ PackageManager.getInstance().deletePackage(csarId);
+ } catch (CatalogResourceException e2) {
+ LOG.error("delete package failed !");
+ }
+ }
+ return RestUtil.getRestException(e1.getMessage());
+ } finally {
+ if (tempDirName != null) {
+ ToolUtil.deleteDir(new File(tempDirName));
+ }
+ }
+ }
+
+ /**
+ * get csar plan uri.
+ * @param csarId package id
+ * @return Response
+ */
+ public Response getCsarPlansUri(String csarId) {
+ ArrayList<FileLink> fileLinks = new ArrayList<FileLink>();
+ LOG.info("start query plans of package.csarId:" + csarId);
+ ArrayList<PackageData> packageList = new ArrayList<PackageData>();
+ try {
+ packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
+ if (packageList != null && packageList.size() != 0) {
+ String downloadUri = packageList.get(0).getDownloadUri();
+ fileLinks = FileManagerFactory.createFileManager().queryWorkFlow(downloadUri);
+ }
+ return Response.ok(fileLinks).build();
+ } catch (CatalogResourceException e1) {
+ LOG.error("Query plans of package by ID failed ! csarId = " + csarId);
+ return RestUtil.getRestException(e1.getMessage());
+ }
+ // return Response.serverError().build();
+ }
+}
diff --git a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java
index 2837fd36..6354e6a1 100644
--- a/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java
+++ b/catalog-core/catalog-mgr/src/main/java/org/openo/commontosca/catalog/wrapper/PackageWrapperUtil.java
@@ -1,413 +1,434 @@
-/**
- * Copyright 2016 [ZTE] and others.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.openo.commontosca.catalog.wrapper;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-
-import javax.ws.rs.NotFoundException;
-
-import org.openo.commontosca.catalog.common.CommonConstant;
-import org.openo.commontosca.catalog.common.FileUtil;
-import org.openo.commontosca.catalog.common.MsbAddrConfig;
-import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
-import org.openo.commontosca.catalog.db.resource.PackageManager;
-import org.openo.commontosca.catalog.entity.EnumProcessState;
-import org.openo.commontosca.catalog.entity.EnumType;
-import org.openo.commontosca.catalog.entity.request.PackageBasicInfo;
-import org.openo.commontosca.catalog.ftp.Ftp;
-import org.openo.commontosca.catalog.model.entity.ServiceTemplate;
-import org.openo.commontosca.catalog.model.externalservice.entity.lifecycle.InstanceEntity;
-import org.openo.commontosca.catalog.model.externalservice.lifecycle.LifeCycleServiceConsumer;
-import org.openo.commontosca.catalog.common.ToolUtil;
-import org.openo.commontosca.catalog.db.entity.PackageData;
-import org.openo.commontosca.catalog.entity.CsarPackage;
-import org.openo.commontosca.catalog.entity.EnumOnboardState;
-import org.openo.commontosca.catalog.entity.EnumOperationalState;
-import org.openo.commontosca.catalog.entity.EnumUsageState;
-import org.openo.commontosca.catalog.entity.response.PackageMeta;
-import org.openo.commontosca.catalog.ftp.FtpUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.gson.Gson;
-import com.google.gson.reflect.TypeToken;
-
-/**
- * @author 00164331
- *
- */
-public class PackageWrapperUtil {
- private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class);
-
-
- public static List<CsarPackage> formJson2Packages(String packageJson) {
- List<CsarPackage> packageList =
- new Gson().fromJson(packageJson, new TypeToken<List<CsarPackage>>() {}.getType());
- if (null == packageList || packageList.size() == 0) {
- throw new NotFoundException("Package do not exist");
- }
- return packageList;
- }
-
- public static long getPacakgeSize(String fileLocation) {
- File file = new File(fileLocation);
- return file.length();
- }
-
- public static PackageData getPackageData(PackageMeta meta) {
- PackageData packageData = new PackageData();
- packageData.setCreateTime(meta.getCreateTime());
- packageData.setDeletionPending(String.valueOf(meta.isDeletionPending()));
- packageData.setDownloadUri(meta.getDownloadUri());
- packageData.setFormat(meta.getFormat());
- packageData.setModifyTime(meta.getModifyTime());
- packageData.setName(meta.getName());
- packageData.setCsarId(meta.getCsarId());
- packageData.setOperationalState(meta.getOperationalState().toString());
- packageData.setProvider(meta.getProvider());
- String fileSize = meta.getSize();
- packageData.setSize(fileSize);
- packageData.setType(meta.getType());
- packageData.setUsageState(meta.getUsageState().toString());
- packageData.setVersion(meta.getVersion());
- packageData.setOnBoardState(meta.getOnBoardState());
- packageData.setProcessState(meta.getProcessState().toString());
- return packageData;
- }
-
- public static boolean isUploadEnd(String contentRange, String csarName) {
- String range = contentRange;
- range = range.replace("bytes", "").trim();
- range = range.substring(0, range.indexOf("/"));
- String size =
- contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim();
- int fileSize = Integer.parseInt(size);
- String[] ranges = range.split("-");
- int startPosition = Integer.parseInt(ranges[0]);
- if (startPosition == 0) {
- // delPackageBySync(csarName);
- }
- // index start from 0
- int endPosition = Integer.parseInt(ranges[1]) + 1;
- if (endPosition >= fileSize) {
- return true;
- }
- return false;
- }
-
- public static ArrayList<PackageData> getPackageInfoById(String csarId) {
- ArrayList<PackageData> result = new ArrayList<PackageData>();
- try {
- result = PackageManager.getInstance().queryPackageByCsarId(csarId);
- } catch (CatalogResourceException e) {
- LOG.error("query package by csarId from db error ! " + e.getMessage());
- }
- return result;
- }
-
- public static PackageMeta getPackageMeta(String fileName, String fileLocation,
- PackageBasicInfo basic) {
- PackageMeta packageMeta = new PackageMeta();
- long size = getPacakgeSize(fileLocation);
- packageMeta.setFormat(basic.getFormat());
- String packageId = ToolUtil.generateId();
- packageMeta.setName(fileName.replace(CommonConstant.CSAR_SUFFIX, ""));
- packageMeta.setCsarId(packageId);
- packageMeta.setType(basic.getType().toString());
- packageMeta.setVersion(basic.getVersion());
- packageMeta.setProvider(basic.getProvider());
- packageMeta.setDeletionPending(false);
- String sizeStr = ToolUtil.getFormatFileSize(size);
- packageMeta.setSize(sizeStr);
- SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- String currentTime = sdf1.format(new Date());
- packageMeta.setCreateTime(currentTime);
- packageMeta.setModifyTime(currentTime);
- packageMeta.setOperationalState(EnumOperationalState.Disabled);
- packageMeta.setUsageState(EnumUsageState.NotInUse);
- packageMeta.setOnBoardState(EnumOnboardState.nonOnBoarded.getValue());
- packageMeta.setProcessState(EnumProcessState.normal);
- return packageMeta;
- }
-
- public static String getPackagePath(String csarId) {
- ArrayList<PackageData> packageList = new ArrayList<PackageData>();
- String downloadUri = null;
- try {
- packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
- downloadUri = packageList.get(0).getDownloadUri();
- } catch (CatalogResourceException e) {
- LOG.error("Query CSAR package by ID failed ! csarId = " + csarId);
- }
- return downloadUri;
- }
-
-
- public static HashSet<String> instanceConvertToHashSet(ArrayList<InstanceEntity> instancelist) {
- HashSet<String> result = new HashSet<String>();
- if (instancelist != null) {
- for (InstanceEntity instance : instancelist) {
- result.add(instance.getServiceTemplateId());
- }
- }
- return result;
- }
-
- public static boolean isExistInstanceCSAR(String csarId) {
- // 查询各O(GSO、NFVO、SDNO)的资源实例数据库,查询指定csarId对应的服务模版
- ArrayList<ServiceTemplate> templateList = queryAvailableTemplatesByCsar(csarId);
- // 调生命周期的接口查询所有实例,查询实例中是否包含指定csarId对应的服务模析ID
- HashSet<String> templateSet = instanceConvertToHashSet(LifeCycleServiceConsumer.getInstances());
- if (templateList != null && templateList.size() > 0 && templateSet.size() > 0) {
- for (ServiceTemplate temp : templateList) {
- if (templateSet.contains(temp.getServiceTemplateId())) {
- return true;
- }
- }
- }
- return false;
- }
-
- public static ArrayList<ServiceTemplate> queryAvailableTemplatesByCsar(String csarId) {
- return null;
- // ArrayList<ServiceTemplate> resultlist = new ArrayList<ServiceTemplate>();
- // String filter = LDAPUtil.getObjectClassFilter(LDAPConstant.OBJECTCLASS_CSAR);
- // String result =
- // LDAPDataFactory.getInstance().queryData(EnumLDAPData.SERVICETEMPLATE, null, false,
- // filter);
- // Type type = new TypeToken<ArrayList<ServiceTemplate>>() {}.getType();
- // ArrayList<ServiceTemplate> templateList = new Gson().fromJson(result, type);
- // for (ServiceTemplate temp : templateList) {
- // if (temp.getCsarid().equals(csarId)) {
- // resultlist.add(temp);
- // }
- // }
- // return resultlist;
- }
-
- // public static void publishDeletionPendingStatusCometdMessage(String csarid) {
- // try {
- // Map<String, Object> cometdMessage = new HashMap<String, Object>();
- // cometdMessage.put("csarid", csarid);
- // cometdMessage.put("status", "deletionPending");
- // CometdService.getInstance().publish(CommonConstant.COMETD_CHANNEL_PACKAGE_DELETE,
- // cometdMessage);
- // } catch (CometdException e) {
- // LOG.error("publish delfinish cometdmsg fail.", e);
- // }
- // }
-
- /**
- * @param ftpUrl
- * @return
- */
- public static Ftp getFtpDetail(String ftpUrl) {
- Ftp ftp = new Ftp();
- int index1 = ftpUrl.indexOf("ftp://");
- int index2 = ftpUrl.indexOf("@");
- String userPassSubString = ftpUrl.substring(index1, index2);
- int index3 = userPassSubString.indexOf(":");
- String userName = userPassSubString.substring(0, index3);
- String pass = userPassSubString.substring(index3 + 1);
- String subString1 = ftpUrl.substring(index2 + 1);
- int index4 = subString1.indexOf("/");
- String ipPortSubString = subString1.substring(0, index4);
- int index5 = ipPortSubString.indexOf(":");
- String ip = ipPortSubString.substring(0, index5);
- String port = ipPortSubString.substring(index5 + 1);
- int index6 = ftpUrl.lastIndexOf("/");
- String path = ftpUrl.substring(0, index6);
- ftp.setIpAddr(ip);
- ftp.setPath(path);
- ftp.setPort(Integer.valueOf(port));
- ftp.setPwd(pass);
- ftp.setUserName(userName);
- return ftp;
- }
-
- /**
- * @param ftpUrl
- * @return
- */
- // public static String getFtpDir(String ftpUrl) {
- // // TODO Auto-generated method stub
- // return null;
- // }
-
- /**
- * @param ftpUrl
- * @return
- */
- public static String getPackageName(String ftpUrl) {
- int index = ftpUrl.lastIndexOf("/");
- String packageName = ftpUrl.substring(index);
- return packageName;
- }
-
- public static void downPackageFromFtp(String ftpUrl, String tempDirName) {
- Ftp ftp = new Ftp();
- ftp = PackageWrapperUtil.getFtpDetail(ftpUrl);
- String remoteBaseDir = ftp.getPath();
- try {
- FtpUtil.startDown(ftp, tempDirName, remoteBaseDir);
- } catch (Exception e) {
- LOG.error("Down package from ftp failed !");
- }
- }
-
- /**
- * @param dbResult
- * @return
- */
- public static ArrayList<PackageMeta> packageDataList2PackageMetaList(
- ArrayList<PackageData> dbResult) {
- ArrayList<PackageMeta> metas = new ArrayList<PackageMeta>();
- PackageMeta meta = new PackageMeta();
- for (int i = 0; i < dbResult.size(); i++) {
- PackageData data = dbResult.get(i);
- meta = packageData2PackageMeta(data);
- metas.add(meta);
- }
- return metas;
- }
-
- public static EnumOnboardState getEnumByValue(String value) {
- if (value == "non-onBoarded") {
- return EnumOnboardState.nonOnBoarded;
- } else {
- return EnumOnboardState.onBoarded;
- }
- }
-
- private static PackageMeta packageData2PackageMeta(PackageData packageData) {
- PackageMeta meta = new PackageMeta();
- meta.setCsarId(packageData.getCsarId());
- meta.setCreateTime(packageData.getCreateTime());
- meta.setDeletionPending(Boolean.getBoolean(packageData.getDeletionPending()));
- String packageUri =
- packageData.getDownloadUri() + packageData.getName() + CommonConstant.CSAR_SUFFIX;
- String packageUrl = getUrl(packageUri);
- meta.setDownloadUri(packageUrl);
- meta.setFormat(packageData.getFormat());
- meta.setModifyTime(packageData.getModifyTime());
- meta.setName(packageData.getName());
- meta.setOperationalState(EnumOperationalState.valueOf(packageData.getOperationalState()));
- meta.setProvider(packageData.getProvider());
- meta.setSize(packageData.getSize());
- meta.setType(packageData.getType());
- meta.setUsageState(EnumUsageState.valueOf(packageData.getUsageState()));
- meta.setVersion(packageData.getVersion());
- meta.setOnBoardState(packageData.getOnBoardState());
- meta.setProcessState(EnumProcessState.valueOf(packageData.getProcessState()));
- return meta;
- }
-
- public static String getUrl(String uri) {
- String url = null;
- if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) {
- url = MsbAddrConfig.getMsbAddress() + uri.substring(1);
- }
- url = MsbAddrConfig.getMsbAddress() + uri;
- String urlresult = url.replace("\\", "/");
- return urlresult;
- }
-
- public static String getLocalPath(String uri) {
- File srcDir = new File(uri);
- String localPath = srcDir.getAbsolutePath();
- return localPath.replace("\\", "/");
- }
-
- /**
- * @param fileLocation
- * @return
- */
- public static PackageBasicInfo getPacageBasicInfo(String fileLocation) {
- PackageBasicInfo basicInfo = new PackageBasicInfo();
- String unzipDir = ToolUtil.getUnzipDir(fileLocation);
- boolean isXmlCsar = false;
- try {
- String tempfolder = unzipDir;
- ArrayList<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
- if (unzipFiles.isEmpty()) {
- isXmlCsar = true;
- }
- for (String unzipFile : unzipFiles) {
- if (unzipFile.endsWith(CommonConstant.CSAR_META)) {
- basicInfo = readCsarMeta(unzipFile);
- }
- if (ToolUtil.isYamlFile(new File(unzipFile))) {
- isXmlCsar = false;
- }
- }
- } catch (IOException e) {
- LOG.error("judge package type error !");
- }
- if (isXmlCsar) {
- basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
- } else {
- basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
- }
- return basicInfo;
- }
-
- /**
- * @param unzipFile
- * @return
- */
- private static PackageBasicInfo readCsarMeta(String unzipFile) {
- PackageBasicInfo basicInfo = new PackageBasicInfo();
- File file = new File(unzipFile);
- BufferedReader reader = null;
- try {
- reader = new BufferedReader(new FileReader(file));
- String tempString = null;
- while ((tempString = reader.readLine()) != null) {
- if (tempString.startsWith(CommonConstant.CSAR_TYPE_META)) {
- int count = tempString.indexOf(":") + 1;
- basicInfo.setType(EnumType.valueOf(tempString.substring(count)));
- }
- if (tempString.startsWith(CommonConstant.CSAR_PROVIDER_META)) {
- int count = tempString.indexOf(":") + 1;
- basicInfo.setProvider(tempString.substring(count));
- }
- if (tempString.startsWith(CommonConstant.CSAR_VERSION_META)) {
- int count = tempString.indexOf(":") + 1;
- basicInfo.setVersion(tempString.substring(count));
- }
- }
- reader.close();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e1) {
- }
- }
- }
- return basicInfo;
- }
-}
+/**
+ * Copyright 2016 [ZTE] and others.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openo.commontosca.catalog.wrapper;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+import org.openo.commontosca.catalog.common.CommonConstant;
+import org.openo.commontosca.catalog.common.FileUtil;
+import org.openo.commontosca.catalog.common.MsbAddrConfig;
+import org.openo.commontosca.catalog.common.ToolUtil;
+import org.openo.commontosca.catalog.db.entity.PackageData;
+import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
+import org.openo.commontosca.catalog.db.resource.PackageManager;
+import org.openo.commontosca.catalog.entity.CsarPackage;
+import org.openo.commontosca.catalog.entity.EnumOnboardState;
+import org.openo.commontosca.catalog.entity.EnumOperationalState;
+import org.openo.commontosca.catalog.entity.EnumProcessState;
+import org.openo.commontosca.catalog.entity.EnumType;
+import org.openo.commontosca.catalog.entity.EnumUsageState;
+import org.openo.commontosca.catalog.entity.request.PackageBasicInfo;
+import org.openo.commontosca.catalog.entity.response.PackageMeta;
+import org.openo.commontosca.catalog.ftp.Ftp;
+import org.openo.commontosca.catalog.ftp.FtpUtil;
+import org.openo.commontosca.catalog.model.entity.ServiceTemplate;
+import org.openo.commontosca.catalog.model.externalservice.entity.lifecycle.InstanceEntity;
+import org.openo.commontosca.catalog.model.externalservice.lifecycle.LifeCycleServiceConsumer;
+import org.openo.commontosca.catalog.model.parser.EnumPackageFormat;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+
+import javax.ws.rs.NotFoundException;
+
+public class PackageWrapperUtil {
+ private static final Logger LOG = LoggerFactory.getLogger(PackageWrapperUtil.class);
+
+
+ /**
+ * change json to object list.
+ * @param packageJson json
+ * @return package list
+ */
+ public static List<CsarPackage> formJson2Packages(String packageJson) {
+ List<CsarPackage> packageList =
+ new Gson().fromJson(packageJson, new TypeToken<List<CsarPackage>>() {}.getType());
+ if (null == packageList || packageList.size() == 0) {
+ throw new NotFoundException("Package do not exist");
+ }
+ return packageList;
+ }
+
+ public static long getPacakgeSize(String fileLocation) {
+ File file = new File(fileLocation);
+ return file.length();
+ }
+
+ /**
+ * change package metadata to fix database.
+ * @param meta package metadata
+ * @return package data in database
+ */
+ public static PackageData getPackageData(PackageMeta meta) {
+ PackageData packageData = new PackageData();
+ packageData.setCreateTime(meta.getCreateTime());
+ packageData.setDeletionPending(String.valueOf(meta.isDeletionPending()));
+ packageData.setDownloadUri(meta.getDownloadUri());
+ packageData.setFormat(meta.getFormat());
+ packageData.setModifyTime(meta.getModifyTime());
+ packageData.setName(meta.getName());
+ packageData.setCsarId(meta.getCsarId());
+ packageData.setOperationalState(meta.getOperationalState().toString());
+ packageData.setProvider(meta.getProvider());
+ String fileSize = meta.getSize();
+ packageData.setSize(fileSize);
+ packageData.setType(meta.getType());
+ packageData.setUsageState(meta.getUsageState().toString());
+ packageData.setVersion(meta.getVersion());
+ packageData.setOnBoardState(meta.getOnBoardState());
+ packageData.setProcessState(meta.getProcessState().toString());
+ return packageData;
+ }
+
+ /**
+ * judge wether is the end of upload package.
+ * @param contentRange package sise range
+ * @param csarName package name
+ * @return boolean
+ */
+ public static boolean isUploadEnd(String contentRange, String csarName) {
+ String range = contentRange;
+ range = range.replace("bytes", "").trim();
+ range = range.substring(0, range.indexOf("/"));
+ String size =
+ contentRange.substring(contentRange.indexOf("/") + 1, contentRange.length()).trim();
+ int fileSize = Integer.parseInt(size);
+ String[] ranges = range.split("-");
+ int startPosition = Integer.parseInt(ranges[0]);
+ if (startPosition == 0) {
+ // delPackageBySync(csarName);
+ }
+ // index start from 0
+ int endPosition = Integer.parseInt(ranges[1]) + 1;
+ if (endPosition >= fileSize) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * get package detail by package id.
+ * @param csarId package id
+ * @return package detail
+ */
+ public static ArrayList<PackageData> getPackageInfoById(String csarId) {
+ ArrayList<PackageData> result = new ArrayList<PackageData>();
+ try {
+ result = PackageManager.getInstance().queryPackageByCsarId(csarId);
+ } catch (CatalogResourceException e1) {
+ LOG.error("query package by csarId from db error ! " + e1.getMessage());
+ }
+ return result;
+ }
+
+ /**
+ * get package metadata from basic info.
+ * @param fileName package name
+ * @param fileLocation the location of package
+ * @param basic basic infomation of package. include version, type and provider
+ * @return package metadata
+ */
+ public static PackageMeta getPackageMeta(String fileName, String fileLocation,
+ PackageBasicInfo basic) {
+ PackageMeta packageMeta = new PackageMeta();
+ long size = getPacakgeSize(fileLocation);
+ packageMeta.setFormat(basic.getFormat());
+ String packageId = ToolUtil.generateId();
+ packageMeta.setName(fileName.replace(CommonConstant.CSAR_SUFFIX, ""));
+ packageMeta.setCsarId(packageId);
+ packageMeta.setType(basic.getType().toString());
+ packageMeta.setVersion(basic.getVersion());
+ packageMeta.setProvider(basic.getProvider());
+ packageMeta.setDeletionPending(false);
+ String sizeStr = ToolUtil.getFormatFileSize(size);
+ packageMeta.setSize(sizeStr);
+ SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ String currentTime = sdf1.format(new Date());
+ packageMeta.setCreateTime(currentTime);
+ packageMeta.setModifyTime(currentTime);
+ packageMeta.setOperationalState(EnumOperationalState.Disabled);
+ packageMeta.setUsageState(EnumUsageState.NotInUse);
+ packageMeta.setOnBoardState(EnumOnboardState.nonOnBoarded.getValue());
+ packageMeta.setProcessState(EnumProcessState.normal);
+ return packageMeta;
+ }
+
+ /**
+ * get downloadUri from package metadata.
+ * @param csarId package id
+ * @return download uri
+ */
+ public static String getPackagePath(String csarId) {
+ ArrayList<PackageData> packageList = new ArrayList<PackageData>();
+ String downloadUri = null;
+ try {
+ packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
+ downloadUri = packageList.get(0).getDownloadUri();
+ } catch (CatalogResourceException e1) {
+ LOG.error("Query CSAR package by ID failed ! csarId = " + csarId);
+ }
+ return downloadUri;
+ }
+
+
+ /**
+ * convert instance to hashset.
+ * @param instancelist instance list
+ * @return HashSet
+ */
+ public static HashSet<String> instanceConvertToHashSet(ArrayList<InstanceEntity> instancelist) {
+ HashSet<String> result = new HashSet<String>();
+ if (instancelist != null) {
+ for (InstanceEntity instance : instancelist) {
+ result.add(instance.getServiceTemplateId());
+ }
+ }
+ return result;
+ }
+
+ /**
+ * get ftp detail information.
+ * @param ftpUrl ftp url
+ * @return ftp detail
+ */
+ public static Ftp getFtpDetail(String ftpUrl) {
+ Ftp ftp = new Ftp();
+ int index1 = ftpUrl.indexOf("ftp://");
+ int index2 = ftpUrl.indexOf("@");
+ String userPassSubString = ftpUrl.substring(index1, index2);
+ int index3 = userPassSubString.indexOf(":");
+ String userName = userPassSubString.substring(0, index3);
+ String pass = userPassSubString.substring(index3 + 1);
+ String subString1 = ftpUrl.substring(index2 + 1);
+ int index4 = subString1.indexOf("/");
+ String ipPortSubString = subString1.substring(0, index4);
+ int index5 = ipPortSubString.indexOf(":");
+ String ip = ipPortSubString.substring(0, index5);
+ String port = ipPortSubString.substring(index5 + 1);
+ int index6 = ftpUrl.lastIndexOf("/");
+ String path = ftpUrl.substring(0, index6);
+ ftp.setIpAddr(ip);
+ ftp.setPath(path);
+ ftp.setPort(Integer.valueOf(port));
+ ftp.setPwd(pass);
+ ftp.setUserName(userName);
+ return ftp;
+ }
+
+ /**
+ * get package name from ftpUrl.
+ * @param ftpUrl ftp url
+ * @return package name
+ */
+ public static String getPackageName(String ftpUrl) {
+ int index = ftpUrl.lastIndexOf("/");
+ String packageName = ftpUrl.substring(index);
+ return packageName;
+ }
+
+ /**
+ * download package from ftp.
+ * @param ftpUrl ftp url
+ * @param tempDirName temp directory
+ */
+ public static void downPackageFromFtp(String ftpUrl, String tempDirName) {
+ Ftp ftp = new Ftp();
+ ftp = PackageWrapperUtil.getFtpDetail(ftpUrl);
+ String remoteBaseDir = ftp.getPath();
+ try {
+ FtpUtil.startDown(ftp, tempDirName, remoteBaseDir);
+ } catch (Exception e1) {
+ LOG.error("Down package from ftp failed !");
+ }
+ }
+
+ /**
+ * translate package data from database to package metadata.
+ * @param dbResult data from database
+ * @return package metadata list
+ */
+ public static ArrayList<PackageMeta> packageDataList2PackageMetaList(
+ ArrayList<PackageData> dbResult) {
+ ArrayList<PackageMeta> metas = new ArrayList<PackageMeta>();
+ PackageMeta meta = new PackageMeta();
+ for (int i = 0; i < dbResult.size(); i++) {
+ PackageData data = dbResult.get(i);
+ meta = packageData2PackageMeta(data);
+ metas.add(meta);
+ }
+ return metas;
+ }
+
+ /**
+ * get onboarded enum value.
+ * @param value onboard value
+ * @return enum
+ */
+ public static EnumOnboardState getEnumByValue(String value) {
+ if (value == "non-onBoarded") {
+ return EnumOnboardState.nonOnBoarded;
+ } else {
+ return EnumOnboardState.onBoarded;
+ }
+ }
+
+ private static PackageMeta packageData2PackageMeta(PackageData packageData) {
+ PackageMeta meta = new PackageMeta();
+ meta.setCsarId(packageData.getCsarId());
+ meta.setCreateTime(packageData.getCreateTime());
+ meta.setDeletionPending(Boolean.getBoolean(packageData.getDeletionPending()));
+ String packageUri =
+ packageData.getDownloadUri() + packageData.getName() + CommonConstant.CSAR_SUFFIX;
+ String packageUrl = getUrl(packageUri);
+ meta.setDownloadUri(packageUrl);
+ meta.setFormat(packageData.getFormat());
+ meta.setModifyTime(packageData.getModifyTime());
+ meta.setName(packageData.getName());
+ meta.setOperationalState(EnumOperationalState.valueOf(packageData.getOperationalState()));
+ meta.setProvider(packageData.getProvider());
+ meta.setSize(packageData.getSize());
+ meta.setType(packageData.getType());
+ meta.setUsageState(EnumUsageState.valueOf(packageData.getUsageState()));
+ meta.setVersion(packageData.getVersion());
+ meta.setOnBoardState(packageData.getOnBoardState());
+ meta.setProcessState(EnumProcessState.valueOf(packageData.getProcessState()));
+ return meta;
+ }
+
+ /**
+ * add msb address as prefix to uri.
+ * @param uri uri
+ * @return url
+ */
+ public static String getUrl(String uri) {
+ String url = null;
+ if ((MsbAddrConfig.getMsbAddress().endsWith("/")) && uri.startsWith("/")) {
+ url = MsbAddrConfig.getMsbAddress() + uri.substring(1);
+ }
+ url = MsbAddrConfig.getMsbAddress() + uri;
+ String urlresult = url.replace("\\", "/");
+ return urlresult;
+ }
+
+ /**
+ * get local path.
+ * @param uri uri
+ * @return local path
+ */
+ public static String getLocalPath(String uri) {
+ File srcDir = new File(uri);
+ String localPath = srcDir.getAbsolutePath();
+ return localPath.replace("\\", "/");
+ }
+
+ /**
+ * get package basic information.
+ * @param fileLocation package location
+ * @return package basic information
+ */
+ public static PackageBasicInfo getPacageBasicInfo(String fileLocation) {
+ PackageBasicInfo basicInfo = new PackageBasicInfo();
+ String unzipDir = ToolUtil.getUnzipDir(fileLocation);
+ boolean isXmlCsar = false;
+ try {
+ String tempfolder = unzipDir;
+ ArrayList<String> unzipFiles = FileUtil.unzip(fileLocation, tempfolder);
+ if (unzipFiles.isEmpty()) {
+ isXmlCsar = true;
+ }
+ for (String unzipFile : unzipFiles) {
+ if (unzipFile.endsWith(CommonConstant.CSAR_META)) {
+ basicInfo = readCsarMeta(unzipFile);
+ }
+ if (ToolUtil.isYamlFile(new File(unzipFile))) {
+ isXmlCsar = false;
+ }
+ }
+ } catch (IOException e1) {
+ LOG.error("judge package type error !");
+ }
+ if (isXmlCsar) {
+ basicInfo.setFormat(CommonConstant.PACKAGE_XML_FORMAT);
+ } else {
+ basicInfo.setFormat(CommonConstant.PACKAGE_YAML_FORMAT);
+ }
+ return basicInfo;
+ }
+
+ private static PackageBasicInfo readCsarMeta(String unzipFile) {
+ PackageBasicInfo basicInfo = new PackageBasicInfo();
+ File file = new File(unzipFile);
+ BufferedReader reader = null;
+ try {
+ reader = new BufferedReader(new FileReader(file));
+ String tempString = null;
+ while ((tempString = reader.readLine()) != null) {
+ if (tempString.startsWith(CommonConstant.CSAR_TYPE_META)) {
+ int count = tempString.indexOf(":") + 1;
+ basicInfo.setType(EnumType.valueOf(tempString.substring(count)));
+ }
+ if (tempString.startsWith(CommonConstant.CSAR_PROVIDER_META)) {
+ int count = tempString.indexOf(":") + 1;
+ basicInfo.setProvider(tempString.substring(count));
+ }
+ if (tempString.startsWith(CommonConstant.CSAR_VERSION_META)) {
+ int count = tempString.indexOf(":") + 1;
+ basicInfo.setVersion(tempString.substring(count));
+ }
+ }
+ reader.close();
+ } catch (IOException e2) {
+ e2.printStackTrace();
+ } finally {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException e1) {
+ LOG.error("close reader failed ! " + e1.getMessage());
+ }
+ }
+ }
+ return basicInfo;
+ }
+
+ /**
+ * get package format enum.
+ * @param format package format
+ * @return package format enum
+ */
+ public static EnumPackageFormat getPackageFormat(String format) {
+ if (format.equals("xml")) {
+ return EnumPackageFormat.TOSCA_XML;
+ } else if (format.equals("yml") || format.equals("yaml")) {
+ return EnumPackageFormat.TOSCA_YAML;
+ } else {
+ return null;
+ }
+ }
+}