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 org.glassfish.jersey.media.multipart.FormDataContentDisposition;
20 import org.openo.commontosca.catalog.common.CommonConstant;
21 import org.openo.commontosca.catalog.common.HttpServerPathConfig;
22 import org.openo.commontosca.catalog.common.RestUtil;
23 import org.openo.commontosca.catalog.common.ToolUtil;
24 import org.openo.commontosca.catalog.db.entity.PackageData;
25 import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
26 import org.openo.commontosca.catalog.db.resource.PackageManager;
27 import org.openo.commontosca.catalog.db.resource.TemplateManager;
28 import org.openo.commontosca.catalog.entity.request.PackageBasicInfo;
29 import org.openo.commontosca.catalog.entity.response.CsarFileUriResponse;
30 import org.openo.commontosca.catalog.entity.response.PackageMeta;
31 import org.openo.commontosca.catalog.entity.response.UploadPackageResponse;
32 import org.openo.commontosca.catalog.filemanage.FileManagerFactory;
33 import org.openo.commontosca.catalog.model.parser.ModelParserFactory;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
37 import java.io.BufferedInputStream;
39 import java.io.FileInputStream;
40 import java.io.InputStream;
41 import java.text.SimpleDateFormat;
42 import java.util.ArrayList;
43 import java.util.Date;
45 import javax.ws.rs.core.HttpHeaders;
46 import javax.ws.rs.core.Response;
47 import javax.ws.rs.core.Response.Status;
49 public class PackageWrapper {
50 private static PackageWrapper packageWrapper;
51 private static final Logger LOG = LoggerFactory.getLogger(PackageWrapper.class);
54 * get PackageWrapper instance.
55 * @return package wrapper instance
57 public static PackageWrapper getInstance() {
58 if (packageWrapper == null) {
59 packageWrapper = new PackageWrapper();
61 return packageWrapper;
65 * query package by id.
66 * @param csarId package id
69 public Response queryPackageById(String csarId) {
70 ArrayList<PackageData> dbResult = new ArrayList<PackageData>();
71 ArrayList<PackageMeta> result = new ArrayList<PackageMeta>();
72 dbResult = PackageWrapperUtil.getPackageInfoById(csarId);
73 result = PackageWrapperUtil.packageDataList2PackageMetaList(dbResult);
74 return Response.ok(result).build();
79 * @param uploadedInputStream inputStream
80 * @param fileDetail package detail
81 * @param head http header
85 public Response uploadPackage(InputStream uploadedInputStream,
86 FormDataContentDisposition fileDetail, HttpHeaders head) throws Exception {
88 if (uploadedInputStream == null) {
89 LOG.info("the uploadStream is null");
90 return Response.serverError().build();
92 if (fileDetail == null) {
93 LOG.info("the fileDetail is null");
94 return Response.serverError().build();
96 LOG.info("the fileDetail = " + ToolUtil.objectToString(fileDetail));
97 String contentRange = null;
99 fileName = ToolUtil.processFileName(fileDetail.getFileName());
100 String tempDirName = null;
101 tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName);
103 contentRange = head.getHeaderString(CommonConstant.HTTP_HEADER_CONTENT_RANGE);
105 LOG.info("store package chunk file, fileName:" + fileName + ",contentRange:" + contentRange);
106 if (ToolUtil.isEmptyString(contentRange)) {
107 fileSize = uploadedInputStream.available();
108 contentRange = "0-" + fileSize + "/" + fileSize;
110 String fileLocation =
111 ToolUtil.storeChunkFileInLocal(tempDirName, fileName, uploadedInputStream);
112 LOG.info("the fileLocation when upload package is :" + fileLocation);
113 uploadedInputStream.close();
115 PackageBasicInfo basicInfo = new PackageBasicInfo();
116 basicInfo = PackageWrapperUtil.getPacageBasicInfo(fileLocation);
117 String path = basicInfo.getType().toString() + File.separator + basicInfo.getProvider()
118 + File.separator + fileName.replace(".csar", "") + File.separator + basicInfo.getVersion();
119 LOG.info("dest path is : " + path);
120 PackageMeta packageMeta = new PackageMeta();
121 packageMeta = PackageWrapperUtil.getPackageMeta(fileName, fileLocation, basicInfo);
122 String dowloadUri = File.separator + path + File.separator;
123 String destPath = File.separator + path;
124 packageMeta.setDownloadUri(dowloadUri);
125 LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta));
126 Boolean isEnd = PackageWrapperUtil.isUploadEnd(contentRange, fileName);
127 PackageData packateDbData = new PackageData();
129 String serviceTemplateId = null;
130 boolean uploadResult = FileManagerFactory.createFileManager().upload(tempDirName, destPath);
131 if (uploadResult == true) {
132 PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta);
133 packateDbData = PackageManager.getInstance().addPackage(packageData);
134 LOG.info("Store package data to database succed ! packateDbData = "
135 + ToolUtil.objectToString(packateDbData));
137 String tempCsarPath = tempDirName + File.separator + fileName;
138 serviceTemplateId = ModelParserFactory.getInstance().parse(packateDbData.getCsarId(),
139 tempCsarPath, PackageWrapperUtil.getPackageFormat(packateDbData.getFormat()));
140 LOG.info("Package parse success ! serviceTemplateId = " + serviceTemplateId);
141 } catch (Exception e1) {
142 LOG.error("Parse package error ! ");
143 PackageManager.getInstance().deletePackage(packateDbData.getCsarId());
144 throw new Exception(e1);
147 if (null != packateDbData && null == serviceTemplateId) {
148 LOG.info("Service template Id is null !");
149 PackageManager.getInstance().deletePackage(packateDbData.getCsarId());
152 LOG.info("upload package file end, fileName:" + fileName);
154 UploadPackageResponse result = new UploadPackageResponse();
155 result.setCsarId(packateDbData.getCsarId());
156 if (tempDirName != null) {
157 ToolUtil.deleteDir(new File(tempDirName));
159 return Response.ok(result).build();
163 * delete package by package id.
164 * @param csarId package id
167 public Response delPackage(String csarId) {
168 LOG.info("delete package info.csarId:" + csarId);
169 if (ToolUtil.isEmptyString(csarId)) {
170 LOG.error("delete package fail, csarid is null");
171 return Response.serverError().build();
174 DelCsarThread thread = new DelCsarThread(csarId, false);
175 new Thread(thread).start();
176 return Response.noContent().build();
177 } catch (Exception e1) {
178 LOG.error("delete fail.", e1);
179 return RestUtil.getRestException(e1.getMessage());
183 // public Response delPackageByServiceTemplateId(String serviceTemplateId) {
184 // LOG.info("delete package info.serviceTemplateId:" + serviceTemplateId);
185 // if (ToolUtil.isEmptyString(serviceTemplateId)) {
186 // LOG.error("delete package fail, serviceTemplateId is null");
187 // return Response.serverError().build();
189 // ArrayList<PackageData> result = new ArrayList<PackageData>();
191 // result = PackageManager.getInstance().queryPackageByServiceTemplateId(serviceTemplateId);
193 // } catch (CatalogResourceException e) {
194 // LOG.error("query package by csarId from db error ! " + e.getMessage());
195 // return RestUtil.getRestException(e.getMessage());
197 // if (result.size() <= 0) {
198 // LOG.warn("not exist package by serviceTemplateId");
199 // return Response.status(Status.NOT_FOUND).build();
201 // if ("true".equals(result.get(0).getDeletionPending())) {
202 // LOG.info("start delete package.csarId:" + result.get(0).getCsarId());
203 // delCsarThread thread = new delCsarThread(result.get(0).getCsarId(), true);
204 // new Thread(thread).start();
206 // return Response.noContent().build();
209 class DelCsarThread implements Runnable {
210 private String csarid;
211 private boolean isInstanceTemplate = false;
213 public DelCsarThread(String csarid, boolean isInstanceTemplate) {
214 this.csarid = csarid;
215 this.isInstanceTemplate = isInstanceTemplate;
221 if (!ToolUtil.isEmptyString(csarid)) {
224 } catch (Exception e1) {
225 LOG.error("del instance csar fail.", e1);
226 updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETE_FAIL,
228 // publishDelFinishCometdMessage(csarid, "false");
232 private void delCsarData(String csarId) {
233 updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETING, null);
234 String packagePath = PackageWrapperUtil.getPackagePath(csarId);
235 if (packagePath == null) {
236 LOG.error("package path is null! ");
239 FileManagerFactory.createFileManager().delete(packagePath);
241 PackageManager.getInstance().deletePackage(csarId);
242 } catch (CatalogResourceException e1) {
243 LOG.error("delete package by csarId from db error ! " + e1.getMessage());
245 // delete template data from db
246 PackageData packageData = new PackageData();
247 packageData.setCsarId(csarId);
249 TemplateManager.getInstance().deleteServiceTemplateByCsarPackageInfo(packageData);
250 } catch (CatalogResourceException e2) {
251 LOG.error("delete template data from db error! csarId = " + csarId);
253 // publishDelFinishCometdMessage(csarid, "true");
256 // private void publishDelFinishCometdMessage(String csarid, String csarDelStatus) {
257 // if (isInstanceTemplate) {
258 // LOG.info("delete instance Template finish. csarid:{}", csarid);
262 // Map<String, Object> cometdMessage = new HashMap<String, Object>();
263 // cometdMessage.put("csarid", csarid);
264 // cometdMessage.put("status", csarDelStatus);
265 // CometdService.getInstance().publish(CommonConstant.COMETD_CHANNEL_PACKAGE_DELETE,
267 // } catch (CometdException e) {
268 // LOG.error("publish delfinish cometdmsg fail.", e);
274 * update package status.
275 * @param csarId package id
276 * @param operationalState package operational state
277 * @param usageState package usage state
278 * @param onBoardState package onboard state
279 * @param processState package process state
280 * @param deletionPending package deletionPending status
283 public Response updatePackageStatus(String csarId, String operationalState, String usageState,
284 String onBoardState, String processState, String deletionPending) {
285 LOG.info("update package status info.csarId:" + csarId + " operationalState:"
287 if (ToolUtil.isEmptyString(csarId)) {
288 LOG.error("update csar status fail, csarid is null");
289 return Response.serverError().build();
292 // UpdatePackageResponse result = new UpdatePackageResponse();
293 PackageData packageInfo = new PackageData();
294 if (operationalState != null) {
295 packageInfo.setOperationalState(operationalState);
297 if (usageState != null) {
298 packageInfo.setUsageState(usageState);
300 if (onBoardState != null) {
301 packageInfo.setOnBoardState(onBoardState);
303 if (processState != null) {
304 packageInfo.setProcessState(processState);
306 if (deletionPending != null) {
307 packageInfo.setDeletionPending(deletionPending);
309 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
310 String currentTime = sdf1.format(new Date());
311 packageInfo.setModifyTime(currentTime);
312 PackageManager.getInstance().updatePackage(packageInfo, csarId);
313 // ArrayList<PackageData> pacackgeList = PackageWrapperUtil.getPackageInfoById(csarId);
314 // String finalUsageState = pacackgeList.get(0).getUsageState();
315 // result.setUsageState(finalUsageState);
316 return Response.ok().build();
317 } catch (CatalogResourceException e1) {
318 LOG.error("update package status by csarId from db error ! " + e1.getMessage());
319 return RestUtil.getRestException(e1.getMessage());
324 * download package by package id.
325 * @param csarId package id
328 public Response downloadCsarPackagesById(String csarId) {
329 ArrayList<PackageData> packageList = PackageWrapperUtil.getPackageInfoById(csarId);
330 String packageName = null;
331 if (null != packageList && packageList.size() > 0) {
332 packageName = packageList.get(0).getName();
334 String path = ToolUtil.getCatalogueCsarPath() + File.separator + packageName;
335 File csarFile = new File(path);
336 if (!csarFile.exists()) {
337 return Response.status(Status.NOT_FOUND).build();
341 InputStream fis = new BufferedInputStream(new FileInputStream(path));
342 return Response.ok(fis)
343 .header("Content-Disposition", "attachment; filename=\"" + csarFile.getName() + "\"")
345 } catch (Exception e1) {
346 LOG.error("download vnf package fail.", e1);
347 return RestUtil.getRestException(e1.getMessage());
352 * query package list by condition.
353 * @param name package name
354 * @param provider package provider
355 * @param version package version
356 * @param deletionPending package deletionPending
357 * @param type package type
360 public Response queryPackageListByCond(String name, String provider, String version,
361 String deletionPending, String type) {
362 ArrayList<PackageData> dbresult = new ArrayList<PackageData>();
363 ArrayList<PackageMeta> result = new ArrayList<PackageMeta>();
364 LOG.info("query package info.name:" + name + " provider:" + provider + " version" + version
365 + " deletionPending" + deletionPending + " type:" + type);
368 PackageManager.getInstance().queryPackage(name, provider, version, deletionPending, type);
369 result = PackageWrapperUtil.packageDataList2PackageMetaList(dbresult);
370 return Response.ok(result).build();
371 } catch (CatalogResourceException e1) {
372 LOG.error("query package by csarId from db error ! " + e1.getMessage());
373 return RestUtil.getRestException(e1.getMessage());
378 * get package file uri.
379 * @param csarId package id
380 * @param relativePath file relative path
383 public Response getCsarFileUri(String csarId, String relativePath) {
385 CsarFileUriResponse result = getCsarFileDownloadUri(csarId, relativePath);
386 return Response.ok(result).build();
387 } catch (CatalogResourceException e1) {
388 LOG.error("Query CSAR package by ID failed ! csarId = " + csarId);
391 return Response.serverError().build();
395 * get package file download uri.
396 * @param csarId package id
397 * @param relativePath package file relative path
398 * @return CsarFileUriResponse
399 * @throws CatalogResourceException e
401 public CsarFileUriResponse getCsarFileDownloadUri(String csarId, String relativePath)
402 throws CatalogResourceException {
403 CsarFileUriResponse result = new CsarFileUriResponse();
404 String downloadUrl = null;
405 String downloadUri = null;
406 String localPath = null;
407 ArrayList<PackageData> packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
408 if (packageList != null && packageList.size() != 0) {
409 String packageName = packageList.get(0).getName();
410 String relativeUri = packageList.get(0).getDownloadUri() + packageName;
411 downloadUri = relativeUri + relativePath;
412 downloadUrl = PackageWrapperUtil.getUrl(downloadUri);
413 String httpUri = HttpServerPathConfig.getHttpServerPath() + downloadUri;
414 localPath = PackageWrapperUtil.getLocalPath(httpUri);
416 result.setDownloadUri(downloadUrl);
417 result.setLocalPath(localPath);