406f064f9bedb8635b7b3c7145b837bd0d57b318
[eliot.git] / blueprints / common / eliot-ui / be / src / eliotk8sclient / src / main / java / com / eliot / eliotbe / eliotk8sclient / service / AppServiceHandler.java
1 /*
2  * Copyright 2020 Huawei Technologies Co., Ltd.
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
17 package com.eliot.eliotbe.eliotk8sclient.service;
18
19
20 import org.apache.tomcat.util.http.fileupload.FileUploadException;
21 import com.eliot.eliotbe.eliotk8sclient.AppException;
22 import com.eliot.eliotbe.eliotk8sclient.common.AppConstants;
23 import org.apache.tomcat.util.http.fileupload.FileUtils;
24 import org.joda.time.LocalDate;
25 import org.joda.time.LocalDateTime;
26 import org.joda.time.LocalTime;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import org.springframework.beans.factory.annotation.Autowired;
30 import org.springframework.http.HttpStatus;
31 import org.springframework.http.ResponseEntity;
32 import org.springframework.stereotype.Component;
33 import org.springframework.util.StringUtils;
34 import org.springframework.web.multipart.MultipartFile;
35
36 import java.io.IOException;
37 import java.net.URLEncoder;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.lang.System;
45 import java.io.File;
46 @Component
47 public class AppServiceHandler {
48
49     public static final Logger logger = LoggerFactory.getLogger(AppServiceHandler.class);
50
51     @Autowired
52     private AppService appService;
53
54     /**
55      * Upload deployment file.
56      * @param file file
57      * @return
58      */
59     public ResponseEntity<Map<String, String>> uploadDeployment(MultipartFile file)
60             throws IOException {
61         try {
62             validateFile(file, AppConstants.MAX_CONFIG_SIZE, "");
63         } catch (FileUploadException | NullPointerException e) {
64             Map<String, String> response = new HashMap<>();
65             response.put("error",e.getMessage());
66             return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
67         }
68
69         String destination = appService.getPackageBasePath() + LocalDate.now().toString()
70                 + LocalTime.now().getMillisOfSecond() +"/";
71         File destinationfile = new File(destination);
72 /*        if (file.exists()) {
73             FileUtils.cleanDirectory(file);
74             FileUtils.deleteDirectory(file);
75         }*/
76         boolean isMk = destinationfile.mkdir();
77         if (!isMk) {
78             logger.info("package directory creation failed");
79         }
80
81         logger.info("destination path is set");
82
83         String deploymentPathWithFile = null;
84
85         deploymentPathWithFile = storeDeployFile(destination,file);
86
87         appService.instantiateApplication(deploymentPathWithFile);
88
89         Map<String, String> response = new HashMap<>();
90         response.put("Application Deployed","OK");
91         return new ResponseEntity<>(response, HttpStatus.OK);
92     }
93
94     private boolean checkK8sConfigFile(Path k8sConfig) {
95         if (!k8sConfig.toFile().isFile() || !k8sConfig.toFile().exists()) {
96             logger.error("Config file does not exist...");
97             return false;
98         }
99         return true;
100     }
101
102     private String storeDeployFile(String basePath, MultipartFile file) throws IOException {
103         // Get the file and save it somewhere
104         byte[] bytes = file.getBytes();
105
106         //String packageDir = getPackageDirName(AppConstants.MAX_PACKAGE_DIR_SIZE);
107         Path path = Paths.get(basePath + file.getOriginalFilename());
108        // Path path = Paths.get("~/");
109         Files.write(path, bytes);
110         String deploymentFilePath;
111         return deploymentFilePath = basePath+ file.getOriginalFilename();
112     }
113
114     private Path loadK8sConfigFilePath(String basePath) {
115         return Paths.get(basePath + "");
116     }
117
118 /*    private String getPackageDirName(int size) {
119         final String allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
120
121         SecureRandom sr = new SecureRandom();
122         StringBuilder sb = new StringBuilder(size);
123         for (int i = 0; i < size; i++) {
124             sb.append(allowed.charAt(sr.nextInt(allowed.length())));
125         }
126         return sb.toString();
127     }*/
128
129     /**
130      * Validate MultipartFile.
131      *
132      * @param file file
133      * @param fileSize  file size for validation
134      * @param extension file extension
135      * @throws FileUploadException on exception throws
136      */
137     public void validateFile(MultipartFile file, long fileSize, String extension) throws FileUploadException {
138         if (file == null) {
139             throw new FileUploadException("file is null");
140         }
141
142         if (file.isEmpty()) {
143             throw new FileUploadException("file is empty");
144         } else if (!extension.isEmpty()
145             && null != file.getOriginalFilename() && !file.getOriginalFilename().endsWith(extension)) {
146             throw new FileUploadException("package format not supported");
147         } else if (file.getSize() > fileSize) {
148             throw new FileUploadException("file size not in the limit");
149         }
150     }
151     private ResponseEntity<Map<String, String>> createErrorResponse(String error) {
152         Map<String, String> response = new HashMap<>();
153         response.put("error", error);
154         response.put("status", HttpStatus.INTERNAL_SERVER_ERROR.toString());
155         return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
156     }
157 }