add websocket

This commit is contained in:
Donghuang 2022-06-16 22:42:33 +08:00
parent ad4e9ca003
commit 2fbd6b5f84
86 changed files with 1398 additions and 417 deletions

View File

@ -3,12 +3,20 @@ package com.pudonghot.ambition.crm;
import lombok.val;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Arrays;
import java.util.List;
/**
* @author Shaun Chyxion <br>
@ -18,8 +26,9 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@EnableAsync
@EnableScheduling
@EnableAspectJAutoProxy(proxyTargetClass = true)
@ImportResource("classpath*:spring/spring-*.xml")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class AmbitionCRM {
public class AmbitionCRM implements WebMvcConfigurer {
/**
* @param args start args
@ -37,4 +46,12 @@ public class AmbitionCRM {
threadPoolTaskExecutor.setQueueCapacity(64);
return threadPoolTaskExecutor;
}
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> messageConverters) {
val jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
jackson2HttpMessageConverter.setSupportedMediaTypes(
Arrays.asList(MediaType.valueOf("text/event-stream")));
messageConverters.add(jackson2HttpMessageConverter);
}
}

View File

@ -2,18 +2,14 @@ package com.pudonghot.ambition.crm.auth;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.model.ViewModel;
import org.apache.shiro.subject.Subject;
import me.chyxion.tigon.shiro.AuthCallback;
import me.chyxion.tigon.shiro.model.AuthUser;
import javax.servlet.http.HttpServletRequest;
import me.chyxion.tigon.shiro.model.AuthInfo;
import com.pudonghot.ambition.crm.model.User;
import org.springframework.stereotype.Service;
import org.apache.shiro.web.subject.WebSubject;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.AuthenticationException;
import com.pudonghot.ambition.crm.auth.model.Principal;
import com.pudonghot.ambition.crm.service.AuthLogService;
import com.pudonghot.ambition.crm.util.HttpServletRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -30,40 +26,40 @@ import com.pudonghot.ambition.crm.form.create.AuthFailedLogFormForCreate;
*/
@Slf4j
@Service
public class AuthCallbackSupport implements AuthCallback {
public class AuthCallbackSupport implements AuthCallback, SessionAbility {
@Autowired
private AuthLogService authLogService;
@Autowired
private AuthFailedLogService authLogFailedService;
@Autowired
private HttpServletRequest request;
/**
* {@inheritDoc}
*/
@Override
public void onSuccessfulLogin(AuthenticationToken token,
AuthenticationInfo info, Subject subject) {
public void onSuccessfulLogin(final AuthenticationToken token,
final AuthenticationInfo info,
final Subject subject) {
val ws = (WebSubject) subject;
val session = ws.getSession(false);
val request = (HttpServletRequest) ws.getServletRequest();
val principal = (Principal) subject.getPrincipal();
val authUser = new AuthUser<ViewModel<User>>();
// val authUser = new AuthUser<ViewModel<User>>();
val ip = HttpServletRequestUtils.getClientIP(request);
authUser.setAttr("ip", ip);
// authUser.setAttr("ip", ip);
val userAgent = request.getHeader("User-Agent");
authUser.setAttr("userAgent", userAgent);
val user = (ViewModel<User>) ((AuthInfo) info).getExtra();
val userId = user.getData().getId();
authUser.setUserId(userId);
authUser.setUser(user);
log.info("Save Auth User [{}] To Session [{}].", user, session.getId());
authUser.save(session);
// authUser.setAttr("userAgent", userAgent);
// val user = (ViewModel<User>) ((AuthInfo) info).getExtra();
val userId = principal.getUserId();
// authUser.setUserId(userId);
// authUser.setUser(user);
// log.info("Save Auth User [{}] To Session [{}].", user, session.getId());
// authUser.save(session);
val alForm = new AuthLogFormForCreate();
alForm.setUserId(userId);
alForm.setUserId(principal.getEmployeeId());
alForm.setIp(ip);
alForm.setUserAgent(userAgent);
alForm.unlock();
alForm.setCreatedBy(userId);
authLogService.create(alForm);
// HttpServletResponse response = (HttpServletResponse) ws.getServletResponse();
@ -74,16 +70,14 @@ public class AuthCallbackSupport implements AuthCallback {
* {@inheritDoc}
*/
@Override
public void onFailedLogin(AuthenticationToken token,
AuthenticationException ae,
Subject subject) {
public void onFailedLogin(final AuthenticationToken token,
final AuthenticationException ae,
final Subject subject) {
val loginId = (String) token.getPrincipal();
val password = new String((char[]) token.getCredentials());
log.info("Login Id [{}] Password [{}] Login Failed.", loginId, password);
val ws = (WebSubject) subject;
val request = (HttpServletRequest) ws.getServletRequest();
val form = new AuthFailedLogFormForCreate();
form.setLoginId(loginId);
form.setPassword(password);
@ -97,8 +91,7 @@ public class AuthCallbackSupport implements AuthCallback {
*/
@Override
public void beforeLogout(final Subject subject) {
val ws = (WebSubject) subject;
val session = ws.getSession(false);
val session = subject.getSession(false);
if (session != null) {
log.warn("Session [{}] Logout.", session);
}

View File

@ -1,7 +1,7 @@
package com.pudonghot.ambition.crm.auth;
import java.util.*;
import lombok.val;
import java.util.*;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.shiro.AuthRealm;
@ -10,6 +10,7 @@ import com.pudonghot.ambition.crm.model.User;
import org.springframework.stereotype.Service;
import me.chyxion.tigon.shiro.model.Credential;
import org.apache.shiro.authc.LockedAccountException;
import com.pudonghot.ambition.crm.auth.model.Principal;
import com.pudonghot.ambition.crm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
@ -21,7 +22,7 @@ import org.springframework.beans.factory.annotation.Autowired;
* Apr 7, 2015 4:14:20 PM
*/
@Service
public class AuthRealmSupport extends AuthRealm {
public class AuthRealmSupport implements AuthRealm<Principal, String> {
@Autowired
private UserService userService;
@ -30,18 +31,19 @@ public class AuthRealmSupport extends AuthRealm {
* {@inheritDoc}
*/
@Override
public Credential credential(Object principal) {
public Credential credential(final Principal principal) {
Credential credential = null;
val userViewModel =
userService.findViewModel(new Search(User.EMPLOYEE_ID, principal));
userService.findViewModel(principal.getUserId());
if (userViewModel != null) {
User admin = userViewModel.getData();
if (!admin.isEnabled()) {
throw new LockedAccountException("账户已禁用,请联系管理员");
val admin = userViewModel.getData();
if (!admin.getEnabled()) {
throw new LockedAccountException("Account locked");
}
credential = new Credential(
admin.getPassword(),
admin.getId()).setExtra(userViewModel);
admin.getId());
credential.setExtra(userViewModel);
}
return credential;
}
@ -50,17 +52,16 @@ public class AuthRealmSupport extends AuthRealm {
* {@inheritDoc}
*/
@Override
public boolean credentialMatch(Object password, Credential credential) {
public boolean credentialMatch(final String password, Credential credential) {
return userService.validatePassword(
((ViewModel<User>) credential.getExtra()).getData().getId(),
new String((char[])password));
((ViewModel<User>) credential.getExtra()).getData().getId(), password);
}
/**
* {@inheritDoc}
*/
@Override
public Collection<String> roles(Object principal) {
public Collection<String> roles(final Principal principal) {
val user = userService.find(new Search(User.EMPLOYEE_ID, principal));
val roles = new ArrayList<String>(4);
if (user.isAdmin()) {

View File

@ -0,0 +1,27 @@
package com.pudonghot.ambition.crm.auth;
import javax.servlet.*;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.core.annotation.Order;
/**
* @author Donghuang <br>
* Nov 17, 2019 16:30:41
*/
@Order
@Slf4j
@Component
public class AuthRequestFilter implements Filter {
/**
* {@inheritDoc}
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.debug("Wrap HTTP servlet request as AUTH request.");
filterChain.doFilter(new AuthRequestWrapper((HttpServletRequest) servletRequest), servletResponse);
}
}

View File

@ -0,0 +1,63 @@
package com.pudonghot.ambition.crm.auth;
import lombok.val;
import java.util.*;
import java.util.function.Function;
import com.pudonghot.ambition.crm.model.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* @author Donghuang <br>
* Nov 17, 2019 16:05:39
*/
public class AuthRequestWrapper extends HttpServletRequestWrapper implements SessionAbility {
private static Map<String, Function<SessionAbility, ?>> AUTH_ELS = new HashMap<>();
static {
AUTH_ELS.put(User.CREATED_BY, SessionAbility::getUserId);
AUTH_ELS.put(User.UPDATED_BY, SessionAbility::getUserId);
}
/**
* {@inheritDoc}
*/
public AuthRequestWrapper(final HttpServletRequest request) {
super(request);
}
/**
* {@inheritDoc}
*/
@Override
public Enumeration<String> getParameterNames() {
final Enumeration<String> paramNames = super.getParameterNames();
if (isAuthenticated()) {
val params = Collections.list(paramNames);
params.addAll(AUTH_ELS.keySet());
return Collections.enumeration(params);
}
return paramNames;
}
/**
* {@inheritDoc}
*/
@Override
public String[] getParameterValues(final String name) {
val getter = AUTH_ELS.get(name);
return getter != null ? new String[] { getParam(getter) } : super.getParameterValues(name);
}
/**
* get params
* @param getter getter
* @return param string or null
*/
private String getParam(final Function<SessionAbility, ?> getter) {
val param = getter.apply(this);
return param != null ?
(param instanceof String ?
(String) param : String.valueOf(param)) : null;
}
}

View File

@ -0,0 +1,88 @@
package com.pudonghot.ambition.crm.auth;
import lombok.val;
import org.apache.shiro.SecurityUtils;
import me.chyxion.tigon.kit.json.JsonService;
import com.pudonghot.ambition.crm.auth.model.Principal;
/**
* @author Donghuang
* @date Aug 12, 2020 10:13:43
*/
public interface SessionAbility {
/**
* get session id
*
* @return session id
*/
default String getSessionId() {
return (String) SecurityUtils.getSubject().getSession(false).getId();
}
/**
* get user id
*
* @return user id
*/
default String getUserId() {
return getPrincipal().getUserId();
}
/**
* get user name
*
* @return user name
*/
default String getName() {
return getPrincipal().getName();
}
/**
* get auth account
*
* @return auth account
*/
default String getAuthAccount() {
return getPrincipal().getAccount();
}
/**
* get auth principal
*
* @return session
*/
default Principal getPrincipal() {
val principal = SecurityUtils.getSubject().getPrincipal();
if (principal instanceof Principal) {
return (Principal) principal;
}
if (principal != null) {
return JsonService.getInstance().convert(principal, Principal.class);
}
throw new IllegalStateException(
"No principal found in security subject");
}
/**
* return true if user is authenticated
*
* @return true if user is authenticated
*/
default boolean isAuthenticated() {
return SecurityUtils.getSubject().isAuthenticated();
}
/**
* return true if user is admin
*
* @return true if user is admin
*/
default boolean isAdmin() {
return getPrincipal().getAdmin();
}
}

View File

@ -0,0 +1,44 @@
package com.pudonghot.ambition.crm.auth.model;
import lombok.Getter;
import lombok.AllArgsConstructor;
import org.apache.shiro.authc.HostAuthenticationToken;
/**
* @author Donghuang
* @date Aug 12, 2020 20:52:03
*/
@Getter
@AllArgsConstructor
public class AuthToken implements HostAuthenticationToken {
private static final long serialVersionUID = 1L;
/**
* principal
*/
private final Principal principal;
/**
* password
*/
private final String password;
/**
* The location from where the login attempt occurs, or <code>null</code> if not known or explicitly
* omitted.
*/
private String host;
public AuthToken(final Principal principal, final String password) {
this(principal, password, null);
}
/**
* {@inheritDoc}
*/
@Override
public Object getCredentials() {
return password;
}
}

View File

@ -0,0 +1,39 @@
package com.pudonghot.ambition.crm.auth.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
/**
* @author Donghuang
* @date Aug 12, 2020 20:47:35
*/
@Getter
@Setter
@ToString
@NoArgsConstructor
public class Principal implements Serializable {
private static final long serialVersionUID = 1L;
// Properties
private String userId;
private String account;
private String employeeId;
private String mobile;
private String email;
private String name;
private String enName;
private String gender;
private Boolean admin;
/**
* 扩展属性
*/
private Serializable attr;
public Principal(final String account) {
this.account = account;
}
}

View File

@ -5,23 +5,19 @@ import java.util.*;
import java.net.URLDecoder;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.model.M1;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import me.chyxion.tigon.mybatis.Search;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.util.TypeUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import org.apache.commons.lang3.CharEncoding;
import me.chyxion.tigon.kit.json.JsonService;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartHttpServletRequest;
/**
@ -35,6 +31,9 @@ import org.springframework.web.multipart.MultipartHttpServletRequest;
@Validated
public abstract class AbstractBaseController {
@Autowired
private JsonService jsonService;
/**
* build sql like value
* @param value
@ -197,7 +196,7 @@ public abstract class AbstractBaseController {
final List<Object[]> criteria;
try {
criteria = JSON.parseArray(decodeParam(strCriteria), Object[].class);
criteria = jsonService.parseArray(decodeParam(strCriteria), Object[].class);
}
catch (Exception e) {
throw new IllegalStateException(
@ -206,14 +205,15 @@ public abstract class AbstractBaseController {
for (val criterion : criteria) {
if (criterion.length == 3) {
final String field = (String) criterion[0];
val field = (String) criterion[0];
if (StringUtils.isNotBlank(field)) {
val colProp = criterionCol(field);
val col = colProp.getKey();
if (StringUtils.isNotBlank(col)) {
val op = (String) criterion[1];
val val = TypeUtils.castToJavaBean(criterion[2], colProp.getValue());
val val = JsonService.getInstance().convert(criterion[2], colProp.getValue());
if (StringUtils.isNotBlank(op) &&
val != null && val instanceof String ?
StringUtils.isNotBlank((String) val) : true) {
@ -258,9 +258,9 @@ public abstract class AbstractBaseController {
return search;
}
protected JSONObject filters(String filters) {
protected Map<String, Object> filters(String filters) {
try {
return JSON.parseObject(decodeParam(filters));
return jsonService.parse(decodeParam(filters), Map.class);
}
catch (Exception e) {
throw new IllegalStateException(
@ -275,7 +275,7 @@ public abstract class AbstractBaseController {
return defaultFilter(search);
}
final JSONObject joFilters = filters(strFilters);
val joFilters = filters(strFilters);
for (val filter : joFilters.entrySet()) {
val field = filter.getKey();
val colProp = filterCol(filter.getKey());
@ -287,9 +287,8 @@ public abstract class AbstractBaseController {
continue;
}
// type convert
if (filterVal instanceof JSONArray) {
search.eq(col, joFilters.getObject(
field, Array.newInstance(colProp.getValue(), 0).getClass()));
if (filterVal instanceof Collection) {
search.eq(col, jsonService.convert((Collection) filterVal, colProp.getValue()));
}
else {
search.eq(col, filterVal);
@ -302,22 +301,15 @@ public abstract class AbstractBaseController {
protected Search order(final Search search, final String strOrders) {
if (StringUtils.isNotBlank(strOrders)) {
final JSONArray jaOrders;
try {
jaOrders = JSON.parseArray(decodeParam(strOrders));
}
catch (JSONException e) {
throw new IllegalStateException(
"Invalid orders params [" + strOrders + "]", e);
}
for (val objOrder : jaOrders) {
val joSorter = (JSONObject) objOrder;
val jaOrders = jsonService.parseArray(decodeParam(strOrders));
for (val joSorter : jaOrders) {
if (!joSorter.isEmpty()) {
val sortEntry =
joSorter.entrySet().iterator().next();
val col = orderCol(sortEntry.getKey());
if (StringUtils.isNotBlank(col)) {
final String dir = (String) sortEntry.getValue();
val dir = (String) sortEntry.getValue();
if ("asc".equalsIgnoreCase(dir)) {
search.asc(col);
}

View File

@ -1,5 +1,6 @@
package com.pudonghot.ambition.crm.controller;
import lombok.val;
import java.util.List;
import java.util.Arrays;
import javax.validation.Valid;
@ -93,7 +94,7 @@ public class ApplicationController
@RequestMapping(value = "/update", method = RequestMethod.POST)
public void update(
@Valid ApplicationFormForUpdate form) {
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
form.setAdmin(isAdmin());
((ApplicationService) queryService).update(form);
}
@ -103,7 +104,7 @@ public class ApplicationController
@Override
public ViewModel<Application> find(final String id) {
final ViewModel<Application> viewModel = queryService.findViewModel(id);
if (getAuthUser().getUser().getData().isAdmin()) {
if (isAdmin()) {
viewModel.setAttr("users", userService.listViewModels(
new Search().asc(User.EMPLOYEE_ID)));
}
@ -114,19 +115,19 @@ public class ApplicationController
public ViewModel<AttachedImage> addImage(
@Valid ApplicationImageFormForCreate form) {
Assert.state(!form.getImage().isEmpty(), "Image content is empty");
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
form.setAdmin(isAdmin());
return new ViewModel<>(((ApplicationService) queryService).addImage(form));
}
@RequestMapping(value = "/remove-image", method = RequestMethod.POST)
public void removeImage(@NotBlank @RequestParam("id") String id) {
final User user = getAuthUser().getUser().getData();
((ApplicationService) queryService).removeImage(id, user.getId(), user.isAdmin());
val principal = getPrincipal();
((ApplicationService) queryService).removeImage(id, principal.getUserId(), principal.getAdmin());
}
@RequestMapping(value = "/update-image", method = RequestMethod.POST)
public void updateImage(@Valid ApplicationImageFormForUpdate form) {
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
form.setAdmin(isAdmin());
((ApplicationService) queryService).updateImage(form);
}
@ -134,19 +135,19 @@ public class ApplicationController
public ViewModel<AttachedFile> addAttachment(
@Valid ApplicationAttachedFileFormForCreate form) {
Assert.state(!form.getAttachment().isEmpty(), "Image content is empty");
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
form.setAdmin(isAdmin());
return new ViewModel<>(((ApplicationService) queryService).addAttachment(form));
}
@RequestMapping(value = "/remove-attachment", method = RequestMethod.POST)
public void removeAttachment(@NotBlank @RequestParam("id") String id) {
final User user = getAuthUser().getUser().getData();
((ApplicationService) queryService).removeAttachment(id, user.getId(), user.isAdmin());
val principal = getPrincipal();
((ApplicationService) queryService).removeAttachment(id, principal.getUserId(), principal.getAdmin());
}
@RequestMapping(value = "/update-attachment", method = RequestMethod.POST)
public void updateImage(@Valid ApplicationAttachedFileFormForUpdate form) {
form.setAdmin(getAuthUser().getUser().getData().isAdmin());
form.setAdmin(isAdmin());
((ApplicationService) queryService).updateAttachment(form);
}

View File

@ -1,6 +1,13 @@
package com.pudonghot.ambition.crm.controller;
import com.pudonghot.ambition.crm.auth.SessionAbility;
import com.pudonghot.ambition.crm.auth.model.AuthToken;
import com.pudonghot.ambition.crm.auth.model.Principal;
import lombok.val;
import me.chyxion.tigon.kit.bean.BeanService;
import me.chyxion.tigon.mybatis.Search;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.util.Assert;
import me.chyxion.tigon.model.ViewModel;
import com.pudonghot.ambition.crm.model.User;
@ -21,11 +28,13 @@ import org.springframework.beans.factory.annotation.Autowired;
*/
@Validated
@Controller
public class AuthController {
public class AuthController implements SessionAbility {
@Autowired
private UserService userService;
@Autowired
private AuthService authService;
@Autowired
private BeanService beanService;
@RequestMapping(value = "/auth/login", method = RequestMethod.POST)
public ViewModel<User> login(
@ -34,13 +43,18 @@ public class AuthController {
String loginId,
@NotBlank(message = "Param 'password' Could Not Be Blank")
@RequestParam("password")
String password,
@RequestParam(value = "rememberMe", defaultValue = "false")
boolean rememberMe) {
final User user = userService.find(new Search(User.ACCOUNT, loginId));
String password) {
val user = userService.find(new Search(User.ACCOUNT, loginId));
Assert.state(user != null, "Unknown account");
return userService.findViewModel((String) authService.login(
user.getEmployeeId(), password, rememberMe).getUserId());
val principal = new Principal();
principal.setAccount(loginId);
principal.setUserId(user.getId());
beanService.assign(principal, user);
SecurityUtils.getSubject().login(new AuthToken(principal, password));
return userService.findViewModel(user.getId());
}
/**
@ -53,6 +67,6 @@ public class AuthController {
@RequestMapping("/auth/info")
public ViewModel<User> info() {
return userService.findViewModel((String) authService.getAuthUser().getUserId());
return userService.findViewModel(getUserId());
}
}

View File

@ -1,10 +1,10 @@
package com.pudonghot.ambition.crm.controller;
import com.pudonghot.ambition.crm.service.UserService;
import me.chyxion.tigon.model.ViewModel;
import com.pudonghot.ambition.crm.model.User;
import me.chyxion.tigon.shiro.model.AuthUser;
import me.chyxion.tigon.shiro.service.AuthService;
import com.pudonghot.ambition.crm.auth.SessionAbility;
import com.pudonghot.ambition.crm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
/**
@ -14,28 +14,12 @@ import org.springframework.beans.factory.annotation.Autowired;
* chyxion@163.com <br>
* Jun 2, 2016 12:52:10 PM
*/
public class BaseController extends AbstractBaseController {
public class BaseController extends AbstractBaseController implements SessionAbility {
@Autowired
protected AuthService authService;
@Autowired
private UserService userService;
/**
* get auth user id
* @return
*/
protected String getUserId() {
return (String) getAuthUser().getUserId();
}
/**
* get auth user
* @return
*/
protected AuthUser<ViewModel<User>> getAuthUser() {
return authService.getAuthUser();
}
/**
* @return
*/

View File

@ -1,18 +1,11 @@
package com.pudonghot.ambition.crm.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import me.chyxion.tigon.form.FC2;
import me.chyxion.tigon.form.FU2;
import org.apache.commons.beanutils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import me.chyxion.tigon.shiro.service.AuthService;
import java.lang.reflect.InvocationTargetException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
@ -25,13 +18,10 @@ import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
* chyxion@163.com <br>
* May 17, 2016 2:49:31 PM
*/
@Slf4j
@Order(32)
@ControllerAdvice(annotations = {Controller.class, RestController.class})
public class BaseControllerAdvice {
private static final Logger log =
LoggerFactory.getLogger(BaseControllerAdvice.class);
@Autowired
private AuthService authService;
private ByteArrayMultipartFileEditor bamfe =
new ByteArrayMultipartFileEditor() {
/**
@ -45,34 +35,8 @@ public class BaseControllerAdvice {
};
@InitBinder
public void registerCustomEditors(WebDataBinder binder, ServletWebRequest request)
throws IllegalAccessException, InvocationTargetException {
Object target = binder.getTarget();
String userId = getUserId();
if (target instanceof FC2) {
log.debug("Base form [{}] for create found, set created by [{}].", target, userId);
((FC2<String>) target).unlock();
((FC2<String>) target).setCreatedBy(userId);
}
else if (target instanceof FU2) {
log.debug("Base form [{}] for update found, set updated by [{}].", target, userId);
((FU2<String, String>) target).unlock();
((FU2<String, String>) target).setUpdatedBy(userId);
}
else if (target != null) {
log.debug("Set form [{}] created/updated by [{}].", target, userId);
BeanUtils.copyProperty(target, "createdBy", userId);
BeanUtils.copyProperty(target, "updatedBy", userId);
}
// PropertyEditorSupport
public void registerCustomEditors(WebDataBinder binder, ServletWebRequest request) {
// PropertyEditorSupport
binder.registerCustomEditor(byte[].class, bamfe);
}
// --
// inner methods
String getUserId() {
return authService.isAuthenticated() ?
(String) authService.getAuthUser().getUserId() : null;
}
}

View File

@ -1,13 +1,11 @@
package com.pudonghot.ambition.crm.controller;
import javax.validation.Valid;
import me.chyxion.tigon.form.FC2;
import me.chyxion.tigon.model.BaseModel;
import me.chyxion.tigon.model.M0;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.form.BaseFormForUpdateApi;
import me.chyxion.tigon.form.FormUpdateApi;
import me.chyxion.tigon.service.BaseCrudByFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@ -20,9 +18,9 @@ import org.springframework.web.bind.annotation.RequestMethod;
* May 4, 2016 6:09:54 PM
*/
public class BaseCruController<
Model extends BaseModel<String>,
Model extends M0<String>,
FC extends FC2<String>,
FU extends BaseFormForUpdateApi<String>>
FU extends FormUpdateApi<String>>
extends BaseQueryController<Model> {
@Autowired

View File

@ -1,11 +1,10 @@
package com.pudonghot.ambition.crm.controller;
import me.chyxion.tigon.form.FC2;
import me.chyxion.tigon.model.BaseModel;
import me.chyxion.tigon.model.M0;
import me.chyxion.tigon.form.FormUpdateApi;
import javax.validation.constraints.NotNull;
import me.chyxion.tigon.form.BaseFormForUpdateApi;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
@ -17,9 +16,9 @@ import org.springframework.web.bind.annotation.RequestMapping;
* May 4, 2016 6:09:54 PM
*/
public class BaseCrudController<
Model extends BaseModel<String>,
Model extends M0<String>,
FC extends FC2<String>,
FU extends BaseFormForUpdateApi<String>>
FU extends FormUpdateApi<String>>
extends BaseCruController<Model, FC, FU> {
@SuppressWarnings("unchecked")

View File

@ -1,8 +1,8 @@
package com.pudonghot.ambition.crm.controller;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.model.M0;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.BaseModel;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.model.ListResult;
import me.chyxion.tigon.service.BaseQueryService;
@ -19,7 +19,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
* May 10, 2016 4:50:58 PM
*/
@Slf4j
public class BaseQueryController<Model extends BaseModel<String>>
public class BaseQueryController<Model extends M0<String>>
extends BaseController {
@Autowired

View File

@ -4,22 +4,22 @@ import lombok.val;
import java.util.*;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONArray;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.ViewModel;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import me.chyxion.tigon.model.ListResult;
import org.apache.commons.lang3.tuple.Pair;
import me.chyxion.tigon.webmvc.ResourceModel;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import com.pudonghot.ambition.crm.model.User;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import com.pudonghot.ambition.crm.model.Customer;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.multipart.MultipartFile;
import com.pudonghot.ambition.crm.util.FileDownloadUtils;
import com.pudonghot.ambition.crm.model.CustomerProperty;
import com.pudonghot.ambition.crm.service.CustomerService;
import org.springframework.web.bind.annotation.PostMapping;
@ -160,10 +160,8 @@ public class CustomerController
@RequiresRoles(User.ROLE_ADMIN)
@RequestMapping("/export")
public ResourceModel exportCSV() {
return new ResourceModel(
((CustomerService) queryService).exportCSV(getUserId()),
"text/csv; charset=gbk", null);
public ResponseEntity<?> exportCSV() {
return FileDownloadUtils.toResponseEntity(((CustomerService) queryService).exportCSV(getUserId()), null);
}
@RequiresRoles(User.ROLE_ADMIN)
@ -221,7 +219,8 @@ public class CustomerController
CustomerYearToDateSale.YTD_SALE.equals(col)) {
search.setAttr("YTD_SALE", true);
}
if ("application".equals(col) && !((JSONArray) val).isEmpty()) {
if ("application".equals(col) && !((Collection<Object>) val).isEmpty()) {
search.setAttr("APPLICATIONS", val);
return true;
}

View File

@ -3,7 +3,6 @@ package com.pudonghot.ambition.crm.controller;
import java.util.List;
import java.util.Arrays;
import javax.validation.Valid;
import com.alibaba.fastjson.JSONArray;
import me.chyxion.tigon.mybatis.Search;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
@ -11,9 +10,9 @@ import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.model.ListResult;
import javax.validation.constraints.NotNull;
import com.pudonghot.ambition.crm.model.User;
import javax.validation.constraints.NotEmpty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.hibernate.validator.constraints.NotEmpty;
import org.apache.shiro.authz.annotation.RequiresRoles;
import com.pudonghot.ambition.crm.model.CustomerProperty;
import org.springframework.web.bind.annotation.RequestParam;
@ -83,7 +82,7 @@ public class CustomerPropertyController
public void updateSort(
@NotEmpty
@RequestParam("ids")
JSONArray ids) {
final List<String> ids) {
((CustomerPropertyService) queryService).updateSort(getUserId(), ids);
}

View File

@ -1,9 +1,21 @@
package com.pudonghot.ambition.crm.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import com.pudonghot.ambition.crm.util.FileDownloadUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import me.chyxion.tigon.webmvc.ResourceModel;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import com.pudonghot.ambition.file.DiskFileApi;
@ -26,23 +38,28 @@ public class FileController {
private DiskFileApi fileApi;
@RequestMapping("/f/**")
public Object file(HttpServletRequest request) {
String reqUri = request.getRequestURI();
public ResponseEntity file(HttpServletRequest request) {
val reqUri = request.getRequestURI();
Assert.state(reqUri.length() > 3, "File name could not be blank");
final String fileName = reqUri.substring(
val fileName = reqUri.substring(
(request.getContextPath() + "/f/").length()).replaceAll("\\.\\w+$", "");
log.info("Get file [{}].", fileName);
final FileInfo fileInfo = fileApi.findFileInfo(fileName);
ResourceModel rm = null;
val fileInfo = fileApi.findFileInfo(fileName);
if (fileInfo != null) {
final File file = fileApi.getFile(fileInfo);
if (file.exists()) {
rm = new ResourceModel(file,
fileInfo.getContentType(), fileInfo.getDownloadName());
}
val file = fileApi.getFile(fileInfo);
return FileDownloadUtils.toResponseEntity(file, fileInfo.getDownloadName());
}
return rm != null ?
rm : ResponseEntity.notFound().build();
return ResponseEntity.notFound().build();
}
@SneakyThrows
String encode(final String downloadName) {
val name = URLEncoder.encode(downloadName, StandardCharsets.UTF_8.name());
return new StringBuilder("attachment; filename=\"")
.append(name)
.append("\"; filename*=utf-8''")
.append(name).toString();
}
}

View File

@ -3,6 +3,8 @@ package com.pudonghot.ambition.crm.controller;
import java.util.List;
import java.util.Arrays;
import javax.validation.Valid;
import lombok.val;
import org.springframework.util.Assert;
import me.chyxion.tigon.mybatis.Search;
import javax.validation.constraints.Max;
@ -88,8 +90,8 @@ public class LocalProductController
*/
@Override
public ViewModel<LocalProduct> find(final String id) {
final ViewModel<LocalProduct> viewModel = queryService.findViewModel(id);
if (getAuthUser().getUser().getData().isAdmin()) {
val viewModel = queryService.findViewModel(id);
if (isAdmin()) {
viewModel.setAttr("users", userService.listViewModels(
new Search().asc(User.EMPLOYEE_ID)));
}

View File

@ -1,19 +1,16 @@
package com.pudonghot.ambition.crm.controller;
import java.util.Date;
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
import java.util.*;
import lombok.val;
import javax.validation.Valid;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import me.chyxion.tigon.mybatis.Search;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import me.chyxion.tigon.model.ViewModel;
import me.chyxion.tigon.model.ListResult;
import org.apache.commons.lang3.StringUtils;
import me.chyxion.tigon.kit.json.JsonService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Controller;
import com.pudonghot.ambition.crm.model.WeekGoal;
@ -21,6 +18,7 @@ import com.pudonghot.ambition.crm.util.AmDateUtil;
import com.pudonghot.ambition.crm.service.WeekGoalService;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pudonghot.ambition.crm.form.update.WeekGoalFormForUpdate;
@ -41,6 +39,9 @@ public class WeekGoalController
"u.account",
"u.employee_id");
@Autowired
private JsonService jsonService;
@RequestMapping("/list")
public ViewModel<List<ViewModel<WeekGoal>>> list(
@Min(0)
@ -67,7 +68,7 @@ public class WeekGoalController
((WeekGoalService) queryService).initWeekGoal(userId);
return addYearSum(listViewModels(mineFilters(new Search(WeekGoal.USER_ID, userId), filters)),
Arrays.asList(getAuthUser().getUser().getData().getEmployeeId()));
Arrays.asList(getPrincipal().getEmployeeId()));
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ -78,11 +79,10 @@ public class WeekGoalController
private List<String> employeeIdsFilter(final String strFilters) {
if (StringUtils.isNotBlank(strFilters)) {
final JSONObject joFilters = parseFilters(strFilters);
final String[] employees =
joFilters.getObject("user", String[].class);
if (employees != null && employees.length > 0) {
return Arrays.asList(employees);
Map<String, Object> joFilters = parseFilters(strFilters);
val employees = (List<String>) joFilters.get("user");
if (employees != null && !employees.isEmpty()) {
return employees;
}
}
return Collections.emptyList();
@ -103,11 +103,10 @@ public class WeekGoalController
return thisMonth(search);
}
final JSONObject joFilters = parseFilters(strFilters);
Map<String, Object> joFilters = parseFilters(strFilters);
final Integer[] months =
joFilters.getObject("month", Integer[].class);
if (months != null && months.length > 0) {
val months = (List<Integer>)joFilters.get("month");
if (months != null && !months.isEmpty()) {
search.and(new Search(WeekGoal.MONTH_START, months)
.or(WeekGoal.MONTH_END, months));
}
@ -152,9 +151,9 @@ public class WeekGoalController
return result;
}
private JSONObject parseFilters(final String filters) {
private Map<String, Object> parseFilters(final String filters) {
try {
return JSON.parseObject(decodeParam(filters));
return jsonService.parseObject(decodeParam(filters));
}
catch (Exception e) {
throw new IllegalStateException(

View File

@ -7,7 +7,6 @@ import org.springframework.stereotype.Service;
import org.springframework.core.annotation.Order;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.dao.DuplicateKeyException;
import me.chyxion.tigon.webmvc.exception.DefaultExceptionResolver;
/**
* @author Shaun Chyxion <br>
@ -16,7 +15,7 @@ import me.chyxion.tigon.webmvc.exception.DefaultExceptionResolver;
*/
@Service
@Order(16)
public class CRMExceptionResolver extends DefaultExceptionResolver {
public class CRMExceptionResolver {
private static final Map<Class<?>, Pair<Integer, String>>
EXCEPTIONS_MAP =
@ -39,28 +38,4 @@ public class CRMExceptionResolver extends DefaultExceptionResolver {
return ImmutablePair.<Integer, String>of(code, msg);
}
};
/**
* {@inheritDoc}
*/
@Override
public boolean accept(Throwable ex) {
return EXCEPTIONS_MAP.containsKey(ex.getClass());
}
/**
* {@inheritDoc}
*/
@Override
protected Object getErrorCode(Throwable ex) {
return EXCEPTIONS_MAP.get(ex.getClass()).getKey();
}
/**
* {@inheritDoc}
*/
@Override
protected Object getErrorMessage(Throwable ex, Object code) {
return EXCEPTIONS_MAP.get(ex.getClass()).getValue();
}
}

View File

@ -3,7 +3,6 @@ package com.pudonghot.ambition.crm.exception;
import java.util.Map;
import java.util.HashMap;
import org.springframework.stereotype.Service;
import me.chyxion.tigon.webmvc.exception.ExceptionMessage;
/**
* @author Shaun Chyxion <br>
@ -11,7 +10,7 @@ import me.chyxion.tigon.webmvc.exception.ExceptionMessage;
* Jun 30, 2017 23:09:33
*/
@Service
public class ExceptionMessageSupport implements ExceptionMessage {
public class ExceptionMessageSupport {
private static final Map<Object, Object> map = new HashMap<Object, Object>() {
private static final long serialVersionUID = 1L;
{
@ -25,12 +24,4 @@ public class ExceptionMessageSupport implements ExceptionMessage {
put(5000, "Unknown error, please contact system admin");
}
};
/**
* {@inheritDoc}
*/
@Override
public Object get(Object code) {
return map.get(code);
}
}

View File

@ -1,13 +1,15 @@
package com.pudonghot.ambition.crm.service;
import com.alibaba.fastjson.JSONArray;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotEmpty;
import me.chyxion.tigon.service.BaseCrudByFormService;
import com.pudonghot.ambition.crm.model.CustomerProperty;
import com.pudonghot.ambition.crm.form.create.CustomerPropertyFormForCreate;
import com.pudonghot.ambition.crm.form.update.CustomerPropertyFormForUpdate;
import java.util.List;
/**
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
@ -24,7 +26,7 @@ public interface CustomerPropertyService
* @param operator operator
* @param ids ids
*/
void updateSort(@NotBlank String operator, @NotEmpty JSONArray ids);
void updateSort(@NotBlank String operator, @NotEmpty List<String> ids);
/**
* init system status

View File

@ -12,7 +12,7 @@ import com.pudonghot.ambition.crm.model.*;
import com.pudonghot.ambition.crm.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.pudonghot.ambition.file.DiskFileApi;
import me.chyxion.tigon.kit.sequence.IdSequence;
import com.pudonghot.ambition.crm.service.UserService;
import org.springframework.web.multipart.MultipartFile;
import com.pudonghot.ambition.crm.service.AttachmentService;
@ -44,8 +44,6 @@ public class ApplicationServiceSupport
@Autowired
private AttachedFileMapper attachmentMapper;
@Autowired
private DiskFileApi fileApi;
@Autowired
private CustomerMapper customerMapper;
@Autowired
private CustomerApplicationMapper customerApplicationMapper;
@ -55,6 +53,8 @@ public class ApplicationServiceSupport
private CustomerPermissionService customerPermissionService;
@Autowired
private AttachmentService attachmentService;
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
@ -223,12 +223,13 @@ public class ApplicationServiceSupport
*/
@Override
@Transactional(rollbackFor = Throwable.class)
public Application delete(final String id) {
return attachmentService.deleteOwner(id,
public int delete(final String id) {
attachmentService.deleteOwner(id,
mapper, application ->
Assert.state(customerApplicationMapper.count(
new Search(CustomerApplication.APPLICATION_ID, id)) == 0,
"Application [" + id + "] is in using"));
return 0;
}
private Application validatePerm(final String appId, final String userId, final boolean admin) {

View File

@ -6,6 +6,7 @@ import java.util.List;
import java.io.IOException;
import java.util.ArrayList;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import me.chyxion.tigon.model.M2;
import java.util.function.Consumer;
import java.util.function.Function;
@ -14,7 +15,6 @@ import me.chyxion.tigon.mybatis.Search;
import org.springframework.util.Assert;
import me.chyxion.tigon.mybatis.BaseMapper;
import org.apache.commons.io.FilenameUtils;
import me.chyxion.tigon.sequence.IdSequence;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.pudonghot.ambition.file.DiskFileApi;
@ -178,7 +178,7 @@ public class AttachmentServiceSupport
log.info("Delete attachment owner [{}].", ownerId);
val owner = mapper.find(ownerId);
Assert.state(owner != null, "No attachment owner [" + ownerId + "] found");
Assert.state(!owner.isEnabled(), "Attachment owner [" + ownerId + "] is enabled");
Assert.state(!owner.getEnabled(), "Attachment owner [" + ownerId + "] is enabled");
if (validator != null) {
validator.accept(owner);

View File

@ -40,7 +40,7 @@ public class CustomerIssueServiceSupport
final CustomerIssue issue = find(id);
Assert.state(issue != null, "No issue [" + id + "] found");
if (!issue.getIssue().equals(form.getIssue()) ||
form.isEnabled() != issue.isEnabled()) {
form.getEnabled() != issue.getEnabled()) {
return super.update(form);
}
log.info("Issue [{}] not changed", issue);

View File

@ -2,7 +2,9 @@ package com.pudonghot.ambition.crm.service.support;
import java.util.Date;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import me.chyxion.tigon.mybatis.Search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pudonghot.ambition.crm.model.CustomerPermission;
import me.chyxion.tigon.service.support.BaseCrudServiceSupport;
@ -22,6 +24,9 @@ public class CustomerPermissionServiceSupport
CustomerPermissionMapper>
implements CustomerPermissionService {
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
*/

View File

@ -1,8 +1,8 @@
package com.pudonghot.ambition.crm.service.support;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONArray;
import org.springframework.util.Assert;
import org.springframework.stereotype.Service;
import com.pudonghot.ambition.crm.model.CustomerProperty;
@ -39,7 +39,7 @@ public class CustomerPropertyServiceSupport
* {@inheritDoc}
*/
@Override
public void updateSort(String operator, JSONArray ids) {
public void updateSort(String operator, List<String> ids) {
int sort = 0;
final Date now = new Date();
for (final Object id : ids) {

View File

@ -4,6 +4,7 @@ import java.io.*;
import java.util.*;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import org.apache.commons.io.FileUtils;
import org.springframework.util.Assert;
import me.chyxion.tigon.mybatis.Search;
@ -61,6 +62,8 @@ public class CustomerServiceSupport
private CustomerApplicationMapper customerApplicationMapper;
@Autowired
private ApplicationMapper applicationMapper;
@Autowired
private IdSequence idSeq;
private static final String SPLITTER = new String(new int[]{0x1d}, 0, 1);
private static final CSVFormat EXPORT_FORMAT =
@ -179,7 +182,7 @@ public class CustomerServiceSupport
val application = applicationMapper.find(applicationId);
Assert.state(application != null,
"No application [" + applicationId + "] found");
Assert.state(application.isEnabled(),
Assert.state(application.getEnabled(),
"Application [" + application.getName() + "] is disabled");
val customerApplication = new CustomerApplication();
@ -549,10 +552,9 @@ public class CustomerServiceSupport
* {@inheritDoc}
*/
@Override
public Customer delete(final String id) {
val customer = super.delete(id);
Assert.state(customer != null,
"No customer [" + id + "] found");
public int delete(final String id) {
val rowDeleted = super.delete(id);
Assert.state(rowDeleted > 0, "No customer [" + id + "] found");
customerPermissionMapper.delete(
new Search(CustomerPermission.CUSTOMER_ID, id));
customerIssueMapper.delete(
@ -562,6 +564,6 @@ public class CustomerServiceSupport
customerApplicationMapper.delete(
new Search(CustomerApplication.CUSTOMER_ID, id));
return customer;
return 0;
}
}

View File

@ -5,6 +5,7 @@ import java.util.Date;
import java.io.InputStream;
import java.text.ParseException;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import me.chyxion.tigon.mybatis.Search;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.lang3.StringUtils;
@ -46,6 +47,8 @@ public class CustomerYearToDateSaleServiceSupport
private ImportRecordMapper importRecordMapper;
@Autowired
private CustomerPropertyService customerPropertyService;
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}

View File

@ -1,9 +1,11 @@
package com.pudonghot.ambition.crm.service.support;
import org.springframework.beans.factory.annotation.Qualifier;
import lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.core.task.TaskExecutor;
import com.pudonghot.ambition.crm.service.CustomerService;
import com.pudonghot.ambition.crm.service.ExportTaskService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Autowired;
/**
@ -15,12 +17,16 @@ public class ExportTaskServiceSupport implements ExportTaskService {
@Autowired
@Qualifier("exportTaskExecutor")
private TaskExecutor threadPoolTaskExecutor;
@Autowired
private CustomerService customerService;
/**
* {@inheritDoc}
*/
@Override
public void doExport(final String operator) {
threadPoolTaskExecutor.execute(() ->{
val exportFile = customerService.exportCSV(operator);
});
}
}

View File

@ -4,6 +4,7 @@ import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.shiro.util.Assert;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.ViewModel;
@ -36,7 +37,7 @@ public class HomePageServiceSupport
public void apply(final String id, final String operator) {
final HomePage homePage = find(id);
Assert.state(homePage != null, "No home page [" + id + "] found");
Assert.state(homePage.isEnabled(), "Home page [" + id + "] is not enabled");
Assert.state(homePage.getEnabled(), "Home page [" + id + "] is not enabled");
Assert.state(!homePage.isApplying(), "Home page [" + id + "] is applying");
final Date now = new Date();
toggleApplying(now, operator);
@ -60,10 +61,10 @@ public class HomePageServiceSupport
* {@inheritDoc}
*/
@Override
public HomePage delete(final String id) {
final HomePage homePage = find(id);
public int delete(final String id) {
val homePage = find(id);
Assert.state(homePage != null, "No home page [" + id + "] found");
Assert.state(!homePage.isEnabled(), "Home page [" + id + "] is enabled");
Assert.state(!homePage.getEnabled(), "Home page [" + id + "] is enabled");
return super.delete(id);
}

View File

@ -4,6 +4,7 @@ import java.util.Map;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import me.chyxion.tigon.kit.sequence.IdSequence;
import me.chyxion.tigon.mybatis.Search;
import org.springframework.util.Assert;
import me.chyxion.tigon.model.ViewModel;
@ -40,6 +41,8 @@ public class LocalProductServiceSupport
private AttachedFileMapper attachmentMapper;
@Autowired
private AttachmentService attachmentService;
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
@ -166,8 +169,9 @@ public class LocalProductServiceSupport
*/
@Override
@Transactional(rollbackFor = Throwable.class)
public LocalProduct delete(final String id) {
return attachmentService.deleteOwner(id, mapper, null);
public int delete(final String id) {
attachmentService.deleteOwner(id, mapper, null);
return 0;
}
private String namePrefix(final String name) {

View File

@ -2,6 +2,7 @@ package com.pudonghot.ambition.crm.service.support;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.util.Assert;
import me.chyxion.tigon.model.ViewModel;
import org.apache.commons.lang3.StringUtils;
@ -34,8 +35,8 @@ public class UserServiceSupport
* {@inheritDoc}
*/
@Override
public ViewModel<User> update(UserFormForUpdate form) {
final String password = form.getPassword();
public ViewModel<User> update(final UserFormForUpdate form) {
val password = form.getPassword();
if (StringUtils.isNotBlank(password)) {
form.setPassword(hashPassword(form.getId(), password));
}
@ -46,10 +47,10 @@ public class UserServiceSupport
* {@inheritDoc}
*/
@Override
public User delete(final String id) {
public int delete(final String id) {
User user = find(id);
Assert.state(user != null, "No user [" + id + "] found");
Assert.state(!user.isEnabled(), "User [" + id + "] is enabled");
Assert.state(!user.getEnabled(), "User [" + id + "] is enabled");
return super.delete(id);
}

View File

@ -3,9 +3,12 @@ package com.pudonghot.ambition.crm.service.support;
import java.util.Map;
import java.util.Date;
import java.util.List;
import me.chyxion.tigon.kit.sequence.IdSequence;
import org.joda.time.*;
import java.util.ArrayList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import me.chyxion.tigon.mybatis.Search;
import me.chyxion.tigon.model.ViewModel;
@ -33,6 +36,9 @@ public class WeekGoalServiceSupport
extends BaseCrudServiceSupport<String, WeekGoal, WeekGoalMapper>
implements WeekGoalService {
@Autowired
private IdSequence idSeq;
/**
* {@inheritDoc}
*/

View File

@ -0,0 +1,72 @@
package com.pudonghot.ambition.crm.util;
import com.pudonghot.ambition.crm.exception.CVSFileImportingException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @author Donghuang
* @date Jun 06, 2022 20:01:02
*/
@Slf4j
public class FileDownloadUtils {
private static final AtomicBoolean lock = new AtomicBoolean(false);
/**
* file to response entity
*
* @param file file
* @return response entity
*/
public static ResponseEntity<?> toResponseEntity(final File file, final String downloadName) {
log.debug("Download file [{}].", file);
if (file.exists()) {
val headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION,
encode(StringUtils.defaultIfBlank(downloadName, file.getName())));
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
try (val fin = new FileInputStream(file)) {
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new InputStreamResource(fin));
}
catch (final IOException e) {
log.error("Download file error caused.", e);
}
}
return ResponseEntity.notFound().build();
}
@SneakyThrows
static String encode(final String downloadName) {
val name = URLEncoder.encode(downloadName, StandardCharsets.UTF_8.name());
return new StringBuilder("attachment; filename=\"")
.append(name)
.append("\"; filename*=utf-8''")
.append(name).toString();
}
}

View File

@ -5,8 +5,8 @@ import lombok.extern.slf4j.Slf4j;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import me.chyxion.tigon.sequence.IdSequence;
import org.springframework.stereotype.Service;
import me.chyxion.tigon.kit.sequence.IdSequence;
import org.springframework.beans.factory.annotation.Autowired;
/**
@ -22,7 +22,7 @@ public class RequestListener implements ServletRequestListener {
@Override
public void requestInitialized(final ServletRequestEvent sre) {
MDC.put("requestId", idSeq.get());
MDC.put("requestId", idSeq.uuid());
sre.getServletRequest().setAttribute("startTime", System.currentTimeMillis());
}

View File

@ -28,6 +28,10 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
*/
@Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
registry.addEndpoint("/stomp").withSockJS();
registry.addEndpoint("/stomp")
.setAllowedOriginPatterns(
"http://localhost:[*]",
"http://127.0.0.1:[*]")
.withSockJS();
}
}

View File

@ -0,0 +1,37 @@
server:
port: 8088
spring:
servlet:
multipart:
max-file-size: 512MB
max-request-size: 512MB
datasource:
database-name: ambition-crm
host: 172.16.4.6
password: MySQL2b||!2b
port: 3306
username: root
database:
backup-dir: /Users/chyxion/Workspaces/ambition-crm/database_backups
restore-shell: /data/program/mysql-backup/bin/mysql_restore.sh
file:
base-dir: /Users/donghuang/Documents/Workspaces/ambition-crm/files/
base-path: http://127.0.0.1:1217/lm-f/
tigon:
shiro:
session:
validation:
scheduler:
enabled: true
filter-chain: >
/auth/login=anon
/=anon
/index.html=anon
/assets/**=anon
/f/**=anon
/**=user

View File

@ -1,24 +0,0 @@
# Server
server.port=8088
# MySQL
datasource.host=172.16.4.6
datasource.port=3306
datasource.database-name=ambition-crm
datasource.username=root
datasource.password=MySQL2b||!2b
database.backup-dir=/Users/chyxion/Workspaces/ambition-crm/database_backups
database.restore-shell=/data/program/mysql-backup/bin/mysql_restore.sh
# Shiro
shiro.session.validation.scheduler.enabled=true
spring.servlet.multipart.max-file-size=512MB
spring.servlet.multipart.max-request-size=512MB
# File
file.base-path=http://127.0.0.1:1217/lm-f/
# file.base-dir=/Users/chyxion/Workspaces/ambition-crm/files/
file.base-dir=/Users/donghuang/Documents/Workspaces/ambition-crm/files/

View File

@ -0,0 +1,37 @@
server:
port: 8088
spring:
servlet:
multipart:
max-file-size: 512MB
max-request-size: 512MB
datasource:
database-name: ambition-crm
host: 172.16.4.6
password: MySQL2b||!2b
port: 3306
username: root
database:
backup-dir: /Users/chyxion/Workspaces/ambition-crm/database_backups
restore-shell: /data/program/mysql-backup/bin/mysql_restore.sh
file:
base-dir: /Users/donghuang/Documents/Workspaces/ambition-crm/files/
base-path: http://127.0.0.1:1217/lm-f/
tigon:
shiro:
session:
validation:
scheduler:
enabled: true
filter-chain: >
/auth/login=anon
/=anon
/index.html=anon
/assets/**=anon
/f/**=anon
/**=user

View File

@ -1,18 +0,0 @@
# Server
server.port=8100
# MySQL
datasource.host=127.0.0.1
datasource.port=43306
datasource.database-name=ambition_crm
datasource.username=root
datasource.password=696@2^~)oZ@^#*Q
database.backup-dir=/data/program/mysql-backup/backup/ambition_crm
database.backup-shell=/data/program/mysql-backup/bin/mysql_restore.sh
# Shiro
shiro.session.validation.scheduler.enabled=true
spring.http.multipart.max-file-size=1024MB
spring.http.multipart.max-request-size=1024MB

View File

@ -0,0 +1,24 @@
server:
port: 8100
spring:
http:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
database:
backup-dir: /data/program/mysql-backup/backup/ambition_crm
backup-shell: /data/program/mysql-backup/bin/mysql_restore.sh
datasource:
database-name: ambition_crm
host: 127.0.0.1
password: 696@2^~)oZ@^#*Q
port: 43306
username: root
shiro:
session:
validation:
scheduler:
enabled: true

View File

@ -1,16 +0,0 @@
# Server
server.port=80
# MySQL
datasource.host=127.0.0.1
datasource.port=3306
datasource.database-name=ambition_crm
datasource.username=root
datasource.password=696@2^~)oZ@^#*Q
# Shiro
shiro.session.validation.scheduler.enabled=true
spring.http.multipart.max-file-size=1024MB
spring.http.multipart.max-request-size=1024MB

View File

@ -0,0 +1,18 @@
datasource:
database-name: ambition_crm
host: 127.0.0.1
password: 696@2^~)oZ@^#*Q
port: 3306
username: root
server:
port: 80
shiro:
session:
validation:
scheduler:
enabled: true
spring:
http:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB

View File

@ -1,6 +0,0 @@
/auth/login=anon
/=anon
/index.html=anon
/assets/**=anon
/f/**=anon
/**=user

View File

@ -0,0 +1,148 @@
package com.pudonghot.ambition.crm;
import com.pudonghot.ambition.crm.auth.model.Principal;
import lombok.SneakyThrows;
import lombok.val;
import me.chyxion.tigon.kit.json.JsonService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DelegatingSubject;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.subject.WebSubject;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @author Donghuang
* @date Jan 05, 2022 15:28:35
*/
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AmbitionCRM.class,
webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public abstract class MockTestBase {
@Autowired
protected WebApplicationContext webApplicationContext;
@Autowired
protected SecurityManager securityManager;
@Autowired
private JsonService jsonService;
protected MockMvc mockMvc;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
@Before
public void before() throws Exception {
SecurityUtils.setSecurityManager(securityManager);
request = new MockHttpServletRequest(webApplicationContext.getServletContext());
response = new MockHttpServletResponse();
val subject = new WebSubject.Builder(request, response).buildWebSubject();
if (subject instanceof DelegatingSubject) {
val delegatingSubject = (DelegatingSubject) subject;
val fieldPrincipals = DelegatingSubject.class.getDeclaredField("principals");
fieldPrincipals.setAccessible(true);
fieldPrincipals.set(delegatingSubject, new SimplePrincipalCollection(getPrincipal(), "realm"));
val fieldAuthenticated = DelegatingSubject.class.getDeclaredField("authenticated");
fieldAuthenticated.setAccessible(true);
fieldAuthenticated.set(delegatingSubject, true);
val fieldSession = DelegatingSubject.class.getDeclaredField("session");
fieldSession.setAccessible(true);
fieldSession.set(delegatingSubject, getSession());
ThreadContext.bind(delegatingSubject);
}
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
/**
* 子类改写
*
* @return principal
*/
protected abstract Principal getPrincipal();
/**
* 子类改写
*
* @return session
*/
protected Session getSession() {
return new SimpleSession();
}
protected String toJsonString(final Object obj) {
return jsonService.toJSONString(obj);
}
/**
* post json
*
* @param path path
* @param payload payload
* @return req builder
*/
protected MvcResult postJson(final String path, final Object payload) {
return perform(MockMvcRequestBuilders.post(path)
.contentType(MediaType.APPLICATION_JSON)
.content(toJsonString(payload))
.accept(MediaType.APPLICATION_JSON));
}
/**
* get json
*
* @param path path
* @return req builder
*/
protected MvcResult getJson(final String path) {
return perform(MockMvcRequestBuilders.get(path)
.accept(MediaType.APPLICATION_JSON));
}
/**
* get json
*
* @param path path
* @return req builder
*/
protected MvcResult getJson(final String path, final Object params) {
val builder = MockMvcRequestBuilders.get(path)
.accept(MediaType.APPLICATION_JSON);
if (params != null) {
jsonService.toMap(params).forEach((key, value) -> builder.queryParam(key, String.valueOf(value)));
}
return perform(builder);
}
@SneakyThrows
MvcResult perform(final MockHttpServletRequestBuilder reqBuilder) {
return mockMvc.perform(reqBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
}
}

View File

@ -0,0 +1,120 @@
package com.pudonghot.ambition.crm;
import lombok.SneakyThrows;
import lombok.val;
import me.chyxion.tigon.kit.json.JsonService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SimpleSession;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.apache.shiro.web.subject.WebSubject;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
/**
* @author Donghuang
* @date Jan 05, 2022 15:28:35
*/
@WebAppConfiguration
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AmbitionCRM.class,
webEnvironment = SpringBootTest.WebEnvironment.MOCK)
public abstract class TestBase {
@Autowired
protected WebApplicationContext webApplicationContext;
@Autowired
protected SecurityManager securityManager;
@Autowired
private JsonService jsonService;
protected MockMvc mockMvc;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
@Before
public void before() throws Exception {
SecurityUtils.setSecurityManager(securityManager);
request = new MockHttpServletRequest(webApplicationContext.getServletContext());
request.addHeader("User-Agent", "Mock-Request");
response = new MockHttpServletResponse();
val subject = new WebSubject.Builder(request, response).buildWebSubject();
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
/**
* 子类改写
*
* @return session
*/
protected Session getSession() {
return new SimpleSession();
}
protected String toJsonString(final Object obj) {
return jsonService.toJSONString(obj);
}
/**
* post json
*
* @param path path
* @param payload payload
* @return req builder
*/
protected MvcResult postJson(final String path, final Object payload) {
return perform(MockMvcRequestBuilders.post(path)
.contentType(MediaType.APPLICATION_JSON)
.content(toJsonString(payload))
.accept(MediaType.APPLICATION_JSON));
}
/**
* get json
*
* @param path path
* @return req builder
*/
protected MvcResult getJson(final String path) {
return perform(MockMvcRequestBuilders.get(path)
.accept(MediaType.APPLICATION_JSON));
}
/**
* get json
*
* @param path path
* @return req builder
*/
protected MvcResult getJson(final String path, final Object params) {
val builder = MockMvcRequestBuilders.get(path)
.accept(MediaType.APPLICATION_JSON);
if (params != null) {
jsonService.toMap(params).forEach((key, value) -> builder.queryParam(key, String.valueOf(value)));
}
return perform(builder);
}
@SneakyThrows
MvcResult perform(final MockHttpServletRequestBuilder reqBuilder) {
return mockMvc.perform(reqBuilder)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
}
}

View File

@ -1,27 +1,19 @@
package com.pudonghot.ambition.crm.controller;
import java.util.Map;
import com.pudonghot.ambition.crm.TestBase;
import lombok.val;
import me.chyxion.tigon.web.test.ControllerTestTool;
import org.junit.Test;
import java.util.HashMap;
import org.junit.runner.RunWith;
import me.chyxion.tigon.webmvc.test.ControllerTestTool;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.pudonghot.ambition.crm.AmbitionCRM;
import java.util.HashMap;
/**
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Mar 10, 2017 23:15:16
*/
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AmbitionCRM.class)
public class SiteControllerTest {
public class SiteControllerTest extends TestBase {
@Autowired
private ControllerTestTool t;
@ -42,11 +34,10 @@ public class SiteControllerTest {
}
@Test
public void testPost() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("id", "id");
params.put("name", "Shaun Chyxion");
params.put("gender", "");
t.print(t.post("/post", params));
public void testAuthLogin() {
val params = new HashMap<String, Object>();
params.put("loginId", "donghuang");
params.put("password", "2b||!2b");
t.print(t.post("/auth/login", params));
}
}

View File

@ -4,5 +4,5 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Scan Controllers -->
<bean class="me.chyxion.tigon.webmvc.test.ControllerTestTool" />
<bean class="me.chyxion.tigon.web.test.ControllerTestTool" />
</beans>

View File

@ -26,7 +26,7 @@
</dependency>
<dependency>
<groupId>me.chyxion.tigon</groupId>
<artifactId>tigon-sequence</artifactId>
<artifactId>tigon-kit</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>

View File

@ -17,9 +17,9 @@ import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import me.chyxion.tigon.sequence.IdSequence;
import com.pudonghot.ambition.file.ImageTool;
import org.springframework.util.MimeTypeUtils;
import me.chyxion.tigon.kit.sequence.IdSequence;
import com.pudonghot.ambition.file.AmbitionFileApi;
import com.pudonghot.ambition.file.request.AmFileUploadReq;
import org.springframework.beans.factory.annotation.Autowired;

View File

@ -22,10 +22,6 @@
<groupId>com.pudonghot.ambition</groupId>
<artifactId>crm-mapper</artifactId>
</dependency>
<dependency>
<groupId>me.chyxion.tigon</groupId>
<artifactId>tigon-sequence</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>

View File

@ -23,6 +23,8 @@ pushd $(dirname "$prg_path")
WORK_DIR=$(pwd)
echo "Work dir [$WORK_DIR]"
export MAVEN_OPTS='-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000'
mvn -T 4C clean -pl crm -am -DskipTests \
-Dspring-boot.run.fork=false \
spring-boot:run

@ -1 +1 @@
Subproject commit cf48c8867c81a24459ddcfffbd1ec4029b4fc95e
Subproject commit a69a6519311d6a5ec932f2f7e1e71bb381a04a20

View File

@ -3,9 +3,8 @@ package com.pudonghot.ambition.crm.form.create;
import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.form.FC2;
import me.chyxion.tigon.format.annotation.Trim;
import me.chyxion.tigon.annotation.Trim;
import javax.validation.constraints.NotBlank;
import me.chyxion.tigon.format.annotation.EmptyToNull;
import org.springframework.web.multipart.MultipartFile;
/**
@ -23,10 +22,8 @@ public class ApplicationFormForCreate extends FC2<String> {
@NotBlank
private String name;
@Trim
@EmptyToNull
private String content;
@Trim
@EmptyToNull
private String owner;
private String[] imageTitles;
private MultipartFile[] images;

View File

@ -5,7 +5,6 @@ import lombok.Setter;
import me.chyxion.tigon.form.FC2;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
import me.chyxion.tigon.format.annotation.EmptyToNull;
/**
* @version 0.0.1
@ -41,7 +40,6 @@ public class CustomerFormForCreate extends FC2<String> {
@NotBlank
@Length(max = 36)
private String region;
@EmptyToNull
@Length(max = 36)
private String status;
}

View File

@ -3,7 +3,7 @@ package com.pudonghot.ambition.crm.form.create;
import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.form.FC2;
import me.chyxion.tigon.format.annotation.Trim;
import me.chyxion.tigon.annotation.Trim;
import javax.validation.constraints.NotBlank;
/**

View File

@ -4,8 +4,7 @@ import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.form.FC2;
import javax.validation.constraints.NotBlank;
import me.chyxion.tigon.format.annotation.Trim;
import me.chyxion.tigon.format.annotation.EmptyToNull;
import me.chyxion.tigon.annotation.Trim;
import org.springframework.web.multipart.MultipartFile;
/**
@ -26,7 +25,6 @@ public class LocalProductFormForCreate extends FC2<String> {
@NotBlank
private String name;
@Trim
@EmptyToNull
private String content;
private String[] imageTitles;
private MultipartFile[] images;

View File

@ -4,7 +4,7 @@ import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.form.FC2;
import javax.validation.constraints.Pattern;
import me.chyxion.tigon.format.annotation.Trim;
import me.chyxion.tigon.annotation.Trim;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;

View File

@ -3,10 +3,9 @@ package com.pudonghot.ambition.crm.form.update;
import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.form.FU2;
import me.chyxion.tigon.annotation.Trim;
import javax.validation.constraints.NotBlank;
import me.chyxion.tigon.format.annotation.Trim;
import org.hibernate.validator.constraints.Length;
import me.chyxion.tigon.format.annotation.EmptyToNull;
/**
* @version 0.0.1
@ -26,9 +25,7 @@ public class ApplicationFormForUpdate extends FU2<String, String> {
@Length(max = 64)
private String name;
@Trim
@EmptyToNull
private String content;
@Trim
@EmptyToNull
private String owner;
}

View File

@ -2,10 +2,8 @@ package com.pudonghot.ambition.crm.form.update;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import me.chyxion.tigon.form.FU2;
import org.hibernate.validator.constraints.Length;
import me.chyxion.tigon.format.annotation.EmptyToNull;
/**
* @version 0.0.1
@ -20,7 +18,6 @@ public class CustomerFormForUpdate extends FU2<String, String> {
private static final long serialVersionUID = 1L;
// Properties
@EmptyToNull
@Length(max = 36)
private String status;
private String[] applications;

View File

@ -3,10 +3,9 @@ package com.pudonghot.ambition.crm.form.update;
import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.form.FU2;
import me.chyxion.tigon.annotation.Trim;
import javax.validation.constraints.NotBlank;
import me.chyxion.tigon.format.annotation.Trim;
import org.hibernate.validator.constraints.Length;
import me.chyxion.tigon.format.annotation.EmptyToNull;
/**
* @version 0.0.1
@ -27,6 +26,5 @@ public class LocalProductFormForUpdate extends FU2<String, String> {
@Length(max = 64)
private String name;
@Trim
@EmptyToNull
private String content;
}

View File

@ -5,11 +5,10 @@ import lombok.Setter;
import me.chyxion.tigon.form.FU2;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import me.chyxion.tigon.format.annotation.Trim;
import me.chyxion.tigon.annotation.Trim;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
import me.chyxion.tigon.format.annotation.EmptyToNull;
import static com.pudonghot.ambition.crm.common.Constants.GENDER_REGEXP;
/**
@ -33,13 +32,11 @@ public class UserFormForUpdate extends FU2<String, String> {
@Length(max = 36)
private String name;
@Trim
@EmptyToNull
@Length(max = 36)
private String enName;
@Trim
@Pattern(regexp = GENDER_REGEXP)
private String gender;
@EmptyToNull
@Length(max = 36)
protected String password;
@Trim

View File

@ -6,8 +6,8 @@ import me.chyxion.tigon.model.M3;
import me.chyxion.tigon.mybatis.Table;
import me.chyxion.tigon.mybatis.NotUpdate;
import lombok.experimental.FieldNameConstants;
import com.alibaba.fastjson.annotation.JSONField;
import me.chyxion.tigon.mybatis.NotUpdateWhenNull;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* @version 0.0.1
@ -25,14 +25,14 @@ public class User extends M3<String, String> {
// roles
public static final String ROLE_ADMIN = "ADMIN";
public static final String ROLE_LELI = "leli";
public static final String ROLE_CHYXION = "chyxion";
public static final String ROLE_CHYXION = "donghuang";
// Properties
private String account;
@NotUpdate
private String employeeId;
@NotUpdateWhenNull
@JSONField(serialize = false)
@Getter(onMethod_ = @JsonIgnore)
private String password;
private String mobile;
private String email;

View File

@ -0,0 +1,47 @@
package me.chyxion.tigon.form;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 5:27:20 PM
*/
@Slf4j
public class BaseForm implements BaseFormApi {
private static final long serialVersionUID = 1L;
/**
* copy to class
* @param clazz copy to class
* @return copy result
*/
@Override
public <T> T copy(final Class<T> clazz) {
log.debug("Copy form [{}] to class [{}].", this, clazz);
final T obj;
try {
obj = clazz.newInstance();
}
catch (Exception e) {
throw new IllegalStateException(
"Create [" + clazz + "] object error caused", e);
}
return copy(obj);
}
/**
* copy to object
* @param obj copy to object
* @return copy result
*/
@Override
public <T> T copy(T obj) {
log.debug("Copy form [{}] to [{}].", this, obj);
BeanUtils.copyProperties(this, obj);
return obj;
}
}

View File

@ -0,0 +1,28 @@
package me.chyxion.tigon.form;
import java.io.Serializable;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 5:25:13 PM
*/
public interface BaseFormApi extends Serializable {
/**
* copy to class
* @param clazz to class
* @param <T> to class type
* @return copy result
*/
<T> T copy(Class<T> clazz);
/**
* @param obj copy to object
* @param <T> to class type
* @return copy result
*/
<T> T copy(T obj);
}

View File

@ -0,0 +1,12 @@
package me.chyxion.tigon.form;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 6:23:41 PM
*/
public interface BaseFormForCreateApi extends BaseFormApi {
}

View File

@ -0,0 +1,21 @@
package me.chyxion.tigon.form;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 6:24:03 PM
*/
public interface BaseFormForUpdateApi<Id> extends BaseFormApi {
/**
* @return id
*/
Id getId();
/**
* @param id id
*/
void setId(Id id);
}

View File

@ -0,0 +1,14 @@
package me.chyxion.tigon.form;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 6:26:19 PM
*/
public class FC0 extends BaseForm
implements BaseFormForCreateApi {
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,25 @@
package me.chyxion.tigon.form;
import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.annotation.Trim;
import javax.validation.constraints.NotNull;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 6:26:19 PM
*/
@Getter
@Setter
public class FC1 extends FC0 {
private static final long serialVersionUID = 1L;
@NotNull
protected Boolean enabled = true;
@Trim
protected String note;
}

View File

@ -0,0 +1,21 @@
package me.chyxion.tigon.form;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotNull;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 6:26:19 PM
*/
@Getter
@Setter
public class FC2<CreatorId> extends FC1 {
private static final long serialVersionUID = 1L;
@NotNull
protected CreatorId createdBy;
}

View File

@ -0,0 +1,24 @@
package me.chyxion.tigon.form;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotNull;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 6:26:36 PM
*/
@Getter
@Setter
public class FU0<Id>
extends BaseForm
implements BaseFormForUpdateApi<Id> {
private static final long serialVersionUID = 1L;
@NotNull
protected Id id;
}

View File

@ -0,0 +1,23 @@
package me.chyxion.tigon.form;
import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.annotation.Trim;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 6:26:36 PM
*/
@Getter
@Setter
public class FU1<Id>
extends FU0<Id> {
private static final long serialVersionUID = 1L;
protected Boolean enabled = true;
@Trim
protected String note;
}

View File

@ -0,0 +1,22 @@
package me.chyxion.tigon.form;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotNull;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 8, 2016 6:26:36 PM
*/
@Getter
@Setter
public class FU2<EditorId, Id>
extends FU1<Id> {
private static final long serialVersionUID = 1L;
@NotNull
private EditorId updatedBy;
}

View File

@ -0,0 +1,46 @@
package me.chyxion.tigon.model;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
import me.chyxion.tigon.mybatis.NotUpdate;
import lombok.experimental.FieldNameConstants;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 17, 2015 2:09:08 PM
*/
@Getter
@Setter
@FieldNameConstants(prefix = "")
public class M1<Id> extends M0<Id> {
private static final long serialVersionUID = 1L;
@NotUpdate
protected Date dateCreated;
protected Date dateUpdated;
/**
* init date created
*/
@Override
public void beforeInsert() {
super.beforeInsert();
if (dateCreated == null) {
dateCreated = new Date();
}
}
/**
* update date updated
*/
@Override
public void beforeUpdate() {
super.beforeUpdate();
dateUpdated = new Date();
}
}

View File

@ -0,0 +1,35 @@
package me.chyxion.tigon.model;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.FieldNameConstants;
/**
* @version 0.0.1
* @since 0.0.1
* @author Shaun Chyxion <br>
* chyxion@163.com <br>
* Oct 17, 2015 2:09:08 PM
*/
@Getter
@Setter
@FieldNameConstants(prefix = "")
public class M2<Id> extends M1<Id> {
private static final long serialVersionUID = 1L;
protected Boolean enabled;
protected String note;
/**
* {@inheritDoc}
*/
@Override
public void beforeInsert() {
super.beforeInsert();
if (enabled == null) {
enabled = true;
}
}
}

View File

@ -0,0 +1,23 @@
package me.chyxion.tigon.model;
import lombok.Getter;
import lombok.Setter;
import me.chyxion.tigon.mybatis.NotUpdate;
import lombok.experimental.FieldNameConstants;
/**
* @author Donghuang
* @date Jun 06, 2022 18:51:35
*/
@Setter
@Getter
@FieldNameConstants(prefix = "")
public class M3<UserId, Id>
extends M2<Id> {
private static final long serialVersionUID = 1L;
// fields
@NotUpdate
protected UserId createdBy;
protected UserId updatedBy;
}

View File

@ -229,6 +229,7 @@
<fileset>
<directory>src/main/resources</directory>
<includes>
<include>application.yml</include>
<include>application.properties</include>
<include>application.yaml</include>
<include>log4j2.xml</include>

View File

@ -1,17 +1,20 @@
import Ember from 'ember';
import BaseComponent from './base-component';
import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';
export default BaseComponent.extend({
// elementId: 'navbar',
classNames: ['navbar', 'navbar-default', 'navbar-collapse'],
user: Ember.computed.alias('ajax.user'),
user: alias('ajax.user'),
websocket: service(),
didReceiveAttrs() {
let me = this;
let user = me.get('user');
const me = this;
const user = me.get('user');
if (!user) {
console.info('No User Found In Session Storage, Try To Load From Cloud');
console.info('No user found in session storage, try to load from server.');
me.ajax.doGet(false, 'auth/info', (u) => {
me.set('user', u);
me.get('websocket').connect();
});
}
},
@ -19,6 +22,7 @@ export default BaseComponent.extend({
logout() {
let me = this;
me.ajax.doPost(false, 'auth/logout', () => {
me.get('websocket').disconnect();
me.set('user', null);
me.get('message').alert('Sign out successfully');
me.get('router').transitionTo('login');

View File

@ -1,10 +1,10 @@
import Ember from 'ember';
import { getOwner } from '@ember/application';
import Route from '@ember/routing/route';
import $ from 'jquery'
export default Route.extend({
getLoginRoute() {
return Ember.getOwner(this).lookup('route:login');
return getOwner(this).lookup('route:login');
},
transitionIntercept(transition) {
if (transition.targetName !== 'login') {

View File

@ -14,4 +14,18 @@ export default Route.extend({
}
// this.transitionTo('app.list', 1);
},
actions: {
didTransition() {
if (window.localStorage) {
const prevURL = window.localStorage.getItem('prevURL');
if (prevURL) {
window.localStorage.removeItem('prevURL');
if (prevURL != window.location.href) {
window.location.href = prevURL;
}
}
}
return true; // Bubble the didTransition event
}
}
});

View File

@ -1,7 +1,6 @@
import Ember from 'ember';
import $ from 'jquery';
import Route from '@ember/routing/route';
export default Ember.Route.extend({
export default Route.extend({
activate() {
this.controllerFor('application').set('login', true);
},
@ -10,14 +9,13 @@ export default Ember.Route.extend({
},
actions: {
doLogin(model) {
let me = this;
const me = this;
me.get('ajax').doPost('auth/login', model,
function(user) {
console.debug(`User ${user} Loggedin`);
console.debug(`User ${user} login successfully`);
me.set('ajax.user', user);
me.message.alert('Sign in successfully');
window.location.href = '/';
$.trigger('LOGINED', true);
}, function(msg) {
me.get('message').warn(msg);
});

View File

@ -1,4 +1,5 @@
import Ember from 'ember';
import { getOwner } from '@ember/application';
import $ from 'jquery';
export default Ember.Service.extend({
@ -74,7 +75,7 @@ export default Ember.Service.extend({
}
else if (r.errcode === 4011) {
// $.trigger('NOT_LOGIN', true);
Ember.getOwner(me).lookup('route:application').transitionTo('login');
getOwner(me).lookup('route:application').transitionTo('login');
}
// ignore fail callback
else if (p.fnFail !== false) {
@ -88,7 +89,14 @@ export default Ember.Service.extend({
},
error(jqXHR, textStatus) {
Ember.Logger.error('Ajax Request Error Caused', arguments);
if (textStatus === 'timeout') {
if (jqXHR.status === 401) {
if (window.localStorage) {
window.localStorage.setItem('prevURL', window.location.href);
}
// window.location.href = jqXHR.getResponseHeader('location')
getOwner(me).lookup('route:application').transitionTo('login');
}
else if (textStatus === 'timeout') {
me.dialog.error('Ajax Request Timeout Error Caused.');
}
else if (textStatus === 'abort') {

View File

@ -1,10 +1,11 @@
import Service from '@ember/service';
import { aliasMethod } from '@ember/object';
import { inject as service } from '@ember/service';
import $ from 'jquery';
export default Service.extend({
ajax: service('ajax'),
connect() {
let me = this;
const me = this;
if (me.get('connected')) {
console.info('Websocket is connected, reconnect.');
me.disconnect();
@ -14,29 +15,39 @@ export default Service.extend({
if (!me.get('stompClient')) {
me.set('stompClient', Stomp.over(new SockJS('/stomp')));
}
const user = me.get('ajax.user');
if (!user) {
console.warn('No user info found, ignore websocket connect.');
return;
}
me.get('stompClient').connect({}, function() {
console.info('Connect websocket.');
me.stompClient.subscribe('/topic/websocket', function(msg) {
console.info('Connect websocket.', user);
me.stompClient.subscribe('/topic/' + user.id, function(msg) {
console.info('On websocket message: ', msg);
$.trigger('websocket', JSON.parse(msg.body));
$.trigger('WEBSOCKET', JSON.parse(msg.body));
});
me.set('connected', true);
console.info('Websocket connected.');
});
},
willDestroy() {
var me = this;
const me = this;
me._super(...arguments);
me.disconnect();
},
disconnect() {
const me = this;
if (me.get('connected') && me.get('stompClient')) {
me.get('stompClient').disconnect();
me.set('connected', false);
console.info('Websocket disconnected.');
return;
}
else {
console.info('Websocket is not connected, ignore disconnect.');
}
},
disconnect: aliasMethod('willDestroy')
console.info('Websocket is not connected, ignore disconnect.');
}
});