summaryrefslogtreecommitdiffstats
path: root/webservice/src/main/java/app/market/webservice/dataManager/AppFileController.java
blob: 8a24a58471c2d20f0308179d0236b8c71a519b31 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/*
 * Copyright (c) 2019 TOYOTA MOTOR CORPORATION
 *
 * 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 app.market.webservice.dataManager;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import app.market.LogUtil;
import app.market.common.comm;
import app.market.model.app.FileInfo;
import app.market.utils.constants.Constants;
import app.market.utils.json.JsonMapperUtils;
import app.market.utils.property.KeysConstants;
import app.market.utils.webservice.ApiParam;
import app.market.utils.webservice.ErrorCode;
import app.market.utils.webservice.ErrorCodeEnum;
import app.market.utils.webservice.WebServiceURI;
import app.market.webservice.WebserviceRestBaseController;


@RestController
public class AppFileController extends WebserviceRestBaseController {

	private static Logger logger = LoggerFactory.getLogger(AppFileController.class);

	@Autowired
	ServletContext context;

	/**
	 * upload application file
	 * @param inputFile
	 * @param md5
	 * @param appDeviceType
	 * @param appId
	 * @param orgFileName
	 * @return
	 */
	@RequestMapping(value = WebServiceURI.REST_APP_FILE_PARM_FILENAME_TYPEID_APPID_LF, headers = ("content-type=multipart/*"), method = RequestMethod.POST)
	public String upload(@RequestParam(ApiParam.API_APP_PARAM_MULTIPARTFILE) MultipartFile inputFile
			,@RequestParam(ApiParam.API_APP_PARAM_FILE_HASH) String hashcode
			,@PathVariable(ApiParam.API_APP_PARAM_APPDEVICETYPEID) String appDeviceType
			,@PathVariable(ApiParam.API_APP_PARAM_APPID) String appId
			,@PathVariable(ApiParam.API_APP_PARAM_FILE_NAME) String orgFileName
			, HttpServletResponse response) {
		logger.debug("upload");

		FileInfo fileInfo = new FileInfo();
		String responseStr = null;

		if (inputFile.isEmpty() || StringUtils.isEmpty(hashcode)) {
			return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
					new ErrorCode(ErrorCodeEnum.MISSING_RESOURCE,KeysConstants.MISSING_NECESSARY_QUERYPARAM));
		}

		if(!orgFileName.endsWith(Constants.FILE_TYPE)){
			return comm.getResponseError(response, Constants.STATUS_UNSUPPORT,
					new ErrorCode(ErrorCodeEnum.UNSUPPORT_FILE,KeysConstants.APP_FILE_TYPE_IS_UNSUPPORTED));
		}

		//md5 check file
		try {
			String md5Hex = DigestUtils.md5Hex(inputFile.getInputStream());
			if (!md5Hex.equalsIgnoreCase(hashcode)) {
				return comm.getResponseError(response, Constants.STATUS_BAD_FILE,
						new ErrorCode(ErrorCodeEnum.MD5_FAILED,KeysConstants.APP_UPLOAD_MD5));
			}
		} catch (IOException e) {
			return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
					new ErrorCode(ErrorCodeEnum.MISSING_RESOURCE,KeysConstants.STATUS_BAD_REQUEST));
		}

		try {
			orgFileName = URLDecoder.decode(orgFileName, "utf-8");
			String destFileName = FileUtil.createFileName(orgFileName);
			String destFilePath = FileUtil.getUploadPath(FileUtil.getAppPath(appDeviceType, appId));

			//save appFile
			String destPath = destFilePath + destFileName;
			File destFile = new File(destFilePath + destFileName);
			inputFile.transferTo(destFile);

			//uncompress appFile
			String uncompressFilePath = FileUtil.uncompress(destPath);
			logger.debug("uncompressFilePath=" + uncompressFilePath);

			//check uncompress file
			if(StringUtils.isEmpty(uncompressFilePath)){
				return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
						new ErrorCode(ErrorCodeEnum.BAD_FAILED,KeysConstants.APP_FILE_UNCOMPRESS_FAILED));
			}

			if (StringUtils.isNotEmpty(uncompressFilePath)) {
				// get info in config.xml
				FileUtil.parseConfigInfo(uncompressFilePath, fileInfo);

				//check customer appid
				if(StringUtils.isEmpty(fileInfo.getConfigAppId())
				|| StringUtils.isEmpty(fileInfo.getConfigVersionName())){
					return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
							new ErrorCode(ErrorCodeEnum.BAD_FAILED,KeysConstants.APP_FILE_READ_FAILED));
				}

				// save icon image of appFile
				String iconPath = "";
				if (StringUtils.isNotEmpty(fileInfo.getIconPath())) {
					iconPath = FileUtil.saveAppIcon(uncompressFilePath, fileInfo.getIconPath());
					fileInfo.setIconPath(iconPath);///resource/appIcon/b4a527c0-0bfc-4ca1-99da-cdd4850ceb43_icon.svg
				}

				// remove temp directory of uncompress
				FileUtil.removeFile(uncompressFilePath);
			}
			String relativeFilePath = FileUtil.getAppPath(appDeviceType, appId) + destFileName;
			fileInfo.setFileName(orgFileName);
			fileInfo.setFileSize(inputFile.getSize());
			fileInfo.setFilePath(relativeFilePath);
			fileInfo.setFileHashCode(hashcode);

			responseStr = JsonMapperUtils.writeValueAsString(fileInfo);
		} catch (Exception e) {
			responseStr = comm.getResponseException(response, e);
		}

		logger.debug("upload end");
		return responseStr;
	}

	/**
	 * download
	 * @param fileName
	 * @param appType
	 * @param appId
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = WebServiceURI.REST_APP_FILE_PARM_FILEPATH_LF, method = RequestMethod.GET)
	public ResponseEntity<byte[]> download(@RequestParam(ApiParam.API_APP_PARAM_FILE_PATH) String filePath)	throws IOException {

		 String downloadPath = FileUtil.getUploadPath(filePath);
		 String orgFileName = FileUtil.getOrgFileName(filePath);

		 HttpHeaders headers = new HttpHeaders();
		 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		 headers.setContentDispositionFormData("attachment", URLEncoder.encode(orgFileName,"UTF-8"));

		 byte[] body = null;
		 ResponseEntity<byte[]> responseEntity = null;

		try {
			File file = new File(downloadPath);
			body = FileUtils.readFileToByteArray(file);

			responseEntity = new ResponseEntity<byte[]>(body, headers, HttpStatus.OK);
		} catch (IOException e) {
			LogUtil.printCatchLog(logger, e);
			responseEntity = new ResponseEntity<byte[]>(body, headers, HttpStatus.INTERNAL_SERVER_ERROR);
			e.printStackTrace();
		}
		return responseEntity;
	}

	/**
	 * upload image
	 * @param inputFile
	 * @param orgFileName
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = WebServiceURI.REST_APP_IMAGE_LF, headers = ("content-type=multipart/*"), method = RequestMethod.POST)
	public String imageUpload(@RequestParam(ApiParam.API_APP_PARAM_MULTIPARTFILE) MultipartFile inputFile
			,@RequestParam(value=ApiParam.API_APP_PARAM_FILE_NAME,required = false) String orgFileName
			, HttpServletResponse response){
		logger.debug("imageUpload");

		FileInfo fileInfo = new FileInfo();
		String responseStr = null;

		//check image
		if (inputFile.isEmpty()) {
			return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
					new ErrorCode(ErrorCodeEnum.MISSING_RESOURCE,KeysConstants.MISSING_NECESSARY_QUERYPARAM));
		}
		try {
			//check image
			String contentType = inputFile.getContentType();
			String imageStr = contentType.substring(Constants.IMAGE_INT,contentType.lastIndexOf(Constants.PATH_SEPARATOR));
			if(!orgFileName.endsWith(Constants.IMAGE_SVG) && !orgFileName.endsWith(Constants.IMAGE_PNG)
					&&!imageStr.equals(Constants.IMAGE_TYPE)) {
				return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
						new ErrorCode(ErrorCodeEnum.MISSING_RESOURCE,KeysConstants.UPLOAD_PICTURES_ONLY));
			}
			if(inputFile.getSize() > (Constants.IMAGE_SIZE)) {
				return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
						new ErrorCode(ErrorCodeEnum.MISSING_RESOURCE,KeysConstants.THE_PICTURE_SIZES));
			}
			if(StringUtils.isEmpty(orgFileName)){
				orgFileName = inputFile.getOriginalFilename();
			}
			String destFilePath = FileUtil.getImagePath(orgFileName);

			File destFile = new File(destFilePath);
			inputFile.transferTo(destFile);

            String fullImagePath = FileUtil.getImageAccessPath(destFilePath);
            fileInfo.setIconPath(fullImagePath);

			responseStr = JsonMapperUtils.writeValueAsString(fileInfo);
		} catch (Exception e) {
			responseStr = comm.getResponseException(response, e);
		}

		logger.debug("imageUpload end");
		return responseStr;
	}

}