summaryrefslogtreecommitdiffstats
path: root/warehouse/src/main/java/app/market/web/services/app/impl/AppServiceImpl.java
blob: 77a0e5678694a1a34a66150bdea18fe60a5a7400 (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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
/*
 * 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.web.services.app.impl;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import app.market.LogUtil;
import app.market.WebServiceClient;
import app.market.model.app.App;
import app.market.model.app.AppVersion;
import app.market.model.app.FileInfo;
import app.market.model.resource.Dictionary;
import app.market.utils.Utils;
import app.market.utils.constants.Constants;
import app.market.utils.json.JsonMapperUtils;
import app.market.utils.json.JsonResult;
import app.market.utils.property.KeysConstants;
import app.market.utils.property.MessageUtil;
import app.market.utils.property.Option;
import app.market.utils.property.PropertyUtil;
import app.market.utils.rest.RestTemplateUtil;
import app.market.utils.webservice.ApiParam;
import app.market.web.controller.ControllerMapping;
import app.market.web.controller.PageMapping;
import app.market.web.form.app.AppForm;
import app.market.web.services.SpringBaseService;
import app.market.web.services.app.AppService;

@Service
public class AppServiceImpl extends SpringBaseService implements AppService {
    private static Logger logger = LoggerFactory.getLogger( AppServiceImpl.class );

    /**
	 * Authentication
	 *
	 * @return
	 */
    @Override
    public JsonResult validateAuthentication1(HttpSession session) {
        return super.validateAuthentication(session);
    }

    /**
     * Page Search
     *
     * @param form
     * @return
     */
    @Override
    public String selectPaginationData(AppForm form, HttpSession session) {
        logger.debug( "search app list start--Class: " + this.getClass().getName() + "--method: "
                + Thread.currentThread().getStackTrace()[1].getMethodName() + form.getAppId() );

        Map<String, Object> param = new HashMap<>();
        param.put( ApiParam.API_APP_PARAM_APPNAME, form.getAppName() );
        param.put( ApiParam.API_APP_PARAM_APPTYPEID, form.getTypeId() );
        param.put( ApiParam.API_APP_PARAM_DEVELOPER, form.getDeveloper() );
        param.put( ApiParam.API_PARAM_ORDER, form.getOrder() );
        param.put( ApiParam.API_APP_PARAM_APPISPUBLIC, form.getAppIsPublic() );
        param.put( ApiParam.API_PARAM_SORT, form.getSort());
        param.put( ApiParam.API_PARAM_OFFSET, form.getOffset() );
        param.put( ApiParam.API_PARAM_LIMIT, form.getLimit() );
        param.put( ApiParam.API_APP_PARAM_APPDEVICETYPEID, form.getAppDeviceTypeId() );
        param.put( ApiParam.API_APP_PARAM_KEYWORD, form.getKeyWord());

        return super.selectPaginationData( WebServiceClient.REST_APP_COLLECTION_APP, form, null, param , session);
    }

    /**
     * App Save
     *
     * @param form
     * @return
     */
	@Override
	public String save(AppForm form, HttpSession session) {
		logger.debug("save app --S--");
		App record = new App();
		String ret = "";
		List<String> msgList = new ArrayList<String>();
		String appId;
		try {
			Utils.reflect(form, record);
			RestTemplateUtil restTemplate = new RestTemplateUtil();
			String jsonStr = restTemplate.post(WebServiceClient.REST_APP_INFO, record, session);

			JSONObject json = JsonMapperUtils.getJsonObject(jsonStr);
			appId = json.getString(ApiParam.API_RESPONSE_APPID);
			form.setAppId(appId);
			ret = JsonMapperUtils.getJsonString(Constants.STATUS_SUCCESS, PageMapping.INIT_INFO.toString(), form);
		} catch (HttpClientErrorException e) {
			if (e.getStatusCode().value() == Constants.STATUS_BAD_REQUEST) {
				msgList.add(MessageUtil.getPropertites(KeysConstants.INVALID_QUERYPARAM));
				return ret = JsonMapperUtils.getJsonString(Constants.STATUS_BAD_REQUEST, null, msgList);
			}else if( e.getStatusCode().value() == Constants.STATUS_UNAUTHORIZED){
				msgList.add( MessageUtil.getPropertites( KeysConstants.STATUS_UNAUTHORIZED ) );
				return ret = JsonMapperUtils.getJsonString(Constants.STATUS_UNAUTHORIZED, null, msgList);
			}else if( e.getStatusCode().value() == Constants.STATUS_ALREADY_EXISTS){
				msgList.add( MessageUtil.getPropertites( KeysConstants.RESOURCE_APP_ALREADY_EXISTS ) );
				return ret = JsonMapperUtils.getJsonString(Constants.STATUS_ALREADY_EXISTS, null, msgList);
            }else if( e.getStatusCode().value() == Constants.STATUS_FORBIDDEN){
				msgList.add( MessageUtil.getPropertites( KeysConstants.STATUS_FORBIDDEN ) );
				return ret = JsonMapperUtils.getJsonString(Constants.STATUS_ALREADY_EXISTS, null, msgList);
            }
			else{
				msgList.add(MessageUtil.getPropertites(KeysConstants.PROJECT_ERROR));
				return ret = JsonMapperUtils.getJsonString(Constants.STATUS_ERROR, null, msgList);
			}

		} catch (Exception e) {
			return ret = exceptionHandler(e, msgList);
		}

		logger.debug("save app --E-- ret=" + ret);
		return ret;
	}

    /**
     * App Upload
     *
     * @param form
     * @return
     */
    @Override
	public String upload(AppForm form, MultipartFile multFile, String fileName,boolean isImage, HttpSession session) {
		logger.debug("upload app start");
		String ret = JsonMapperUtils.getJsonString(Constants.STATUS_SUCCESS, null, null);
		List<String> msgList = new ArrayList<String>();
		FileInfo fileInfo = null;
		String[] pathParam = null;
		String httpUrl = WebServiceClient.REST_APP_IMAGE;

		try {
			//create fileResource

			File file = getResource(multFile, fileName);
			if (file == null) {
				msgList.add(MessageUtil.getPropertites(KeysConstants.APP_UPLOAD_PARAM_FILE_IS_NULL));
				return JsonMapperUtils.getJsonString(Constants.STATUS_ERROR, null, msgList);
			}
			MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
			FileSystemResource fileSystemResource = new FileSystemResource(file);
			param.add(ApiParam.API_APP_PARAM_MULTIPARTFILE, fileSystemResource);
			param.add(ApiParam.API_APP_PARAM_FILE_NAME, fileName);

			if (!isImage) {
				// create md5
				String md5Hex = DigestUtils.md5Hex(fileSystemResource.getInputStream());
				param.add(ApiParam.API_APP_PARAM_FILE_HASH, md5Hex);

				// create pathParam
				String id = form.getAppId();
				String appDeviceTypeId = form.getAppDeviceTypeId();
				pathParam = new String[] { URLDecoder.decode(fileName, Constants.CHARACTER_UTF8), appDeviceTypeId, id };

				httpUrl = WebServiceClient.REST_APP_FILE_PARM_FILENAME_TYPEID_APPID;
			}

			//http post
			RestTemplateUtil restTemplate = new RestTemplateUtil();
			String jsonStr = restTemplate.post(httpUrl, param, String.class, pathParam, session);

			//delete tempFile
			deleteFile(file);

			//
			fileInfo = JsonMapperUtils.readValue(jsonStr, FileInfo.class);
			if (!isImage) {
			    form.setVerFilePath(fileInfo.getFilePath());
			    form.setAppSize(fileInfo.getFileSize());
			}else{
				form.setImagePath(fileInfo.getIconPath());
			}
			ret = JsonMapperUtils.getJsonString( Constants.STATUS_SUCCESS, null, fileInfo );
        } catch ( HttpClientErrorException e ) {
            if ( e.getStatusCode().value() == Constants.STATUS_BAD_FILE ) {
            	msgList.add( MessageUtil.getPropertites( KeysConstants.APP_UPLOAD_MD5 ) );
            } else if(e.getStatusCode().value() == Constants.STATUS_UNSUPPORT){
            	msgList.add( MessageUtil.getPropertites( KeysConstants.APP_FILE_TYPE_IS_UNSUPPORTED ) );
            } else if(e.getStatusCode().value() == Constants.STATUS_BAD_REQUEST){
            	msgList.add( MessageUtil.getPropertites( KeysConstants.APP_FILE_UNCOMPRESS_FAILED ) );
            }
            return JsonMapperUtils.getJsonString( Constants.STATUS_ERROR, null, msgList );
		} catch (Exception e) {
			msgList.add(e.getMessage());
			logger.debug(this.getClass().getName());
			logger.debug(e.getMessage());
			return JsonMapperUtils.getJsonString(Constants.STATUS_ERROR, null, msgList);
		}
		return ret;
	}

	/**
	 * MultipartFile-> File
	 * @param multfile
	 * @param fileName2
	 * @return
	 * @throws Exception
	 */
    public File getResource(MultipartFile multfile, String fileName) throws Exception {
    	File file = null;
		try {
			String suffix = fileName.substring(fileName.lastIndexOf("."));
			String prefix = FilenameUtils.getBaseName(fileName);
	        if(prefix.length() < 3) {
	        	prefix += "aaa";
	        }
			file = File.createTempFile(prefix, suffix);
			multfile.transferTo(file);
			//deleteFile(file);
		} catch (Exception e) {
			LogUtil.printCatchLog(logger, e);
			logger.error( e.getMessage() );
		}
        return file;
     }

    /**
     * delete file
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }


    /**
     * App Version Save
     *
     * @param form
     * @return
     */

    @Override
    public String saveVersion(AppForm form, HttpSession session) {
        logger.debug( "save app version start" );
        AppVersion record = new AppVersion();
        String ret = JsonMapperUtils.getJsonString( Constants.STATUS_SUCCESS, null, null );
        List<String> msgList = new ArrayList<String>();
        try {
        	record.setFilePath(form.getVerFilePath());
        	record.setSize((int)form.getAppSize());
        	record.setvAppId(form.getAppId());
        	record.setVersionName(form.getVersionName());
        	record.setMd5(form.getHashcode());
        	record.setVersionId(form.getAppVersionId());
        	record.setImagePath(form.getImagePath());
        	//Size is equal to 0 when modified, and should be assigned to null
	        if(StringUtils.isNotEmpty(form.getAppVersionId())){
	        	record.setSize(null);
			}
            RestTemplateUtil restTemplate = new RestTemplateUtil();
            String jsonStr = restTemplate.post( WebServiceClient.REST_APP_VERSION_INFO, record, session);

			JSONObject json = JsonMapperUtils.getJsonObject(jsonStr);
			String versionId = json.getString(ApiParam.API_RESPONSE_APPVERSIONID);
            ret =  JsonMapperUtils.getJsonString( Constants.STATUS_SUCCESS, PageMapping.INIT_CHECK.toString(), form );
		} catch (HttpClientErrorException e) {
			if (e.getStatusCode().value() == Constants.STATUS_BAD_REQUEST) {
				msgList.add(MessageUtil.getPropertites(KeysConstants.INVALID_QUERYPARAM));
			}else if(e.getStatusCode().value() == Constants.STATUS_CONFLICT) {
				msgList.add(MessageUtil.getPropertites(KeysConstants.ALREADY_EXIST));
			}
			return JsonMapperUtils.getJsonString(Constants.STATUS_ERROR, null, msgList);
		} catch (Exception e) {
			ret = exceptionHandler(e, msgList);
		}
       return ret;
    }

    /**
     * App Delete
     *
     * @param id
     * @return
     */
    @Override
    public String delete(String id, HttpSession session) {
        try {
            RestTemplateUtil restTemplate = new RestTemplateUtil();
            // Rest template operation
            restTemplate.delete( WebServiceClient.REST_APP_INFO_PARM_ID, id, session);
        } catch ( Exception e ) {
        	return String.valueOf( Constants.STATUS_ERROR );
        }

        return String.valueOf( Constants.STATUS_SUCCESS );
    }

   /**
     * Search AppForm By AppId
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public AppForm searchFormById(String id, HttpSession session) throws Exception {
    	AppForm appForm = null;
        try {
        	appForm = getAppInfoById(WebServiceClient.REST_APP_INFO_PARM_ID, id, session);
        } catch ( Exception e ) {
            super.exceptionHandler( e );
        }
        return appForm;
    }

    /**
     * Search AppForm By CustomId
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public AppForm searchFormByCustomId(String id, HttpSession session) throws Exception {
        AppForm appForm = new AppForm();
        try {
            RestTemplateUtil restTemplate = new RestTemplateUtil();
            // Rest template operation
            String jsonStr = restTemplate.get( WebServiceClient.REST_APP_INFO_PARM_CUSTOMID, session, new String[] { id } );
            App app = JsonMapperUtils.readValue( jsonStr, App.class );
            Utils.reflect( app, appForm );
        } catch ( Exception e ) {
        	appForm = null;
        }
        return appForm;
    }

    /***
     * Search AppInfo By Id
     * @param url
     * @param id
     * @return
     * @throws Exception
     */
    private AppForm getAppInfoById(String url,String id, HttpSession session) throws Exception {
        AppForm appForm = new AppForm();
        try {
            RestTemplateUtil restTemplate = new RestTemplateUtil();
            // Rest template operation
            String jsonStr = restTemplate.get( url, session, new String[] { id } );
            App app = JsonMapperUtils.readValue( jsonStr, App.class );
            Utils.reflect( app, appForm );
        } catch ( Exception e ) {
            super.exceptionHandler( e );
        }
        return appForm;
    }

    /**
     * Get App type Option
     *
     * @param model
     * @param hasSpace
     * @throws Exception
     */
    @Override
	public void getAppTypeOption(Map<String, Object> model, boolean hasSpace, HttpSession session) throws Exception {
		List<Option> list = getOption(hasSpace, ApiParam.API_PARAM_VALUE_DICTIONARY_CATEGORY, session);
		model.put("appTypeList", list);
	}

    /**
     * Get device type Option
     *
     * @param model
     * @param hasSpace
     * @throws Exception
     */
    @Override
	public void getDeviceTypeOption(Map<String, Object> model, boolean hasSpace, HttpSession session) throws Exception {
		List<Option> list = getOption(hasSpace, ApiParam.API_PARAM_VALUE_DICTIONARY_DEVICETYPE, session);
		model.put("appDeviceTypeList", list);
	}

    /**
     * Get device type Option
     *
     * @param model
     * @param hasSpace
     * @throws Exception
     */
    @Override
	public void getIsPublicOption(Map<String, Object> model, boolean hasSpace, HttpSession session) throws Exception {
		List<Option> list = getOption(hasSpace, ApiParam.API_PARAM_VALUE_DICTIONARY_ISPUBLIC, session);
		model.put("appIsPublicList", list);
	}

	private List<Option> getOption( boolean hasSpace,String optionType, HttpSession session) throws Exception {
		RestTemplateUtil restTemplate = new RestTemplateUtil();
		List<Option> list = new ArrayList<Option>();
		// Rest template operation
		try {
			String jsonStr = restTemplate.get(WebServiceClient.REST_DICTIONARY_COLLECTION, session, optionType);
			List<Dictionary> typelist = (List<Dictionary>)JsonMapperUtils.getJsonList(jsonStr, Dictionary.class);

			if (hasSpace) {
				Option option = new Option(PropertyUtil.DEFAULLABEL, "");
				list.add(option);
			}
			for (Dictionary type : typelist) {
				Option option = new Option(type.getDicLabel(), type.getDicValue().toString());
				list.add(option);
			}
		} catch (Exception e) {
			super.exceptionHandler(e);
		}

		return list;
	}

    /**
     * App Download
     *
     * @param form
     * @return
     */
	@Override
	public ResponseEntity<byte[]> download(AppForm form, HttpSession session) {
		String url = WebServiceClient.REST_APP_FILE_PARM_FILEPATH;
		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(null, null, HttpStatus.FORBIDDEN);;

		try {
	        Map<String, Object> param = new HashMap<>();
	        param.put( ApiParam.API_APP_PARAM_FILE_PATH, form.getVerFilePath() );

			RestTemplateUtil restTemplate = new RestTemplateUtil();
			response = restTemplate.download(url, param, session);
		} catch (Exception e) {
			LogUtil.printCatchLog(logger, e);
			e.printStackTrace();
		}
		return response;
	}

    /**
     * Add Or Update Type/Device Type
     *
     * @param dicType
     * @param dicValue
     * @param dicLabel
     * @return
     */
	public String saveDictionary(String dicType, String dicValue, String dicLabel, HttpSession session) {
		logger.debug("APPを更新・新規する");
		Dictionary record = new Dictionary();
		String ret = JsonMapperUtils.getJsonString(Constants.STATUS_SUCCESS, null, null);
		List<String> msgList = new ArrayList<String>();
		try {
			record.setDicType(dicType);
			record.setDicValue(dicValue);
			record.setDicLabel(dicLabel);

			RestTemplateUtil restTemplate = new RestTemplateUtil();
			restTemplate.post(WebServiceClient.REST_DICTIONARY_INFO, record, session);
			ret = JsonMapperUtils.getJsonString(Constants.STATUS_SUCCESS, PageMapping.APP_TYPE.toString(), null);
		} catch (HttpClientErrorException e) {
			if (e.getStatusCode().value() == Constants.STATUS_BAD_REQUEST) {
				msgList.add(MessageUtil.getPropertites(KeysConstants.INVALID_QUERYPARAM));
			} else if (e.getStatusCode().value() == Constants.STATUS_CONFLICT) {
				msgList.add(MessageUtil.getPropertites(KeysConstants.ALREADY_EXIST));
			}
			return JsonMapperUtils.getJsonString(Constants.STATUS_ERROR, null, msgList);
		} catch (Exception e) {
			ret = exceptionHandler(e, msgList);
		}
		return ret;
	}
}