Fix bugs TOSCA-123 GSO-33
[vfc/nfvo/catalog.git] / catalog-core / catalog-mgr / src / main / java / org / openo / commontosca / catalog / wrapper / PackageWrapper.java
1 /**
2  * Copyright 2016 ZTE Corporation.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 package org.openo.commontosca.catalog.wrapper;
17
18 import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
19 import org.openo.commontosca.catalog.common.CommonConstant;
20 import org.openo.commontosca.catalog.common.HttpServerPathConfig;
21 import org.openo.commontosca.catalog.common.RestUtil;
22 import org.openo.commontosca.catalog.common.ToolUtil;
23 import org.openo.commontosca.catalog.db.entity.PackageData;
24 import org.openo.commontosca.catalog.db.exception.CatalogResourceException;
25 import org.openo.commontosca.catalog.db.resource.PackageManager;
26 import org.openo.commontosca.catalog.db.resource.TemplateManager;
27 import org.openo.commontosca.catalog.entity.request.PackageBasicInfo;
28 import org.openo.commontosca.catalog.entity.response.CsarFileUriResponse;
29 import org.openo.commontosca.catalog.entity.response.PackageMeta;
30 import org.openo.commontosca.catalog.entity.response.UploadPackageResponse;
31 import org.openo.commontosca.catalog.filemanage.FileManagerFactory;
32 import org.openo.commontosca.catalog.model.parser.ModelParserFactory;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import java.io.BufferedInputStream;
37 import java.io.File;
38 import java.io.FileInputStream;
39 import java.io.InputStream;
40 import java.text.SimpleDateFormat;
41 import java.util.ArrayList;
42 import java.util.Date;
43
44 import javax.ws.rs.core.HttpHeaders;
45 import javax.ws.rs.core.Response;
46 import javax.ws.rs.core.Response.Status;
47
48 public class PackageWrapper {
49   private static PackageWrapper packageWrapper;
50   private static final Logger LOG = LoggerFactory.getLogger(PackageWrapper.class);
51
52   /**
53    * get PackageWrapper instance.
54    * @return package wrapper instance
55    */
56   public static PackageWrapper getInstance() {
57     if (packageWrapper == null) {
58       packageWrapper = new PackageWrapper();
59     }
60     return packageWrapper;
61   }
62
63   /**
64    * query package by id.
65    * @param csarId package id
66    * @return Response
67    */
68   public Response queryPackageById(String csarId) {
69     PackageData dbResult = new PackageData();
70     PackageMeta result = new PackageMeta();
71     dbResult = PackageWrapperUtil.getPackageInfoById(csarId);
72     result = PackageWrapperUtil.packageData2PackageMeta(dbResult);
73     return Response.ok(result).build();
74   }
75
76   /**
77    * upload package.
78    * @param uploadedInputStream inputStream
79    * @param fileDetail package detail
80    * @param head http header
81    * @return Response
82    * @throws Exception e
83    */
84   public Response uploadPackage(InputStream uploadedInputStream,
85       FormDataContentDisposition fileDetail, HttpHeaders head) throws Exception {
86     int fileSize = 0;
87     if (uploadedInputStream == null) {
88       LOG.info("the uploadStream is null");
89       return Response.serverError().build();
90     }
91     if (fileDetail == null) {
92       LOG.info("the fileDetail is null");
93       return Response.serverError().build();
94     }
95     LOG.info("the fileDetail = " + ToolUtil.objectToString(fileDetail));
96     String contentRange = null;
97     String fileName = "";
98     fileName = ToolUtil.processFileName(fileDetail.getFileName());
99     String tempDirName = null;
100     tempDirName = ToolUtil.getTempDir(CommonConstant.CATALOG_CSAR_DIR_NAME, fileName);
101     if (head != null) {
102       contentRange = head.getHeaderString(CommonConstant.HTTP_HEADER_CONTENT_RANGE);
103     }
104     LOG.info("store package chunk file, fileName:" + fileName + ",contentRange:" + contentRange);
105     if (ToolUtil.isEmptyString(contentRange)) {
106       fileSize = uploadedInputStream.available();
107       contentRange = "0-" + fileSize + "/" + fileSize;
108     }
109     String fileLocation =
110         ToolUtil.storeChunkFileInLocal(tempDirName, fileName, uploadedInputStream);
111     LOG.info("the fileLocation when upload package is :" + fileLocation);
112     uploadedInputStream.close();
113
114     PackageBasicInfo basicInfo = new PackageBasicInfo();
115     basicInfo = PackageWrapperUtil.getPacageBasicInfo(fileLocation);
116     String path = basicInfo.getType().toString() + File.separator + basicInfo.getProvider()
117         + File.separator + fileName.replace(".csar", "") + File.separator + basicInfo.getVersion();
118     LOG.info("dest path is : " + path);
119     PackageMeta packageMeta = new PackageMeta();
120     packageMeta = PackageWrapperUtil.getPackageMeta(fileName, fileLocation, basicInfo);
121     String dowloadUri = File.separator + path + File.separator;
122     String destPath = File.separator + path;
123     packageMeta.setDownloadUri(dowloadUri);
124     LOG.info("packageMeta = " + ToolUtil.objectToString(packageMeta));
125     Boolean isEnd = PackageWrapperUtil.isUploadEnd(contentRange, fileName);
126     PackageData packateDbData = new PackageData();
127     if (isEnd) {
128       String serviceTemplateId = null;
129       boolean uploadResult = FileManagerFactory.createFileManager().upload(tempDirName, destPath);
130       if (uploadResult == true) {
131         PackageData packageData = PackageWrapperUtil.getPackageData(packageMeta);
132         ArrayList<PackageData> existPackageDatas =
133             PackageManager.getInstance().queryPackage(packageData.getName(),
134                 packageData.getProvider(), packageData.getVersion(), null, packageData.getType());
135         if (null != existPackageDatas && existPackageDatas.size() > 0) {
136           LOG.warn("The package already exist ! Begin to delete the orgin data and reupload !");
137           for (int i = 0; i < existPackageDatas.size(); i++) {
138             this.delPackage(existPackageDatas.get(i).getCsarId());
139           }
140         } 
141         packateDbData = PackageManager.getInstance().addPackage(packageData);
142         LOG.info("Store package data to database succed ! packateDbData = "
143             + ToolUtil.objectToString(packateDbData));
144         try {
145           String tempCsarPath = tempDirName + File.separator + fileName;
146           serviceTemplateId = ModelParserFactory.getInstance().parse(packateDbData.getCsarId(),
147               tempCsarPath, PackageWrapperUtil.getPackageFormat(packateDbData.getFormat()));
148           LOG.info("Package parse success ! serviceTemplateId = " + serviceTemplateId);
149         } catch (Exception e1) {
150           LOG.error("Parse package error ! ");
151           PackageManager.getInstance().deletePackage(packateDbData.getCsarId());
152           throw new Exception(e1);
153         }
154
155         if (null != packateDbData && null == serviceTemplateId) {
156           LOG.info("Service template Id is null !");
157           PackageManager.getInstance().deletePackage(packateDbData.getCsarId());
158         }
159       }
160       LOG.info("upload package file end, fileName:" + fileName);
161     }
162     UploadPackageResponse result = new UploadPackageResponse();
163     result.setCsarId(packateDbData.getCsarId());
164     if (tempDirName != null) {
165       ToolUtil.deleteDir(new File(tempDirName));
166     }
167     return Response.ok(result).build();
168   }
169
170   /**
171    * delete package by package id.
172    * @param csarId package id
173    * @return Response
174    */
175   public Response delPackage(String csarId) {
176     LOG.info("delete package  info.csarId:" + csarId);
177     if (ToolUtil.isEmptyString(csarId)) {
178       LOG.error("delete package  fail, csarid is null");
179       return Response.serverError().build();
180     }
181     try {
182       DelCsarThread thread = new DelCsarThread(csarId, false);
183       new Thread(thread).start();
184       return Response.noContent().build();
185     } catch (Exception e1) {
186       LOG.error("delete fail." + e1.getMessage());
187       return RestUtil.getRestException(e1.getMessage());
188     }
189   }
190
191   class DelCsarThread implements Runnable {
192     private String csarid;
193     private boolean isInstanceTemplate = false;
194
195     public DelCsarThread(String csarid, boolean isInstanceTemplate) {
196       this.csarid = csarid;
197       this.isInstanceTemplate = isInstanceTemplate;
198     }
199
200     @Override
201     public void run() {
202       try {
203         if (!ToolUtil.isEmptyString(csarid)) {
204           delCsarData(csarid);
205         }
206       } catch (Exception e1) {
207         LOG.error("del instance csar fail."+ e1.getMessage());
208         updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETE_FAIL,
209             null);
210         // publishDelFinishCometdMessage(csarid, "false");
211       }
212     }
213
214     private void delCsarData(String csarId) {
215       updatePackageStatus(csarid, null, null, null, CommonConstant.PACKAGE_STATUS_DELETING, null);
216       String packagePath = PackageWrapperUtil.getPackagePath(csarId);
217       if (packagePath == null) {
218         LOG.error("package path is null! ");
219         return;
220       }
221       FileManagerFactory.createFileManager().delete(packagePath);
222       // delete template data from db
223       PackageData packageData = new PackageData();
224       packageData.setCsarId(csarId);
225       try {
226         TemplateManager.getInstance().deleteServiceTemplateByCsarPackageInfo(packageData);
227       } catch (CatalogResourceException e2) {
228         LOG.error("delete template data from db error! csarId = " + csarId);
229       }
230       //delete package data from database
231       try {
232         PackageManager.getInstance().deletePackage(csarId);
233       } catch (CatalogResourceException e1) {
234         LOG.error("delete package  by csarId from db error ! " + e1.getMessage());
235       }
236     }
237
238     // private void publishDelFinishCometdMessage(String csarid, String csarDelStatus) {
239     // if (isInstanceTemplate) {
240     // LOG.info("delete instance Template finish. csarid:{}", csarid);
241     // return;
242     // }
243     // try {
244     // Map<String, Object> cometdMessage = new HashMap<String, Object>();
245     // cometdMessage.put("csarid", csarid);
246     // cometdMessage.put("status", csarDelStatus);
247     // CometdService.getInstance().publish(CommonConstant.COMETD_CHANNEL_PACKAGE_DELETE,
248     // cometdMessage);
249     // } catch (CometdException e) {
250     // LOG.error("publish delfinish cometdmsg fail.", e);
251     // }
252     // }
253   }
254
255   /**
256    * update package status.
257    * @param csarId package id
258    * @param operationalState package operational state
259    * @param usageState package usage state
260    * @param onBoardState package onboard state
261    * @param processState package process state
262    * @param deletionPending package deletionPending status
263    * @return Response
264    */
265   public Response updatePackageStatus(String csarId, String operationalState, String usageState,
266       String onBoardState, String processState, String deletionPending) {
267     LOG.info("update package status info.csarId:" + csarId + " operationalState:"
268         + operationalState);
269     if (ToolUtil.isEmptyString(csarId)) {
270       LOG.error("update csar status fail, csarid is null");
271       return Response.serverError().build();
272     }
273     try {
274       // UpdatePackageResponse result = new UpdatePackageResponse();
275       PackageData packageInfo = new PackageData();
276       if (operationalState != null) {
277         packageInfo.setOperationalState(operationalState);
278       }
279       if (usageState != null) {
280         packageInfo.setUsageState(usageState);
281       }
282       if (onBoardState != null) {
283         packageInfo.setOnBoardState(onBoardState);
284       }
285       if (processState != null) {
286         packageInfo.setProcessState(processState);
287       }
288       if (deletionPending != null) {
289         packageInfo.setDeletionPending(deletionPending);
290       }
291       SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
292       String currentTime = sdf1.format(new Date());
293       packageInfo.setModifyTime(currentTime);
294       PackageManager.getInstance().updatePackage(packageInfo, csarId);
295       // ArrayList<PackageData> pacackgeList = PackageWrapperUtil.getPackageInfoById(csarId);
296       // String finalUsageState = pacackgeList.get(0).getUsageState();
297       // result.setUsageState(finalUsageState);
298       return Response.ok().build();
299     } catch (CatalogResourceException e1) {
300       LOG.error("update package status by csarId from db error ! " + e1.getMessage());
301       return RestUtil.getRestException(e1.getMessage());
302     }
303   }
304
305   /**
306    * download package by package id.
307    * @param csarId package id
308    * @return Response
309    */
310   public Response downloadCsarPackagesById(String csarId) {
311     PackageData packageData = PackageWrapperUtil.getPackageInfoById(csarId);
312     String packageName = null;
313     packageName = packageData.getName();
314     String path = ToolUtil.getCatalogueCsarPath() + File.separator + packageName;
315     File csarFile = new File(path);
316     if (!csarFile.exists()) {
317       return Response.status(Status.NOT_FOUND).build();
318     }
319
320     try {
321       InputStream fis = new BufferedInputStream(new FileInputStream(path));
322       return Response.ok(fis)
323           .header("Content-Disposition", "attachment; filename=\"" + csarFile.getName() + "\"")
324           .build();
325     } catch (Exception e1) {
326       LOG.error("download vnf package fail.", e1);
327       return RestUtil.getRestException(e1.getMessage());
328     }
329   }
330
331   /**
332    * query package list by condition.
333    * @param name package name
334    * @param provider package provider
335    * @param version package version
336    * @param deletionPending package deletionPending
337    * @param type package type
338    * @return Response
339    */
340   public Response queryPackageListByCond(String name, String provider, String version,
341       String deletionPending, String type) {
342     ArrayList<PackageData> dbresult = new ArrayList<PackageData>();
343     ArrayList<PackageMeta> result = new ArrayList<PackageMeta>();
344     LOG.info("query package info.name:" + name + " provider:" + provider + " version" + version
345         + " deletionPending" + deletionPending + " type:" + type);
346     try {
347       dbresult =
348           PackageManager.getInstance().queryPackage(name, provider, version, deletionPending, type);
349       result = PackageWrapperUtil.packageDataList2PackageMetaList(dbresult);
350       return Response.ok(result).build();
351     } catch (CatalogResourceException e1) {
352       LOG.error("query package by csarId from db error ! " + e1.getMessage());
353       return RestUtil.getRestException(e1.getMessage());
354     }
355   }
356
357   /**
358    * get package file uri.
359    * @param csarId package id
360    * @param relativePath file relative path
361    * @return Response
362    */
363   public Response getCsarFileUri(String csarId, String relativePath) {
364     try {
365       CsarFileUriResponse result = getCsarFileDownloadUri(csarId, relativePath);
366       return Response.ok(result).build();
367     } catch (CatalogResourceException e1) {
368       LOG.error("Query CSAR package by ID failed ! csarId = " + csarId);
369     }
370
371     return Response.serverError().build();
372   }
373
374   /**
375    * get package file download uri.
376    * @param csarId package id
377    * @param relativePath package file relative path
378    * @return CsarFileUriResponse
379    * @throws CatalogResourceException e
380    */
381   public CsarFileUriResponse getCsarFileDownloadUri(String csarId, String relativePath)
382       throws CatalogResourceException {
383     CsarFileUriResponse result = new CsarFileUriResponse();
384     String downloadUrl = null;
385     String downloadUri = null;
386     String localPath = null;
387     ArrayList<PackageData> packageList = PackageManager.getInstance().queryPackageByCsarId(csarId);
388     if (packageList != null && packageList.size() != 0) {
389       String packageName = packageList.get(0).getName();
390       String relativeUri = packageList.get(0).getDownloadUri() + packageName;
391       downloadUri = relativeUri + relativePath;
392       downloadUrl = PackageWrapperUtil.getUrl(downloadUri);
393       String httpUri = HttpServerPathConfig.getHttpServerPath() + downloadUri;
394       localPath = PackageWrapperUtil.getLocalPath(httpUri);
395     }
396     result.setDownloadUri(downloadUrl);
397     result.setLocalPath(localPath);
398     return result;
399   }
400
401   
402 }