summaryrefslogtreecommitdiffstats
path: root/webservice/src/main/java/app/market
diff options
context:
space:
mode:
Diffstat (limited to 'webservice/src/main/java/app/market')
-rw-r--r--webservice/src/main/java/app/market/LogUtil.java25
-rw-r--r--webservice/src/main/java/app/market/PropertyUtil.java82
-rw-r--r--webservice/src/main/java/app/market/WebServiceConstants.java33
-rw-r--r--webservice/src/main/java/app/market/common/comm.java51
-rw-r--r--webservice/src/main/java/app/market/token/dao/RedisGeneratorDao.java48
-rw-r--r--webservice/src/main/java/app/market/token/interceptor/AuthenticationTokenInterceptor.java65
-rw-r--r--webservice/src/main/java/app/market/token/service/RedisTokenManager.java268
-rw-r--r--webservice/src/main/java/app/market/webservice/Filter.java40
-rw-r--r--webservice/src/main/java/app/market/webservice/InitServer.java52
-rw-r--r--webservice/src/main/java/app/market/webservice/Log4jlistener.java53
-rw-r--r--webservice/src/main/java/app/market/webservice/WebServiceClient.java24
-rw-r--r--webservice/src/main/java/app/market/webservice/WebserviceRestBaseController.java35
-rw-r--r--webservice/src/main/java/app/market/webservice/app/AppRestController.java485
-rw-r--r--webservice/src/main/java/app/market/webservice/authority/AuthorityRestController.java66
-rw-r--r--webservice/src/main/java/app/market/webservice/dataManager/AppFileController.java255
-rw-r--r--webservice/src/main/java/app/market/webservice/dataManager/FileUtil.java248
-rw-r--r--webservice/src/main/java/app/market/webservice/dataManager/XmlFactory.java43
-rw-r--r--webservice/src/main/java/app/market/webservice/resource/DictionaryRestController.java124
-rw-r--r--webservice/src/main/java/app/market/webservice/resource/ResourceRestController.java71
-rw-r--r--webservice/src/main/java/app/market/webservice/token/TokenRestController.java37
-rw-r--r--webservice/src/main/java/app/market/webservice/user/UserRestController.java482
21 files changed, 2587 insertions, 0 deletions
diff --git a/webservice/src/main/java/app/market/LogUtil.java b/webservice/src/main/java/app/market/LogUtil.java
new file mode 100644
index 0000000..3c626b8
--- /dev/null
+++ b/webservice/src/main/java/app/market/LogUtil.java
@@ -0,0 +1,25 @@
+/*
+ * 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;
+
+import org.slf4j.Logger;
+
+public class LogUtil {
+
+ public static void printCatchLog(final Logger logger, Exception e){
+ //logger.error("Thread.currentThread().getStackTrace()[1].getMethodName()" + e.getMessage());
+ }
+}
diff --git a/webservice/src/main/java/app/market/PropertyUtil.java b/webservice/src/main/java/app/market/PropertyUtil.java
new file mode 100644
index 0000000..4d83c0c
--- /dev/null
+++ b/webservice/src/main/java/app/market/PropertyUtil.java
@@ -0,0 +1,82 @@
+/*
+ * 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;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Properties;
+
+import app.market.utils.constants.Constants;
+
+public class PropertyUtil {
+
+ public static Properties defaultProp;
+ public static Properties fileProp;
+ public static Properties redisProp;
+
+ private static Properties getPropertyInstance(String fileName) {
+ Properties prop = new Properties();
+ try {
+ prop.load(new InputStreamReader(PropertyUtil.class.getClassLoader().getResourceAsStream(fileName),
+ Constants.CHARACTER_UTF8));
+ } catch (FileNotFoundException e) {
+ throw new RuntimeException();
+ } catch (IOException e) {
+ throw new RuntimeException();
+ }
+ return prop;
+ }
+
+ /**
+ * get Redis property
+ *
+ * @param key
+ * @return String
+ */
+ public static String getRedisPropertites(String key) {
+ if (redisProp == null) {
+ redisProp = getPropertyInstance(Constants.PROPERTIES_FILE_NAME_REDIS);
+ }
+ return redisProp.getProperty(key);
+ }
+
+ /**
+ * get file property
+ *
+ * @param key
+ * @return String
+ */
+ public static String getFileManagerPropertites(String key) {
+ if (fileProp == null) {
+ fileProp = getPropertyInstance(Constants.PROPERTIES_FILE_NAME_FILE);
+ }
+ return fileProp.getProperty(key);
+ }
+
+ /**
+ * get propertites
+ *
+ * @param key
+ * @return String
+ */
+ public static String getPropertites(String key) {
+ if (defaultProp == null) {
+ defaultProp = getPropertyInstance(Constants.PROPERTIES_FILE_NAME_DEFAULT);
+ }
+ return defaultProp.getProperty(key);
+ }
+}
diff --git a/webservice/src/main/java/app/market/WebServiceConstants.java b/webservice/src/main/java/app/market/WebServiceConstants.java
new file mode 100644
index 0000000..0416441
--- /dev/null
+++ b/webservice/src/main/java/app/market/WebServiceConstants.java
@@ -0,0 +1,33 @@
+/*
+ * 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;
+
+public class WebServiceConstants {
+
+ /** Time-out */
+ public static final long EXPIRE_TIME_MINUTES = Long.valueOf( PropertyUtil.getRedisPropertites( "redis.timeout" ) );
+ public static final long EXPIRE_TIME_HOURS = Long.valueOf( PropertyUtil.getRedisPropertites( "redis.refreshtimeout" ) );
+
+ public static final String PATTERN_SKIP_LOGIN_AUTHRIZATION = "[A-Za-z0-9_/-]+/login";
+ public static final String PATTERN_SKIP_REFRESHTOKEN_AUTHRIZATION = "[A-Za-z0-9_/-]+/token/[A-Za-z0-9_/:-]+";
+ public static final String PATTERN_RESOURSE_API = "./api/v1/(.*?)[/{*|]\\w";
+ public static final String PATTERN_RESOURSE_S = "/api/v1/";
+ public static final String PATTERN_RESOURSE_PARAM_S = "/{";
+ public static final String SEPARATOR = "/";
+
+ public static final String RESOURSE_TYPE_RES = "resource";
+ public static final String RESOURSE_TYPE_API = "api";
+}
diff --git a/webservice/src/main/java/app/market/common/comm.java b/webservice/src/main/java/app/market/common/comm.java
new file mode 100644
index 0000000..4b200ba
--- /dev/null
+++ b/webservice/src/main/java/app/market/common/comm.java
@@ -0,0 +1,51 @@
+/*
+ * 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.common;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.http.HttpStatus;
+
+import app.market.model.errors.ResponseErrors;
+import app.market.utils.constants.Constants;
+import app.market.utils.json.JsonMapperUtils;
+import app.market.utils.webservice.ErrorCode;
+
+public class comm {
+
+ public static String getResponseError(HttpServletResponse response, int httpCode, ErrorCode errorcode)
+ {
+ //set Response code
+ ResponseErrors errors = new ResponseErrors();
+ response.setStatus(httpCode);
+
+ //set errors message
+ errors.setcode(errorcode.getCodeStr().toString());
+ errors.setMessage(errorcode.getMessage());
+ return JsonMapperUtils.writeValueAsString(errors);
+ }
+
+ public static String getResponseException(HttpServletResponse response, Exception e) {
+ ResponseErrors errors = new ResponseErrors();
+ response.setStatus(Constants.STATUS_ERROR);
+ errors.setcode(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
+ errors.setMessage(e.getMessage());
+ return JsonMapperUtils.writeValueAsString(errors);
+
+ }
+
+
+}
diff --git a/webservice/src/main/java/app/market/token/dao/RedisGeneratorDao.java b/webservice/src/main/java/app/market/token/dao/RedisGeneratorDao.java
new file mode 100644
index 0000000..9b18594
--- /dev/null
+++ b/webservice/src/main/java/app/market/token/dao/RedisGeneratorDao.java
@@ -0,0 +1,48 @@
+/*
+ * 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.token.dao;
+
+import java.io.Serializable;
+
+import javax.annotation.Resource;
+
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.serializer.RedisSerializer;
+
+public abstract class RedisGeneratorDao<K extends Serializable, V extends Object> {
+
+ @Resource(name = "redisTemplate")
+ protected RedisTemplate<K, V> redis;
+
+ /**
+ * set redisTemplate
+ *
+ * @param redisTemplate
+ * the redisTemplate to set
+ */
+ public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
+ this.redis = redisTemplate;
+ }
+
+ /**
+ * get RedisSerializer <br>
+ * ------------------------------<br>
+ */
+ protected RedisSerializer<String> getRedisSerializer() {
+ return redis.getStringSerializer();
+ }
+
+} \ No newline at end of file
diff --git a/webservice/src/main/java/app/market/token/interceptor/AuthenticationTokenInterceptor.java b/webservice/src/main/java/app/market/token/interceptor/AuthenticationTokenInterceptor.java
new file mode 100644
index 0000000..f6993a0
--- /dev/null
+++ b/webservice/src/main/java/app/market/token/interceptor/AuthenticationTokenInterceptor.java
@@ -0,0 +1,65 @@
+/*
+ * 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.token.interceptor;
+
+import java.util.regex.Pattern;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.lang3.StringUtils;
+import org.aspectj.lang.annotation.Aspect;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpMethod;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
+
+import app.market.WebServiceConstants;
+import app.market.token.service.RedisTokenManager;
+import app.market.utils.constants.Constants;
+
+@Aspect
+@Component
+public class AuthenticationTokenInterceptor extends HandlerInterceptorAdapter {
+
+ @Autowired
+ private RedisTokenManager tokenManager;
+
+ @Override
+ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
+ throws Exception {
+
+ if (Pattern.matches(WebServiceConstants.PATTERN_SKIP_LOGIN_AUTHRIZATION, request.getRequestURI())
+ || (Pattern.matches(WebServiceConstants.PATTERN_SKIP_REFRESHTOKEN_AUTHRIZATION, request.getRequestURI())
+ && HttpMethod.GET.name().equals(request.getMethod())))
+ return true;
+
+ // get token from header
+ String authentication = request.getHeader(Constants.TOKEN_AUTHORIZATION);
+ String servletPath = request.getHeader(Constants.TOKEN_AUTHORIZATION_RESOURCE);
+ String url = request.getRequestURI();
+ String httpMethod = request.getMethod();
+
+ // check authentication
+ int status = tokenManager.checkAuthentication(authentication, servletPath, url, httpMethod);
+ if (status != Constants.STATUS_SUCCESS) {
+ response.setStatus(status);
+ return false;
+ }
+ return true;
+ }
+
+}
diff --git a/webservice/src/main/java/app/market/token/service/RedisTokenManager.java b/webservice/src/main/java/app/market/token/service/RedisTokenManager.java
new file mode 100644
index 0000000..aea419e
--- /dev/null
+++ b/webservice/src/main/java/app/market/token/service/RedisTokenManager.java
@@ -0,0 +1,268 @@
+/*
+ * 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.token.service;
+
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+
+import app.market.WebServiceConstants;
+import app.market.model.resource.Resource;
+import app.market.model.user.User;
+import app.market.token.dao.RedisGeneratorDao;
+import app.market.utils.constants.Constants;
+import app.market.utils.token.TokenModel;
+import app.market.utils.webservice.WebServiceURI;
+
+@Component
+public class RedisTokenManager extends RedisGeneratorDao<String, Object> {
+
+ private static Logger logger = LoggerFactory.getLogger( RedisTokenManager.class );
+
+ /**
+ * generate token
+ * @param loginId
+ * @param user
+ * @param list
+ * @param isPermanent guestUser not expire
+ * @return
+ */
+ public TokenModel generateToken(String loginId, User user, List<Resource> list, boolean isPermanent ) {
+ // user UUID as token
+ String token = UUID.randomUUID().toString().replace( "-", "" );
+ TokenModel model = new TokenModel( loginId, user, token );
+ for (Resource res : list) {
+ if ( res.getResType().equals( WebServiceConstants.RESOURSE_TYPE_RES ) ) {
+ model.getResourceList().add( res );
+ } else if ( res.getResType().equals( WebServiceConstants.RESOURSE_TYPE_API ) ) {
+ model.getApiList().add( res );
+ }
+ }
+ // save token, set expire time
+ if(isPermanent){
+ redis.boundValueOps( loginId ).set( model );
+ }else{
+ redis.boundValueOps( loginId ).set( model, WebServiceConstants.EXPIRE_TIME_MINUTES, TimeUnit.MINUTES );
+ }
+ return model;
+ }
+
+
+ public String generateRefreshToken(String loginId) {
+ String token = UUID.randomUUID().toString().replace( "-", "" );
+ redis.boundValueOps( token ).set( loginId, WebServiceConstants.EXPIRE_TIME_HOURS, TimeUnit.HOURS );
+ return token;
+ }
+
+ public int checkAuthentication(String authentication, String servletPath, String url, String httpMethod) {
+ int ret = Constants.STATUS_SUCCESS;
+ if(StringUtils.isEmpty(authentication)){ //guest
+ ret = validateAuthentication(authentication, servletPath, url, httpMethod);
+ }else{
+ ret = validateToken(authentication, servletPath, url, httpMethod);
+ }
+ return ret;
+ }
+
+ /**
+ * check Authentication when guest
+ * @param authentication
+ * @param servletPath
+ * @param httpMethod
+ * @param url
+ * @return
+ */
+ private int validateAuthentication(String authentication, String servletPath, String url, String httpMethod) {
+ int ret = Constants.STATUS_FORBIDDEN;
+ String guestId = Constants.GUEST_ID;
+ TokenModel model = null;
+
+ if (redis.opsForValue().get(guestId) instanceof TokenModel) {
+ model = (TokenModel) redis.opsForValue().get(guestId);
+ }
+
+ if (model == null) {
+ //ResourceRestController.initGuestResoureList(Constants.GUEST_ID);
+ logger.debug( "validateAuthentication" + this.getClass().getName() + "--method: "
+ + Thread.currentThread().getStackTrace()[1].getMethodName() + "model is null" );
+ ret = Constants.STATUS_ERROR;
+ }
+
+ if(checkResoureAuth(model, servletPath, url, httpMethod)) {
+ ret = Constants.STATUS_SUCCESS;
+ }else {
+ ret = Constants.STATUS_FORBIDDEN;
+ }
+
+ return ret;
+ }
+
+ /**
+ * check Authentication when not guest
+ * @param authentication
+ * @param servletPath
+ * @param httpMethod
+ * @param url
+ * @return
+ */
+ private int validateToken(String authentication, String servletPath, String url, String httpMethod) {
+ TokenModel model = getToken( authentication );
+
+ if ( model == null )
+ return Constants.STATUS_UNAUTHORIZED;
+ // Only one account is online as one time
+ if ( !model.getToken().equals( authentication.split( Constants.TOKEN_SEPARATOR )[1] ) ) {
+ return Constants.STATUS_TOO_MANY_CONNECTIONS;
+ }
+ // get cache token
+ TokenModel cacheModel = getCacheModel( model.getLoginId() );
+ // check cache token
+ if ( cacheModel == null )
+ return Constants.STATUS_UNAUTHORIZED;
+
+ String token = cacheModel.getToken();
+ if ( !token.equals( model.getToken() ) )
+ return Constants.STATUS_UNAUTHORIZED;
+
+ if (!checkResoureAuth(cacheModel, servletPath, url, httpMethod)) {
+ return Constants.STATUS_FORBIDDEN;
+ }
+
+ // check ok, reset expire time
+ redis.boundValueOps( model.getLoginId() ).expire( WebServiceConstants.EXPIRE_TIME_MINUTES, TimeUnit.SECONDS );
+ return Constants.STATUS_SUCCESS;
+ }
+
+ /**
+ *
+ * @param list
+ * @param resPath
+ * @return
+ */
+ private boolean checkResoureAuth(TokenModel model, String resPath, String url, String httpMethod) {
+ boolean ret = false;
+
+ if (StringUtils.isEmpty(resPath) && !url.contains(WebServiceURI.REST_TOKEN_VALIDATETOKENAUTHORTICATION_LF)) { //URL check
+
+ int s = url.indexOf(WebServiceConstants.PATTERN_RESOURSE_S);
+ if (s < 0) {
+ return ret;
+ }
+ resPath = url.substring(s + WebServiceConstants.PATTERN_RESOURSE_S.length()-1);
+ if (resPath.endsWith(WebServiceConstants.SEPARATOR)) {
+ resPath = resPath.substring(0, resPath.length() - 1);
+ }
+
+ int count = (resPath.split(WebServiceConstants.SEPARATOR)).length;
+
+ List<Object> list = model.getApiList();
+ for (Object obj : list) {
+ Resource r = (Resource) obj;
+
+ //httpmethod check
+ if (!r.getHttpMethod().equalsIgnoreCase(httpMethod)){
+ continue;
+ }
+
+ //url length check
+ if(count != r.getAccessPath().split(WebServiceConstants.SEPARATOR).length) {
+ continue;
+ }
+
+ String rUrl = r.getAccessPath();
+ //delete param depart of url
+ int paramS = r.getAccessPath().indexOf(WebServiceConstants.PATTERN_RESOURSE_PARAM_S);
+ if (paramS > 0) {
+ rUrl = r.getAccessPath().substring(0, paramS);
+ }
+
+ //url check
+ if (resPath.indexOf(rUrl) == 0) {
+ ret = true;
+ break;
+ }
+ }
+
+ } else if(url.contains(WebServiceURI.REST_TOKEN_VALIDATETOKENAUTHORTICATION_LF)){
+ // temp code
+ ret = true;
+ } else {//For web selertPath check;
+ List<Object> list = model.getResourceList();
+ for (Object obj : list) {
+ Resource res = (Resource) obj;
+ if (res.getAccessPath().contains(resPath)) {
+ ret = true;
+ break;
+ }
+ }
+ }
+ return ret;
+ }
+
+ public TokenModel getToken(String authentication) {
+ String loginId ="";
+ if (StringUtils.isEmpty(authentication)) {
+ loginId = Constants.GUEST_ID;
+ } else {
+ String[] param = authentication.split(Constants.TOKEN_SEPARATOR);
+ if (param.length != 2){
+ return null;
+ }
+ loginId = param[0];
+ }
+ TokenModel model = null;
+ if (redis.opsForValue().get(loginId) instanceof TokenModel) {
+ model = (TokenModel) redis.opsForValue().get(loginId);
+ }
+ return model;
+ }
+
+ public TokenModel getCacheModel(String loginId) {
+ try {
+ return (TokenModel) redis.boundValueOps( loginId ).get();
+ } catch ( Exception e ) {
+ return null;
+ }
+ }
+
+ public String getRefreshtokenValue(String authentication) {
+ if (StringUtils.isEmpty(authentication)) {
+ return null;
+ }
+ String[] param = authentication.split(Constants.TOKEN_SEPARATOR);
+ if (param.length != 2){
+ return null;
+ }
+ String loginId = (String) redis.opsForValue().get(param[1]);
+
+ return loginId;
+ }
+
+ public void updateTokenInfo(TokenModel model) {
+ redis.boundValueOps( model.getLoginId() ).set( model, WebServiceConstants.EXPIRE_TIME_MINUTES,
+ TimeUnit.MINUTES );
+ }
+
+ public void deleteToken(String loginId) {
+ redis.delete( loginId );
+ }
+
+}
diff --git a/webservice/src/main/java/app/market/webservice/Filter.java b/webservice/src/main/java/app/market/webservice/Filter.java
new file mode 100644
index 0000000..de92006
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/Filter.java
@@ -0,0 +1,40 @@
+/*
+ * 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;
+
+import java.io.IOException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import app.market.utils.constants.Constants;
+
+public class Filter extends OncePerRequestFilter {
+
+ @Override
+ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
+ throws ServletException, IOException {
+ request.setCharacterEncoding( Constants.CHARACTER_UTF8 );
+ response.setCharacterEncoding( Constants.CHARACTER_UTF8 );
+ filterChain.doFilter( request, response );
+
+ }
+
+}
diff --git a/webservice/src/main/java/app/market/webservice/InitServer.java b/webservice/src/main/java/app/market/webservice/InitServer.java
new file mode 100644
index 0000000..92f7f6b
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/InitServer.java
@@ -0,0 +1,52 @@
+/*
+ * 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;
+
+import java.util.List;
+
+import javax.servlet.ServletContext;
+
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.web.context.ServletContextAware;
+
+import app.market.core.resource.ResourceCore;
+import app.market.token.service.RedisTokenManager;
+import app.market.utils.constants.Constants;
+
+@Service
+public class InitServer implements InitializingBean, ServletContextAware {
+
+ @Autowired
+ private RedisTokenManager tokenManager;
+
+ @Autowired
+ private ResourceCore resourceCore;
+
+ @Override
+ public void setServletContext(ServletContext arg0) {
+ List<app.market.model.resource.Resource> list = resourceCore.selectResourcesByLoginId( Constants.GUEST_ID );
+ tokenManager.generateToken( Constants.GUEST_ID, null, list, true );
+ }
+
+ @Override
+ public void afterPropertiesSet() throws Exception {
+ // TODO Auto-generated method stub
+
+ }
+
+}
diff --git a/webservice/src/main/java/app/market/webservice/Log4jlistener.java b/webservice/src/main/java/app/market/webservice/Log4jlistener.java
new file mode 100644
index 0000000..9dee500
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/Log4jlistener.java
@@ -0,0 +1,53 @@
+/*
+ * 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;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Enumeration;
+import java.util.Properties;
+
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+
+public class Log4jlistener implements ServletContextListener {
+
+ public void contextDestroyed(ServletContextEvent servletcontextevent) {
+ // System.getProperties().clear();
+ }
+
+ public void contextInitialized(ServletContextEvent servletcontextevent) {
+ Properties prop = new Properties();
+ try {
+ prop.load( new InputStreamReader(
+ Log4jlistener.class.getClassLoader().getResourceAsStream( "properties.properties" ) ) );
+ } catch ( IOException e ) {
+ e.printStackTrace();
+ }
+ Enumeration<Object> e = prop.keys();
+ while ( e.hasMoreElements() ) {
+ String key = e.nextElement().toString();
+ String path = prop.getProperty( key );
+ System.setProperty( key, path );
+ File f = new File( path );
+ if ( !f.getParentFile().exists() ) {
+ f.getParentFile().mkdirs();
+ }
+ }
+ }
+
+}
diff --git a/webservice/src/main/java/app/market/webservice/WebServiceClient.java b/webservice/src/main/java/app/market/webservice/WebServiceClient.java
new file mode 100644
index 0000000..39b63f2
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/WebServiceClient.java
@@ -0,0 +1,24 @@
+/*
+ * 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;
+
+import app.market.utils.property.PropertyUtil;
+
+public class WebServiceClient {
+
+ public static final String REST_SERVICE_URI = PropertyUtil.getPropertites( "webservice_base_uri" );
+
+}
diff --git a/webservice/src/main/java/app/market/webservice/WebserviceRestBaseController.java b/webservice/src/main/java/app/market/webservice/WebserviceRestBaseController.java
new file mode 100644
index 0000000..1f9351c
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/WebserviceRestBaseController.java
@@ -0,0 +1,35 @@
+/*
+ * 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;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.web.servlet.HandlerExceptionResolver;
+import org.springframework.web.servlet.ModelAndView;
+
+public class WebserviceRestBaseController implements HandlerExceptionResolver {
+
+ protected static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";
+
+ @Override
+ public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
+ Exception ex) {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
diff --git a/webservice/src/main/java/app/market/webservice/app/AppRestController.java b/webservice/src/main/java/app/market/webservice/app/AppRestController.java
new file mode 100644
index 0000000..25b5d68
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/app/AppRestController.java
@@ -0,0 +1,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;
+ }
+}
diff --git a/webservice/src/main/java/app/market/webservice/authority/AuthorityRestController.java b/webservice/src/main/java/app/market/webservice/authority/AuthorityRestController.java
new file mode 100644
index 0000000..868fa63
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/authority/AuthorityRestController.java
@@ -0,0 +1,66 @@
+/*
+ * 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.authority;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletResponse;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import app.market.common.comm;
+import app.market.core.authority.AuthorityCore;
+import app.market.utils.json.JsonMapperUtils;
+import app.market.utils.property.Option;
+import app.market.utils.webservice.WebServiceURI;
+import app.market.webservice.WebserviceRestBaseController;
+
+@RestController
+public class AuthorityRestController extends WebserviceRestBaseController {
+
+ private static Logger logger = LoggerFactory.getLogger( AuthorityRestController.class );
+
+ @Autowired
+ private AuthorityCore authorityCore;
+
+ /**
+ * get authority list
+ *
+ * @param userExample
+ * @return
+ */
+ @RequestMapping(value = WebServiceURI.REST_AUTHORITY_GET_LIST_OPTION_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String selectAuthorityListOption(HttpServletResponse response) {
+ logger.debug(" selectAuthorityListOption --S--");
+ String responseStr = null;
+
+ try {
+ List<Option> auList = authorityCore.getAuListOption();
+ responseStr = JsonMapperUtils.writeValueAsString(auList);
+ } catch (Exception e) {
+ responseStr = comm.getResponseException(response, e);
+ }
+
+ logger.debug("selectAuthorityListOption --E--");
+ return responseStr;
+ }
+
+}
diff --git a/webservice/src/main/java/app/market/webservice/dataManager/AppFileController.java b/webservice/src/main/java/app/market/webservice/dataManager/AppFileController.java
new file mode 100644
index 0000000..8a24a58
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/dataManager/AppFileController.java
@@ -0,0 +1,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;
+ }
+
+}
diff --git a/webservice/src/main/java/app/market/webservice/dataManager/FileUtil.java b/webservice/src/main/java/app/market/webservice/dataManager/FileUtil.java
new file mode 100644
index 0000000..5018e89
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/dataManager/FileUtil.java
@@ -0,0 +1,248 @@
+/*
+ * 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.io.File;
+import java.io.FileNotFoundException;
+import java.io.UnsupportedEncodingException;
+import java.util.UUID;
+
+import org.apache.commons.lang3.StringUtils;
+import org.dom4j.Document;
+import org.dom4j.Element;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import app.market.PropertyUtil;
+
+import app.market.model.app.FileInfo;
+import app.market.utils.RuntimeUtil;
+import app.market.utils.Utils;
+import app.market.utils.constants.Constants;
+import app.market.utils.datetime.DateTimeUtils;
+
+public class FileUtil {
+ private static Logger logger = LoggerFactory.getLogger(FileUtil.class);// TODO DJ log确认要不要打,要打的话按照等级来做,catch中error,有可能出错的地方warn,其他的info
+
+ /**
+ *
+ * @param type
+ * @param appId
+ * @return
+ */
+ public static String getUploadPath(String path) {
+ String dir = "";
+
+ String uploadPath = PropertyUtil.getFileManagerPropertites("upload_path");
+ if (StringUtils.isEmpty(uploadPath)) {
+ uploadPath = Constants.UPLOAD_PATH_DEFAULT;
+ }
+
+ dir = uploadPath + path;
+ File file = new File(dir);
+ if (!file.exists()) {
+ file.mkdirs();
+ }
+
+ return dir;
+ }
+
+ /**
+ * relative path
+ * @param type
+ * @param appId
+ * @return
+ */
+ public static String getAppPath(String type, String appId){
+ if (Utils.strIsEmpty(type)) {
+ type = Constants.UPLOAD_PATH_TYPE_DEFAULT;
+ }
+ if (Utils.strIsEmpty(appId)) {
+ appId = Constants.UPLOAD_PATH_APP_DEFAULT;
+ }
+
+ String path = Constants.UPLOAD_APP_FILE_PATH + Constants.PATH_SEPARATOR
+ + type + Constants.PATH_SEPARATOR
+ + appId + Constants.PATH_SEPARATOR;
+ return path;
+ }
+
+ /***
+ *
+ * @param orgfilename
+ * @return
+ */
+ public static String createFileName(String orgfilename) {
+ String fileName = UUID.randomUUID().toString();
+
+ if(StringUtils.isNotEmpty(orgfilename)){
+ fileName += Constants.FILE_SEPARATOR + orgfilename;
+ }
+
+ return fileName;
+ }
+
+ /***
+ * generate file name
+ * @param path
+ * @return orgfileName
+ */
+ public static String getOrgFileName(String path) {
+ String orgfileName = path;
+ //String fileName = path.substring(path.lastIndexOf(Constants.PATH_SEPARATOR) + 1);
+ String fileName = Utils.getFileNameFromPath(path);
+ if(fileName != null){
+ try {
+ int separatorIndex = UUID.randomUUID().toString().length() + Constants.FILE_SEPARATOR.length();
+ orgfileName = fileName.substring(separatorIndex);
+ } catch (Exception e) {
+ logger.debug("getOrgFileName:"+e.getMessage());
+ }
+ }
+ return orgfileName;
+ }
+
+ public static String encodeStr(String str) {
+ try {
+ return new String(str.getBytes(Constants.CHARACTER_ISO), Constants.CHARACTER_UTF8);
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ /**
+ * Uncompress File
+ * @param filePath:Compress File's Ordinary Path
+ * @return uncompressPath: Be Uncompressed File's Temperature Save Path
+ * @throws Exception
+ */
+ public static String uncompress(String filePath) throws Exception {
+ String ret = null;
+ String nowTime =DateTimeUtils.getCurrectDate(DateTimeUtils.DATE_FORMAT_YYYYMMDDHHMMSS);
+ String uncompressPath= getUploadPath(Constants.UPLOAD_APP_UNCOMPRESS_PATH) + Constants.PATH_SEPARATOR + nowTime;
+
+ String cmd = "unzip " + filePath + " -d " + uncompressPath;
+
+ if(RuntimeUtil.linuxCmdExec(cmd)) {
+ ret = uncompressPath;
+ }
+ return ret;
+ }
+
+ /**
+ * XML File Parse
+ * @param path:Be Uncompressed File's Temperature Save Path
+ * @param fileInfo
+ */
+ public static void parseConfigInfo(String path, FileInfo fileInfo) {
+ String configId ="";
+ String configVersionName="";
+ String configAppName = "";
+ String iconPath = "";
+ try {
+ Document doc = XmlFactory.parse(path + Constants.UPLOAD_APP_UNCOMPRESS_FILE_CONFIG);
+ Element root = doc.getRootElement();
+
+ configId = root.attributeValue(Constants.CONFIG_APP_PARAM_ID);
+ configVersionName = root.attributeValue(Constants.CONFIG_APP_PARAM_VERSION);
+ configAppName = root.elementText(Constants.CONFIG_APP_PARAM_NAME);
+ if (root.element(Constants.CONFIG_APP_PARAM_ICON) != null) {
+ iconPath = root.element(Constants.CONFIG_APP_PARAM_ICON).attributeValue(Constants.CONFIG_APP_PARAM_SRC);
+ }
+
+ logger.debug("iconPath="+iconPath);
+ } catch (Exception e) {
+ logger.debug("getConfigInfo"+e.getMessage());
+ }
+ fileInfo.setConfigAppId(configId);
+ fileInfo.setConfigVersionName(configVersionName);
+ fileInfo.setConfigAppName(configAppName);
+ fileInfo.setIconPath(iconPath);
+ }
+
+ /**
+ * save icon path
+ * @param path:Be Uncompressed File's Temperature Save Path
+ * @param iconPath:icon's name in config.xml file
+ * @throws FileNotFoundException
+ * @return Icon's Save Path to server
+ */
+ public static String saveAppIcon(String path, String iconPath) throws FileNotFoundException {
+ String ret = "";
+ String orgPath = path + Constants.PATH_SEPARATOR + iconPath;
+ String destPath = getImagePath(iconPath);
+
+ logger.debug("destPath=" + destPath);
+ logger.debug("orgPath=" + orgPath);
+
+ String cmd = "cp " + orgPath + " " + destPath;
+ logger.debug("cp_cmd=" + cmd);
+
+ if(RuntimeUtil.linuxCmdExec(cmd)) {
+ ret = FileUtil.getImageAccessPath(destPath);//http:\\\\localhost:8080\\resource/appIcon/xxxxx.png
+ logger.debug("cp_ret=" + ret);
+ }
+ return ret;
+ }
+
+ /**
+ * get icon path
+ * @param filename:Icon's name
+ * @return Relative Path :appIcon/xxxxx.png
+ */
+ public static String getImagePath(String filename) {
+ //get image file name
+ if(filename.contains(Constants.PATH_SEPARATOR)) {
+ //filename = filename.substring(filename.lastIndexOf(Constants.PATH_SEPARATOR) + 1);
+ filename = Utils.getFileNameFromPath(filename);
+ }
+
+ String imagePath = getUploadPath(Constants.UPLOAD_APP_RES_PATH_ICON);
+
+ String fullPath = imagePath + Constants.PATH_SEPARATOR + createFileName(filename);
+ return fullPath;
+ }
+
+ /**
+ * getImageAccessPath
+ * @param fullFilePath
+ * @return
+ */
+ public static String getImageAccessPath(String fullFilePath) {
+ String basePath = getUploadPath("");
+ String httpPathHeader = PropertyUtil.getFileManagerPropertites("upload_icon_path");
+ String path = fullFilePath.replace(basePath, httpPathHeader);
+
+ logger.debug("getImageAccessPath=" + path);
+ return path;
+ }
+
+ /**
+ *
+ * @param filePath:Be Uncompressed File's Temperature Save Path
+ * @return result
+ */
+ public static int removeFile(String filePath) {
+ String cmd = "rm -rf " + filePath;
+ int ret = 0;
+ System.out.println(cmd);
+ if(RuntimeUtil.linuxCmdExec(cmd)) {
+ ret = 1;
+ }
+ return ret;
+ }
+}
diff --git a/webservice/src/main/java/app/market/webservice/dataManager/XmlFactory.java b/webservice/src/main/java/app/market/webservice/dataManager/XmlFactory.java
new file mode 100644
index 0000000..489a6da
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/dataManager/XmlFactory.java
@@ -0,0 +1,43 @@
+/*
+ * 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.net.URL;
+
+import org.dom4j.Document;
+import org.dom4j.DocumentException;
+import org.dom4j.io.SAXReader;
+
+public class XmlFactory {
+
+ public Document parse(URL url) throws DocumentException {
+ SAXReader reader = new SAXReader();
+ Document document = reader.read(url);
+ return document;
+ }
+
+ // load local xml file
+ public static Document parse(String path) {
+ SAXReader reader = new SAXReader();
+ Document document = null;
+ try {
+ document = reader.read(path);
+ } catch (DocumentException e) {
+ e.printStackTrace();
+ }
+ return document;
+ }
+}
diff --git a/webservice/src/main/java/app/market/webservice/resource/DictionaryRestController.java b/webservice/src/main/java/app/market/webservice/resource/DictionaryRestController.java
new file mode 100644
index 0000000..d7d8253
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/resource/DictionaryRestController.java
@@ -0,0 +1,124 @@
+/*
+ * 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.resource;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+
+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.http.HttpStatus;
+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.RestController;
+
+import app.market.common.comm;
+import app.market.core.resource.DictionaryCore;
+import app.market.model.errors.ResponseErrors;
+import app.market.model.resource.Dictionary;
+import app.market.model.resource.DictionaryExample;
+import app.market.model.resource.DictionaryExample.Criteria;
+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 DictionaryRestController extends WebserviceRestBaseController {
+
+ private static Logger logger = LoggerFactory.getLogger(DictionaryRestController.class);
+
+ @Autowired
+ private DictionaryCore dicCore;
+
+ @RequestMapping(value = WebServiceURI.REST_DICTIONARY_COLLECTION_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String selectDictionary(@PathVariable(ApiParam.API_APP_PARAM_DICTIONARY_TYPEID) String dicTypeId,
+ HttpServletResponse response) {
+ ResponseErrors errors = new ResponseErrors();
+ String responseStr = null;
+
+ try {
+ List<Dictionary> dic = dicCore.selectItemsByTypeId(dicTypeId);
+ responseStr = JsonMapperUtils.writeValueAsString(dic);
+ } catch (Exception e) {
+ response.setStatus(Constants.STATUS_ERROR);
+ errors.setcode(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
+ errors.setMessage(e.getMessage());
+ }
+
+ if (StringUtils.isEmpty(responseStr)) {
+ responseStr = JsonMapperUtils.writeValueAsString(errors);
+ }
+
+ logger.debug("IDにより、アプリ情報を検索 --E-- appId=" + dicTypeId);
+ return responseStr;
+ }
+
+ /**
+ * Add Or Update Type/Device Type
+ * @return
+ */
+ @RequestMapping(value = WebServiceURI.REST_DICTIONARY_INFO_LF, method = RequestMethod.POST, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String saveDictionary(@RequestBody Dictionary record, HttpServletResponse response) {
+ String responseStr = null;
+ try {
+ //Verify whether the name has already existed.
+ DictionaryExample verifyLabel = new DictionaryExample();
+ Criteria verify = verifyLabel.createCriteria();
+ verify.andDicLabelEqualTo(record.getDicLabel());
+ verify.andDicTypeEqualTo(record.getDicType());
+ int num = dicCore.countByExample(verifyLabel);
+ //Name has already existed.
+ if (num > 0) {
+ responseStr = comm.getResponseError(response, Constants.STATUS_ALREADY_EXISTS,
+ new ErrorCode(ErrorCodeEnum.TYPENAME_ALREADY_EXISTS, KeysConstants.TYPENAME_ALREADY_EXISTS));
+ return responseStr;
+ }
+ if (StringUtils.isEmpty(record.getDicValue())) {
+ // create new type
+ int i = dicCore.insert(record);
+ if (i == 1) {
+ responseStr = JsonMapperUtils.writeValueAsString(i);
+ }
+ } else {
+ // update type
+ DictionaryExample example = new DictionaryExample();
+ Criteria uc = example.createCriteria();
+ uc.andDicValueEqualTo(record.getDicValue());
+ uc.andDicTypeEqualTo(record.getDicType());
+ int i = dicCore.updateByExample(record, example);
+ if (i == 1) {
+ responseStr = JsonMapperUtils.writeValueAsString(i);
+ }
+ }
+ } catch (Exception e) {
+ responseStr = comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
+ new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM,KeysConstants.MISSING_NECESSARY_QUERYPARAM));
+ }
+ return responseStr;
+
+ }
+}
diff --git a/webservice/src/main/java/app/market/webservice/resource/ResourceRestController.java b/webservice/src/main/java/app/market/webservice/resource/ResourceRestController.java
new file mode 100644
index 0000000..7b6de02
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/resource/ResourceRestController.java
@@ -0,0 +1,71 @@
+/*
+ * 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.resource;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import app.market.LogUtil;
+import app.market.core.resource.ResourceCore;
+import app.market.model.resource.Resource;
+import app.market.token.service.RedisTokenManager;
+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.token.TokenModel;
+import app.market.utils.webservice.WebServiceURI;
+import app.market.webservice.WebserviceRestBaseController;
+
+@RestController
+public class ResourceRestController extends WebserviceRestBaseController {
+
+ private static Logger logger = LoggerFactory.getLogger(ResourceRestController.class);
+
+ @Autowired
+ private RedisTokenManager tokenManager;
+
+ @Autowired
+ private ResourceCore resourceCore;
+
+ @RequestMapping(value = WebServiceURI.REST_RESOURCE_GET_MENU_RESOURCES_BY_LOGINID_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String selectMenuResourceByLoginId(@RequestHeader(Constants.TOKEN_AUTHORIZATION) String token) {
+ JsonResult jr = new JsonResult();
+ try {
+ // read cache resource
+ TokenModel model = tokenManager.getToken( token );
+ List<Resource> list = new ArrayList<Resource>();
+ for (Object obj : model.getResourceList()) {
+ list.add( (Resource) obj );
+ }
+ jr.setData( JsonMapperUtils.writeValueAsString( list ) );
+ } catch ( Exception e ) {
+ LogUtil.printCatchLog(logger, e);
+ jr.setData( MessageUtil.getPropertites( KeysConstants.PROJECT_ERROR ) );
+ jr.setStatus( Constants.STATUS_ERROR );
+ }
+ return JsonMapperUtils.writeValueAsString( jr );
+ }
+}
diff --git a/webservice/src/main/java/app/market/webservice/token/TokenRestController.java b/webservice/src/main/java/app/market/webservice/token/TokenRestController.java
new file mode 100644
index 0000000..5ddd915
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/token/TokenRestController.java
@@ -0,0 +1,37 @@
+/*
+ * 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.token;
+
+import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+import app.market.utils.constants.Constants;
+import app.market.utils.json.JsonMapperUtils;
+import app.market.utils.json.JsonResult;
+import app.market.utils.webservice.WebServiceURI;
+import app.market.webservice.WebserviceRestBaseController;
+
+@RestController
+public class TokenRestController extends WebserviceRestBaseController {
+
+ @RequestMapping(value = WebServiceURI.REST_TOKEN_VALIDATETOKENAUTHORTICATION_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String validateTokenAuthortication(@RequestHeader(Constants.TOKEN_AUTHORIZATION) String token) {
+ return JsonMapperUtils.writeValueAsString( new JsonResult() );
+ }
+
+}
diff --git a/webservice/src/main/java/app/market/webservice/user/UserRestController.java b/webservice/src/main/java/app/market/webservice/user/UserRestController.java
new file mode 100644
index 0000000..199d28e
--- /dev/null
+++ b/webservice/src/main/java/app/market/webservice/user/UserRestController.java
@@ -0,0 +1,482 @@
+/*
+ * 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.user;
+
+import java.text.ParseException;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+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.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestHeader;
+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.LogUtil;
+import app.market.common.comm;
+import app.market.core.app.AppCore;
+import app.market.core.resource.ResourceCore;
+import app.market.core.user.UserCore;
+import app.market.model.app.AppExample;
+import app.market.model.resource.Resource;
+import app.market.model.user.User;
+import app.market.model.user.UserExample;
+import app.market.model.user.UserExample.Criteria;
+import app.market.token.service.RedisTokenManager;
+import app.market.utils.constants.Constants;
+import app.market.utils.datetime.DateTimeUtils;
+import app.market.utils.json.JsonMapperUtils;
+import app.market.utils.json.JsonResult;
+import app.market.utils.property.KeysConstants;
+import app.market.utils.token.TokenModel;
+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 UserRestController extends WebserviceRestBaseController {
+
+ private static Logger logger = LoggerFactory.getLogger( UserRestController.class );
+ @Autowired
+ private AppCore appCore;
+
+ @Autowired
+ private UserCore userCore;
+
+ @Autowired
+ private ResourceCore resourceCore;
+
+ @Autowired
+ private RedisTokenManager tokenManager;
+
+ /**
+ * login
+ *
+ * @return
+ */
+ @RequestMapping(value = WebServiceURI.REST_USER_SELECTLOGINUSER_LF, method = RequestMethod.POST, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String selectLoginUser(@RequestBody String requestJson, HttpServletResponse response) {
+ logger.debug("login RequestBody:" + requestJson);
+
+ JSONObject jObj = JsonMapperUtils.getJsonObject(requestJson);
+ String loginId = jObj.getString(ApiParam.API_APP_PARAM_LOGINID);
+ String userPw = jObj.getString(ApiParam.API_APP_PARAM_PASSWORD);
+
+ // get token from cache
+ if (tokenManager.getCacheModel(loginId) != null) {
+ // again login
+ tokenManager.deleteToken(loginId);
+ }
+
+ JSONObject responseData = new JSONObject();
+ String responseStr = null;
+
+ UserExample userExample = new UserExample();
+ Criteria uc = userExample.createCriteria();
+ uc.andUserNameEqualTo(loginId);
+ uc.andUserPwEqualTo(userPw);
+
+ try {
+ // get user information
+ User user = userCore.selectByExample(userExample);
+ responseStr = generateToken(user, loginId, false);
+ if (responseStr != null) {
+ response.setStatus(Constants.STATUS_SUCCESS);
+ } else {
+ responseStr = comm.getResponseError(response, Constants.STATUS_UNAUTHORIZED,
+ new ErrorCode(ErrorCodeEnum.LOGIN_FAILD,KeysConstants.LOGIN_LOGINID_IS_NOT_EXIST));
+ }
+ } catch (Exception e) {
+ responseStr = comm.getResponseException(response, e);
+ }
+
+ logger.debug("login done,loginId:" + loginId);
+ return responseStr;
+ }
+
+ /**
+ * get access token
+ * @param refreshToken
+ * @param response
+ * @return
+ */
+ @RequestMapping(value = WebServiceURI.REST_TOKEN_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String getAccessToken(@PathVariable(ApiParam.API_APP_PARAM_REFRESHTOKEN) String refreshToken, HttpServletResponse response) {
+ logger.debug("getAccessToken refreshToken:" + refreshToken);
+
+ String responseStr = null;
+ String loginId = tokenManager.getRefreshtokenValue(refreshToken);
+
+ if (loginId == null) {
+ responseStr = comm.getResponseError(response, Constants.STATUS_UNAUTHORIZED,
+ new ErrorCode(ErrorCodeEnum.EXPIRED_REFRESH_TOKEN, KeysConstants.EXPIRED_REFRESH_TOKEN));
+ return responseStr;
+ }
+
+ try {
+ User user = userCore.selectUserByUserName(loginId);
+ //user.setUserPw("");
+ responseStr = generateToken(user, loginId, true);
+ if (responseStr != null) {
+ response.setStatus(Constants.STATUS_SUCCESS);
+ } else {
+ responseStr = comm.getResponseError(response, Constants.STATUS_UNAUTHORIZED,
+ new ErrorCode(ErrorCodeEnum.EXPIRED_REFRESH_TOKEN,KeysConstants.EXPIRED_REFRESH_TOKEN));
+ }
+ } catch (Exception e) {
+ responseStr = comm.getResponseException(response, e);
+ }
+
+ logger.debug("getAccessToken loginId:" + loginId);
+ return responseStr;
+ }
+
+ /**
+ * get user collection
+ *
+ * @param userName
+ * @param mail
+ * @param sort
+ * @param order
+ * @param offset
+ * @param limit
+ * @return
+ * @throws ParseException
+ */
+ @RequestMapping(value = WebServiceURI.REST_USER_SELECTPAGINATIONDATABYEXAMPLE_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String selectPaginationDataByExample(
+ @RequestParam(value = ApiParam.API_USER_PARAM_CREATEDATE, required = false, defaultValue = "") String createDate,
+ @RequestParam(value = ApiParam.API_USER_PARAM_AUID, required = false, defaultValue = "") String auId,
+ @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 = "") Integer offset,
+ @RequestParam(value = ApiParam.API_PARAM_LIMIT, required = false, defaultValue = "") Integer limit,
+ @RequestParam(value = ApiParam.API_APP_PARAM_KEYWORD, required = false, defaultValue = "") String keyWord
+ , HttpServletResponse response)
+ {
+ logger.debug("get user collection --S--");
+ if ((!ApiParam.API_PARAM_VALUE_ORDER_ASC.equalsIgnoreCase(order)&& !ApiParam.API_PARAM_VALUE_ORDER_DESC.equalsIgnoreCase(order))
+ || (ApiParam.UserQueryParam.get(sort) == null)
+ || limit < Integer.valueOf(ApiParam.API_PARAM_CRITICAL_LIMIT_MIN) || offset < Integer.valueOf(ApiParam.API_PARAM_DEFAULT_OFFSET)) {
+ return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
+ new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM, KeysConstants.STATUS_BAD_REQUEST));
+ }
+
+ UserExample example = getSearchExample(auId, createDate, keyWord, sort, order);
+
+ String responseStr = null;
+ Map<String, Object> map = new HashMap<String, Object>();
+
+ try {
+ int counter = userCore.countByExample( example );
+ List<User> list = userCore.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 user collection --E--");
+ return responseStr;
+ }
+
+ private UserExample getSearchExample(String auId, String createDate, String keyWord, String sort, String order) {
+ UserExample example = new UserExample();
+
+ //set or condition
+ if (StringUtils.isNotEmpty(keyWord)) {
+ String likeKeyWord = "%" + keyWord + "%";
+
+ Criteria ucName = example.createCriteria();
+ setAndCondition(ucName, auId, createDate);
+ ucName.andUserNameLike(likeKeyWord);
+
+ Criteria ucMail = example.createCriteria();
+ setAndCondition(ucMail, auId, createDate);
+ ucMail.andMailAddressLike(likeKeyWord);
+ example.or(ucMail);
+ }else{
+ Criteria uc = example.createCriteria();
+ setAndCondition(uc, auId, createDate);
+ }
+
+ // set sort and order
+ String sortName = ApiParam.UserQueryParam.get(sort);
+ if (StringUtils.isNotEmpty(sortName)) {
+ example.setOrderByClause(sortName + " " + order);
+ }
+ return example;
+ }
+
+ /**
+ *
+ * @param uc
+ * @param auId
+ * @param createDate
+ * @param deviceTypeId
+ * @param isPublic
+ * @param appTypeId
+ */
+ private void setAndCondition(Criteria uc, String auId, String createDate)
+ {
+ uc.andIsDelEqualTo( Constants.DATA_VALID );
+ uc.andUserNameNotEqualTo(Constants.GUEST_ID);
+ uc.andUserNameNotEqualTo(Constants.ADMID_ID);
+ if ( StringUtils.isNotEmpty( auId ) ) {
+ uc.andAuIdEqualTo( auId );
+ }
+ if (StringUtils.isNotEmpty( createDate ) ) {
+ Date endDate = DateTimeUtils.getDate(DateTimeUtils.DATE_FORMAT_YYYYMMDD,DateTimeUtils.betweenTime(createDate));
+ Date beginDate = DateTimeUtils.getDate(DateTimeUtils.DATE_FORMAT_YYYYMMDD,createDate);
+ uc.andCreateDateBetween(beginDate, endDate);
+ }
+ }
+
+ /**
+ * get user information from id
+ *
+ * @return
+ */
+ @RequestMapping(value = WebServiceURI.REST_USER_BY_USERID_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String selectUserByUserId(@PathVariable("userId") String userId
+ , HttpServletResponse response) {
+ logger.debug("get user information from id --S-- userId=" + userId);
+ String responseStr = "";
+
+ try {
+ User user = userCore.selectUserByUserId( userId );
+ if(user == null){
+ return responseStr;
+ }
+ responseStr = JsonMapperUtils.writeValueAsString(user);
+ } catch (Exception e) {
+ responseStr = comm.getResponseException(response, e);
+ }
+
+ logger.debug("get user information from id --E-- userId=" + userId);
+ return responseStr;
+ }
+
+ /**
+ * get current user
+ *
+ * @return
+ */
+ @RequestMapping(value = WebServiceURI.REST_USER_SELECT_CURRENT_LF, method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String selectCurrentUser(@RequestHeader(Constants.TOKEN_AUTHORIZATION) String token) {
+ logger.debug( "get current user start, token=" + token );
+ JsonResult jr = new JsonResult();
+ try {
+ TokenModel tokenModel = tokenManager.getToken( token );
+ User user = (User) tokenModel.getUserEntity();
+ jr.setData( JsonMapperUtils.writeValueAsString( user ) );
+ } catch ( Exception e ) {
+ LogUtil.printCatchLog(logger, e);
+ jr.setData( e.getMessage() );
+ jr.setStatus( Constants.STATUS_ERROR );
+ }
+ logger.debug( "get current user done, token=" + token );
+ return JsonMapperUtils.writeValueAsString( jr );
+ }
+
+ /**
+ * save user information
+ *
+ * @param user
+ * @return
+ */
+ @RequestMapping(value = WebServiceURI.REST_USER_LF, method = RequestMethod.POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String saveUser(@RequestBody String jsonStr, HttpServletResponse response) {
+ logger.debug( "save user start, user=" + jsonStr.toString() );
+
+ if(StringUtils.isEmpty(jsonStr)){
+ return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
+ new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM,KeysConstants.INVALID_QUERYPARAM));
+ }
+
+ User user = JsonMapperUtils.readValue(jsonStr, User.class);
+ if(user == null){
+ return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
+ new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM,KeysConstants.INVALID_QUERYPARAM));
+ }
+
+ //createDate and updateDate
+ Date date = new Date();
+ if(user.getUserId().isEmpty()){
+ user.setCreateDate(date);
+ user.setUpdateDate(date);
+ }else{
+ user.setUpdateDate(date);
+ }
+ //check parameter
+ ErrorCode paramCheckResult = checkParamSave(user);
+ if (paramCheckResult != null) {
+ return comm.getResponseError(response, Constants.STATUS_BAD_REQUEST, paramCheckResult);
+ }
+ user.setIsDel(Constants.DATA_VALID);
+
+ JSONObject responseData = new JSONObject();
+ String responseStr = null;
+ try {
+ int r = userCore.saveUser( user );
+ if (r == 0) {
+ responseStr = comm.getResponseError(response, Constants.STATUS_BAD_REQUEST,
+ new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM,KeysConstants.MISSING_NECESSARY_QUERYPARAM));
+ } else if(r == -1){
+ responseStr = comm.getResponseError(response, Constants.STATUS_ALREADY_EXISTS,
+ new ErrorCode(ErrorCodeEnum.RESOURCE_ALREADY_EXISTS,KeysConstants.RESOURCE_ALREADY_EXISTS));
+ } else {
+ responseData.put(ApiParam.API_RESPONSE_USERID, user.getUserId());
+ responseStr = responseData.toJSONString();
+ }
+ } catch (Exception e) {
+ responseStr = comm.getResponseException(response, e);
+ }
+ logger.debug("save user end --E-- appStr=" + jsonStr);
+ return responseStr;
+ }
+
+ /**
+ * delete user
+ *
+ * @param userExample
+ * @return
+ */
+ @RequestMapping(value = WebServiceURI.REST_USER_BY_USERID_LF, method = RequestMethod.DELETE, produces = APPLICATION_JSON_UTF8_VALUE)
+ public String deleteByUserId(@PathVariable("userId") String id, HttpServletResponse response) {
+ logger.debug("delete user start --S--" + id);
+ String responseStr = "";
+
+ ErrorCode paramCheckResult = checkParamDel(id);
+ if (paramCheckResult != null) {
+ return comm.getResponseError(response, Constants.STATUS_ALREADY_EXISTS, paramCheckResult);
+ }
+
+ try {
+ int r = userCore.deleteByUserId(id);
+ 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 user end --E-- appId=" + id);
+ return responseStr;
+ }
+
+ /**
+ * check user have app
+ * @param id
+ * @return
+ */
+ private ErrorCode checkParamDel(String id) {
+ try {
+ AppExample example = new AppExample();
+ app.market.model.app.AppExample.Criteria uc = example.createCriteria();
+ uc.andDeveloperEqualTo(id);
+ uc.andAppIsPublicEqualTo(ApiParam.API_PARAM_DEFAULT_IS_PUBLIC);
+ if (appCore.countByExample(example) > 0) {
+ return new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM, KeysConstants.USER_NOT_DELETE);
+ }
+ } catch (Exception e) {
+ return new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM, KeysConstants.INVALID_QUERYPARAM);
+ }
+
+ return null;
+ }
+
+ /**
+ * check parameter for update/create application
+ * @param user
+ * @return
+ */
+ private ErrorCode checkParamSave(User user) {
+ if (StringUtils.isEmpty(user.getUserId())) {// create application
+ if (StringUtils.isEmpty(user.getUserPw().replace(" ", "")) || user.getCreateDate() == null
+ || StringUtils.isEmpty(user.getUserName().replace(" ", ""))|| StringUtils.isEmpty(user.getMailAddress().replace(" ", ""))
+ || StringUtils.isEmpty(user.getAuId().replace(" ", ""))){
+ return new ErrorCode(ErrorCodeEnum.MISSING_NECESSARY_QUERYPARAM,
+ KeysConstants.MISSING_NECESSARY_QUERYPARAM);
+ }
+ if (user.getUserPw().indexOf(" ") != -1) {
+ return new ErrorCode(ErrorCodeEnum.MISSING_NECESSARY_QUERYPARAM,
+ KeysConstants.USER_PASSWORD_IS_NOT_SPACES);
+ }
+ } else if (user.getUpdateDate() == null) {// update application
+ return new ErrorCode(ErrorCodeEnum.MISSING_NECESSARY_QUERYPARAM,
+ KeysConstants.MISSING_NECESSARY_QUERYPARAM);
+ }
+
+ //check auId
+ try{
+ int auId = Integer.valueOf(user.getAuId());
+ if(auId < ApiParam.UserAuId.ADIMIN.getId() || auId > ApiParam.UserAuId.NORMAL.getId()){
+ return new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM, KeysConstants.INVALID_QUERYPARAM);
+ }
+ }catch (Exception e) {
+ return new ErrorCode(ErrorCodeEnum.INVALID_QUERYPARAM, KeysConstants.INVALID_QUERYPARAM);
+ }
+ return null;
+ }
+
+ /**
+ * generate token
+ * @param user
+ * @param loginId
+ * @param isRefreshToken
+ * @return token,refresh token
+ */
+ private String generateToken(User user, String loginId, boolean isRefreshToken) {
+ JSONObject responseData = new JSONObject();
+ String responseStr = null;
+
+ if (user != null) {
+ // get resource
+ List<Resource> list = resourceCore.selectResourcesByLoginId(loginId);
+ // set token
+ String accessToken = loginId + Constants.TOKEN_SEPARATOR + tokenManager.generateToken(loginId, user, list, false).getToken();
+ responseData.put(ApiParam.API_RESPONSE_TOKEN, accessToken);
+
+ if (!isRefreshToken) {
+ String refreshToken = loginId + Constants.TOKEN_SEPARATOR + tokenManager.generateRefreshToken(loginId);
+ responseData.put(ApiParam.API_RESPONSE_REFRESHTOKEN, refreshToken);
+ }
+
+ responseStr = responseData.toJSONString();
+ }
+
+ return responseStr;
+ }
+}
+