/* * 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 map = new HashMap(); try { int counter = appCore.countByExample(example); List 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; } }