summaryrefslogtreecommitdiffstats
path: root/webservice/src/main/java/app/market/webservice/app/AppRestController.java
blob: 25b5d68c38e2d7d1b95073e4a47d7a9c8357e3d0 (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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/*
 * 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.app;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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 com.alibaba.fastjson.JSONObject;

import app.market.common.comm;
import app.market.core.app.AppCore;
import app.market.core.resource.DictionaryCore;
import app.market.core.user.UserCore;
import app.market.model.app.App;
import app.market.model.app.AppExample;
import app.market.model.app.AppExample.Criteria;
import app.market.model.app.AppVersion;
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 AppRestController extends WebserviceRestBaseController {

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

	@Autowired
	private AppCore appCore;

    @Autowired
    private UserCore userCore;

    @Autowired
    private DictionaryCore dicCore;

	/**
	 * get application list
	 *
	 * @param appName
	 * @param appTypeId
	 * @param appDeveloper
	 * @param sort
	 * @param order
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = WebServiceURI.REST_APP_COLLECTION_APP_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
	public String selectDataByExample(
			@RequestParam(value = ApiParam.API_APP_PARAM_APPTYPEID, required = false, defaultValue = "") String appTypeId,
			@RequestParam(value = ApiParam.API_APP_PARAM_APPDEVICETYPEID, required = false, defaultValue = "") String deviceTypeId,
			@RequestParam(value = ApiParam.API_APP_PARAM_APPISPUBLIC, required = false, defaultValue = "") String isPublic,
			@RequestParam(value = ApiParam.API_PARAM_ORDER, required = false, defaultValue = ApiParam.API_PARAM_VALUE_ORDER_ASC) String order,
			@RequestParam(value = ApiParam.API_PARAM_SORT, required = false,  defaultValue = ApiParam.API_PARAM_DEFAULT_SORT_NAME) String sort,
			@RequestParam(value = ApiParam.API_PARAM_OFFSET, required = false, defaultValue = ApiParam.API_PARAM_DEFAULT_OFFSET) Integer offset,
			@RequestParam(value = ApiParam.API_PARAM_LIMIT, required = false, defaultValue = ApiParam.API_PARAM_DEFAULT_LIMIT ) Integer limit,
			@RequestParam(value = ApiParam.API_APP_PARAM_KEYWORD, required = false, defaultValue = "") String keyWord,
			HttpServletRequest request,
			HttpServletResponse response) {
		logger.debug("get application list --S--");

		ErrorCode paramCheckResult = checkParamSearch(appTypeId,deviceTypeId,isPublic,order,sort,offset,limit,request);
		if (paramCheckResult != null) {
			return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST, paramCheckResult);
		}
		//guest user do not authority
		String authentication = request.getHeader(Constants.TOKEN_AUTHORIZATION);
		if(StringUtils.isEmpty(authentication)) {
			if(StringUtils.isEmpty(isPublic)) {
				isPublic = ApiParam.API_PARAM_DEFAULT_IS_PUBLIC;
			}
			else if (ApiParam.API_PARAM_DEFAULT_NOT_PUBLIC.equals(isPublic)) {
				return comm.getResponseError(response, Constants.STATUS_FORBIDDEN,
					new ErrorCode(ErrorCodeEnum.FORBIDDEN_RESOURCE,KeysConstants.STATUS_FORBIDDEN));
			}
		}

		AppExample example = getAppSearchExample(deviceTypeId, isPublic, appTypeId, keyWord, sort, order);
		String responseStr = null;
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			int counter = appCore.countByExample(example);
			List<App> list = appCore.selectByExample(offset, limit, example);

			map.put(Constants.PAGINATION_COUNTER, counter);
			map.put(Constants.PAGINATION_DATA, list);

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

		logger.debug("get application list --E--");
		return responseStr;
	}

	/**
	 *
	 * @param deviceTypeId
	 * @param isPublic
	 * @param appTypeId
	 * @param keyWord
	 * @param sort
	 * @param order
	 * @return
	 */
	private AppExample getAppSearchExample(String deviceTypeId, String isPublic, String appTypeId, String keyWord, Object sort, String order) {
		AppExample example = new AppExample();

		//set or condition
		if (StringUtils.isNotEmpty(keyWord)) {
			String likeKeyWord = "%" + keyWord + "%";
			Criteria ucAppName = example.createCriteria();
			setAndCondition(ucAppName, deviceTypeId, isPublic, appTypeId);
			ucAppName.andAppNameLike(likeKeyWord);

			Criteria ucDeveloper = example.createCriteria();
			setAndCondition(ucDeveloper, deviceTypeId, isPublic, appTypeId);
			ucDeveloper.andDeveloperNameLike(likeKeyWord);
			example.or(ucDeveloper);

			Criteria ucAbstract = example.createCriteria();
			setAndCondition(ucAbstract, deviceTypeId, isPublic, appTypeId);
			ucAbstract.andAbstractLike(likeKeyWord);
			example.or(ucAbstract);
		}else{
			Criteria uc = example.createCriteria();
			setAndCondition(uc, deviceTypeId, isPublic, appTypeId);
		}

		// set sort and order
		String sortName = ApiParam.AppQueryParam.get(sort);
		if (StringUtils.isNotEmpty(sortName)) {
			example.setOrderByClause(sortName + " " + order);
		}
		return example;
	}

	/**
	 *
	 * @param uc
	 * @param deviceTypeId
	 * @param isPublic
	 * @param appTypeId
	 */
	private void setAndCondition(Criteria uc, String deviceTypeId, String isPublic, String appTypeId)
	{
		uc.andIsDelEqualTo(Constants.DATA_VALID);
		uc.andAppNameIsNotNull();
		if (StringUtils.isNotEmpty(deviceTypeId)) {
			uc.andAppDeviceTypeIdEqualTo(deviceTypeId);
		}
		if (StringUtils.isNotEmpty(isPublic)) {
			uc.andAppIsPublicEqualTo(isPublic);
		}
		if (StringUtils.isNotEmpty(appTypeId)) {
			uc.andTypeIdEqualTo(appTypeId);
		}
	}

	/**
	 * update application information
	 *
	 * @param appJsonStr
	 * @return appId
	 */
	@RequestMapping(value = WebServiceURI.REST_APP_INFO_LF, method = RequestMethod.POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
	public String saveApp(@RequestBody String appJsonStr, HttpServletResponse response) {
		logger.debug("update application information --S-- appStr=" + appJsonStr);

		if(StringUtils.isEmpty(appJsonStr)){
			return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
					new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM,KeysConstants.INVALID_QUERYPARAM));
		}

		App app = JsonMapperUtils.readValue(appJsonStr, App.class);

		//createDate and updateDate
		Date date = new Date();
		if(StringUtils.isEmpty(app.getAppId())){
			app.setCreateDate(date);
			app.setUpdateDate(date);
		}else{
			app.setUpdateDate(date);
		}

		//パラメータのチェック
		ErrorCode paramCheckResult = checkParamSave(app);
		if (paramCheckResult != null) {
			return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST, paramCheckResult);
		}
		app.setIsDel(Constants.DATA_VALID);

		JSONObject responseData = new JSONObject();
		String responseStr = null;

		try {
			int r = appCore.save(app);
			if (r == 0) {
				responseStr = comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
						new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM,KeysConstants.MISSING_NECESSARY_QUERYPARAM));
			} else {
				responseData.put(ApiParam.API_RESPONSE_APPID, app.getAppId());
				responseStr = responseData.toJSONString();
			}
		} catch (DuplicateKeyException ed) {
			responseStr = comm.getResponseError(response, Constants.STATUS_ALREADY_EXISTS, new ErrorCode(ErrorCodeEnum.RESOURCE_ALREADY_EXISTS,KeysConstants.RESOURCE_APP_ALREADY_EXISTS));
		} catch (Exception e) {
			responseStr = comm.getResponseException(response, e);
		}
		logger.debug("update application information --E-- appStr=" + appJsonStr);
		return responseStr;
	}

	/**
	 *
	 * @param appVerInfo
	 * @return
	 */
	@RequestMapping(value = WebServiceURI.REST_APP_VERSION_INFO_LF, method = RequestMethod.POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
	public String saveAppVersionInfo(@RequestBody String appVerInfo, HttpServletResponse response) {
		logger.debug("saveAppVersionInfo,input=" + appVerInfo);
		boolean insertFlag = false;

		if(StringUtils.isEmpty(appVerInfo)){
			return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
					new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM,KeysConstants.APP_VERSIONNAME_IS_NOT_EMPTY));
		}

		AppVersion appVer = JsonMapperUtils.readValue(appVerInfo, AppVersion.class);

		//createDate and updateDate
		Date date = new Date();
		if(StringUtils.isEmpty(appVer.getVersionId())){
            appVer.setVersionCreateDate(date);
		}

		//check parameter
		ErrorCode paramCheckResult = checkParamVersionSave(appVer);
		if (paramCheckResult != null) {
			return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST, paramCheckResult);
		}

		appVer.setVersionIsDel(Constants.DATA_VALID);
		if (appVer.getVersionId().isEmpty()) {
			insertFlag = true;
		}

		JSONObject responseData = new JSONObject();
		String responseStr = null;

		try {
			int r = appCore.saveVision(appVer);
			if (r == 0) {
				responseStr = comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
						new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM,KeysConstants.MISSING_NECESSARY_QUERYPARAM));
			} else {
				responseData.put(ApiParam.API_RESPONSE_APPVERSIONID, appVer.getVersionId());
				responseStr = responseData.toJSONString();

				//Save verion
				if (insertFlag) {
					App app = new App();
					app.setAppId(appVer.getvAppId());
					app.setAppVersionId(appVer.getVersionId());
					int i = appCore.save(app);
					if (i == 0) {
						responseStr = comm.getResponseError(response, Constants.STATUS_BAD_REQUEST, new ErrorCode(
								ErrorCodeEnum.INVALID_QUERYPARAM, KeysConstants.MISSING_NECESSARY_QUERYPARAM));
					}
				}
			}
		} catch (Exception e) {
			responseStr = comm.getResponseException(response, e);
		}
		logger.debug("アプリを保存終了 --E-- appStr=" + appVerInfo);
		return responseStr;
	}

	/**
	 * Delete application information
	 *
	 * @param user
	 * @return
	 */
	@RequestMapping(value = WebServiceURI.REST_APP_INFO_PARM_ID_LF, method = RequestMethod.DELETE, produces = APPLICATION_JSON_UTF8_VALUE)
	public String deleteApp(@PathVariable(ApiParam.API_APP_PARAM_APPID) String appId, HttpServletResponse response) {
		logger.debug("Delete application --S--" + appId);

		String responseStr = "";
		try {
			int r = appCore.deleteByAppId(appId);
			if (r == 0) {
				responseStr = comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
						new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM,KeysConstants.INVALID_OPERATION));
			}
		} catch (Exception e) {
			responseStr = comm.getResponseException(response, e);
		}

		logger.debug("Delete application --E-- appId=" + appId);
		return responseStr;
	}

	/**
	 * Get application information from id
	 *
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = WebServiceURI.REST_APP_INFO_PARM_ID_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
	public String getAppInfo(@PathVariable(ApiParam.API_APP_PARAM_APPID) String appId, HttpServletResponse response) {
		logger.debug(" Get application information from id --S-- appId=" + appId);
		String responseStr = "";

		try {
			App app = appCore.selectAppByAppId(appId);
			if(app == null){
				return responseStr;
			}
			responseStr = JsonMapperUtils.writeValueAsString(app);
		} catch (Exception e) {
			responseStr = comm.getResponseException(response, e);
		}

		logger.debug(" Get application information from id --E-- appId=" + appId);
		return responseStr;
	}

	/**
	 * Get application information from CustomId
	 *
	 * @param appCustomId
	 * @return
	 */
	@RequestMapping(value = WebServiceURI.REST_APP_INFO_PARM_CUSTOMID_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
	public String getAppInfoByCustomId(@PathVariable(ApiParam.API_APP_PARAM_APPID_CUSTOM) String appIdCustom, HttpServletResponse response) {
		logger.debug(" Get application information from CustomId --S-- appIdCustom=" + appIdCustom);
		String responseStr = "";

		try {
			App app = appCore.selectAppByAppCustomId(appIdCustom);
			if(app == null){
				return responseStr;
			}
			responseStr = JsonMapperUtils.writeValueAsString(app);
		} catch (Exception e) {
			responseStr = comm.getResponseException(response, e);
		}

		logger.debug(" Get application information from CustomId --E-- appIdCustom=" + appIdCustom);
		return responseStr;
	}

	/**
	 * Check application
	 * @param app
	 * @return null:valid parameter
	 *         ErrorCode: invalid parameter
	 */

	private ErrorCode checkParamSave(App app) {
		// create new application
		if(StringUtils.isEmpty(app.getAppId())){
			if(StringUtils.isEmpty(app.getAppDeviceTypeId().replace(" ", ""))){
				return new ErrorCode(ErrorCodeEnum.MISSING_NECESSARY_QUERYPARAM, KeysConstants.MISSING_NECESSARY_QUERYPARAM);
			}
		}else{
			// update application
			if (!StringUtils.isEmpty(app.getAppId())&& app.getUpdateDate() == null) {
				return new ErrorCode(ErrorCodeEnum.MISSING_NECESSARY_QUERYPARAM, KeysConstants.MISSING_NECESSARY_QUERYPARAM);
		    }

		    //check developer
		    if (userCore.countById(app.getDeveloper()) <= 0) {
		    	return new ErrorCode(ErrorCodeEnum.INVALID_BODY, KeysConstants.DEVELOPER_IS_NOT_EXIST);
		    }

		    //check typeId
		    if (dicCore.countDicforItem(ApiParam.API_PARAM_VALUE_DICTIONARY_CATEGORY, app.getTypeId()) <= 0) {
		    	return new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM, KeysConstants.INVALID_QUERYPARAM);
		    }

		    //check deviceTypeId
		    /*if (0 > Integer.valueOf(app.getAppDeviceTypeId()) || Integer.valueOf(app.getAppDeviceTypeId()) > 9 ) {
			return new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM, KeysConstants.INVALID_QUERYPARAM);
		    }*/
		}

		return null;
	}

	/**
	 * Check applciation version
	 * @param ver
	 * @return null:valid parameter
	 *         ErrorCode: invalid parameter
	 */
	private ErrorCode checkParamVersionSave(AppVersion ver) {
		if (ver.getVersionName() == null
			|| ver.getvAppId() == null
			|| (StringUtils.isEmpty(ver.getvAppId().replace(" ", "")))
			|| (StringUtils.isEmpty(ver.getVersionName().replace(" ", "")))) {
			   return new ErrorCode(ErrorCodeEnum.MISSING_NECESSARY_QUERYPARAM, KeysConstants.MISSING_NECESSARY_QUERYPARAM);
		}
		// create new applciation
		if (StringUtils.isEmpty(ver.getVersionId())){
			if ((StringUtils.isEmpty(ver.getFilePath()) || ver.getSize() == 0 || ver.getVersionCreateDate() == null )) {
				return new ErrorCode(ErrorCodeEnum.MISSING_NECESSARY_QUERYPARAM, KeysConstants.MISSING_NECESSARY_QUERYPARAM);
			} else {
				// check appId
				AppExample appExample = new AppExample();
				Criteria uc = appExample.createCriteria();
				uc.andAppIdEqualTo(ver.getvAppId());
				if (appCore.countByExample(appExample) <= 0) {
					return new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM, KeysConstants.INVALID_QUERYPARAM);
				}
			}
		}
		return null;
	}

	/***
	 * get application list
	 * @param appTypeId
	 * @param deviceTypeId
	 * @param isPublic
	 * @param order
	 * @param sort
	 * @param offset
	 * @param limit
	 * @param request
	 * @return ErrorCode
	 */
	private ErrorCode checkParamSearch(String appTypeId, String deviceTypeId, String isPublic, String order,
			String sort, int offset, int limit, HttpServletRequest request) {
		ErrorCode ret = null;

		if (offset < ApiParam.API_PARAM_CRITICAL_OFFSET || limit < ApiParam.API_PARAM_CRITICAL_LIMIT ||(!ApiParam.API_PARAM_VALUE_ORDER_ASC.equalsIgnoreCase(order)
				&& !ApiParam.API_PARAM_VALUE_ORDER_DESC.equalsIgnoreCase(order))
				|| (ApiParam.AppQueryParam.get(sort) == null)
				|| (StringUtils.isNotEmpty(isPublic) && (!isPublic.equals(ApiParam.API_PARAM_DEFAULT_NOT_PUBLIC)
						&& !isPublic.equals(ApiParam.API_PARAM_DEFAULT_IS_PUBLIC)))) {
			ret = new ErrorCode(ErrorCodeEnum.MISSING_NECESSARY_QUERYPARAM, KeysConstants.MISSING_NECESSARY_QUERYPARAM);
		}

		return ret;
	}
}