Commit 024b7bff by lanmw

init

parent 26e04707
package com.keymobile.tagmanager.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.keymobile.tagmanager.model.Page;
import com.keymobile.tagmanager.model.Tag;
import com.keymobile.tagmanager.service.TagService;
import com.keymobile.tagmanager.util.Constants;
import com.keymobile.tagmanager.util.JsonTreeHelper.JsonNode;
import com.keymobile.tagmanager.util.UserInfoUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api(value = "标签相关", tags = "标签相关")
@RestController
@RequestMapping(value = "/tagCtrl")
//@PreAuthorize("principal.authorities.?[authority.startsWith('ROLE_tagmanager_operator')].size() > 0")
public class TagCtrl {
@Autowired
private TagService tagService;
@ApiOperation(value = "新增或更新标签", notes = "新增或更新标签")
@PostMapping(value = "/addOrUpdateTag")
public Tag addTag(@RequestParam(value = "parentId", required = false) String parentId,
@RequestBody Tag tag) throws Exception {
String userName = UserInfoUtils.getUserName();
tag.setCreator(userName);
return tagService.addOrUpdateTag(parentId, tag);
}
// @PreAuthorize("principal.authorities.?[authority.startsWith('ROLE_tagmanager_admin')].size() > 0")
@ApiOperation(value = "查询系统标签树", notes = "查询系统标签树")
@PostMapping(value = "/querySystemTagAsTree")
public JsonNode[] querySystemTagAsTree(@RequestParam(value = "parentId", required = false) String parentId) throws Exception {
String userName = UserInfoUtils.getUserName();
return tagService.queryTagAsTreeByTagType(Constants.TAG_SYSTEM_TYPE, parentId, userName);
}
@ApiOperation(value = "查询个人标签树", notes = "查询个人标签树")
@PostMapping(value = "/queryPersonalTagAsTree")
public JsonNode[] queryPersonalTagAsTree(@RequestParam(value = "parentId", required = false) String parentId) throws Exception {
String userName = UserInfoUtils.getUserName();
return tagService.queryTagAsTreeByTagType(Constants.TAG_PERSONAL_TYPE, parentId, userName);
}
@ApiOperation(value = "搜索系統标签", notes = "搜索系統标签")
@PostMapping(value = "/searchSystemTagByPage")
public Page searchSystemTagByPage(@RequestParam(required = false, value = "keyword") String keyword,
@RequestParam(required = false, value = "domain") Integer domain,
@RequestParam("pageNo") Integer pageNo,
@RequestParam("pageSize") Integer pageSize) throws Exception {
String userName = UserInfoUtils.getUserName();
return tagService.searchSystemTagByPage(userName, keyword, domain, new Page(pageSize, pageNo));
}
@ApiOperation(value = "搜索个人标签", notes = "搜索个人标签")
@PostMapping(value = "/searchPersonalTagByPage")
public Page searchPersonalTagByPage(@RequestParam(required = false, value = "keyword") String keyword,
@RequestParam(required = false , value = "domain") Integer domain,
@RequestParam("pageNo") Integer pageNo,
@RequestParam("pageSize") Integer pageSize) throws Exception {
String userName = UserInfoUtils.getUserName();
return tagService.searchPersonalTagByPage(userName, keyword, domain, new Page(pageSize, pageNo));
}
}
...@@ -4,9 +4,15 @@ import java.util.List; ...@@ -4,9 +4,15 @@ import java.util.List;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.convert.CustomConversions;
import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration; import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.gridfs.GridFsTemplate; import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions; import com.mongodb.MongoClientOptions;
...@@ -17,6 +23,8 @@ import com.mongodb.ServerAddress; ...@@ -17,6 +23,8 @@ import com.mongodb.ServerAddress;
import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets; import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
@Configuration @Configuration
public class MongoDBConfig extends AbstractMongoConfiguration { public class MongoDBConfig extends AbstractMongoConfiguration {
...@@ -78,5 +86,20 @@ public class MongoDBConfig extends AbstractMongoConfiguration { ...@@ -78,5 +86,20 @@ public class MongoDBConfig extends AbstractMongoConfiguration {
return new MongoClient(clientURI); return new MongoClient(clientURI);
} }
} }
@Bean
public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
try {
mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
}
catch (NoSuchBeanDefinitionException ignore) {}
// Don't save _class to mongo
mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
return mappingConverter;
}
} }
...@@ -20,7 +20,7 @@ public class Swagger2Config { ...@@ -20,7 +20,7 @@ public class Swagger2Config {
return new Docket(DocumentationType.SWAGGER_2) return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()) .apiInfo(apiInfo())
.select() .select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.api")) .apis(RequestHandlerSelectors.basePackage("com.keymobile.tagmanager.api"))
.paths(PathSelectors.any()) .paths(PathSelectors.any())
.build(); .build();
} }
......
package com.keymobile.tagmanager.enums;
public enum RespCode {
SUCCESS(0, "请求成功"),
FAIL(-1, "请求失败");
private int code;
private String msg;
RespCode(int code, String msg) {
this.code=code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
package com.keymobile.tagmanager.enums;
public enum TagType {
SYSTEM("0", "系统标签"), PERSONAL("1", "个人标签");
private String code;
private String desc;
TagType(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getDesc() {
return desc;
}
public String getCode() {
return code;
}
public static String getTypeByCode(String code) {
for (TagType tagType : TagType.values()) {
if (tagType.getCode().equals(code)) return tagType.getDesc();
}
return "";
}
}
package com.keymobile.tagmanager.exception;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.springframework.http.HttpStatus;
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME, property = "error", visible = true)
class ApiError {
private HttpStatus status;
private Long timestamp;
private String message;
private String cnMessage;
private Throwable ex;
private ApiError() {
timestamp = System.currentTimeMillis();
}
ApiError(HttpStatus status) {
this();
this.status = status;
}
ApiError(HttpStatus status, Throwable ex) {
this();
this.status = status;
this.ex = ex;
}
ApiError(HttpStatus status, String message, Throwable ex) {
this();
this.status = status;
this.message = message;
this.ex = ex;
}
ApiError(HttpStatus status, String message, Throwable ex, String cnMessage) {
this();
this.status = status;
this.message = message;
this.setCnMessage(cnMessage);
this.ex = ex;
}
public void setEx(Throwable ex) {
this.ex = ex;
}
public Throwable getEx() {
return ex;
}
public HttpStatus getStatus() {
return status;
}
public Long getTimestamp() {
return timestamp;
}
public String getMessage() {
return message;
}
public String getCnMessage() {
return cnMessage;
}
public void setCnMessage(String cnMessage) {
this.cnMessage = cnMessage;
}
}
package com.keymobile.tagmanager.exception;
public class PrivilegeException extends Exception{
private static final long serialVersionUID = 1L;
public PrivilegeException(String errorMsg) {
super(errorMsg);
}
public PrivilegeException(String errorMsg, Throwable cause) {
super(errorMsg, cause);
}
}
package com.keymobile.tagmanager.exception;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
protected ResponseEntity<Object> handlException(Exception ex, WebRequest request){
logger.error(ex.getMessage(), ex);
return buildResponseEntity(new ApiError(INTERNAL_SERVER_ERROR, ex.getMessage(), ex, "网络异常"));
}
private ResponseEntity<Object> buildResponseEntity(ApiError apiError) {
return new ResponseEntity<>(apiError, apiError.getStatus());
}
}
package com.keymobile.tagmanager.exception;
public class TagDuplicateException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
public TagDuplicateException(String errorMsg) {
super(errorMsg);
}
public TagDuplicateException(String errorMsg, Throwable cause) {
super(errorMsg, cause);
}
}
package com.keymobile.tagmanager.exception;
public class TagException extends Exception{
private static final long serialVersionUID = 1L;
public TagException(String errorMsg) {
super(errorMsg);
}
public TagException(String errorMsg, Throwable cause) {
super(errorMsg, cause);
}
}
package com.keymobile.tagmanager.exception;
public class TagNotExistException extends Exception{
private static final long serialVersionUID = 1L;
public TagNotExistException(String errorMsg) {
super(errorMsg);
}
public TagNotExistException(String errorMsg, Throwable cause) {
super(errorMsg, cause);
}
}
package com.keymobile.tagmanager.model;
/**
* 分页辅助类
*
*/
public class Page {
private Long total;
private int pageNo;
private int pageSize;
private Object data;
public Page (int pageSize, int pageNo) {
this.pageSize = pageSize;
this.pageNo = pageNo;
}
public void setData(Object data) {
this.data = data;
}
public Object getData() {
return data;
}
public int getOffset() {
return pageSize * (pageNo - 1);
}
public int getFromIndex() {
return pageSize * (pageNo - 1);
}
public int getToIndex() {
return getFromIndex() + pageSize;
}
public int getLimit() {
// in order to support old style db2 grammar, limit = size * page
return pageSize * pageNo;
}
public void setTotal(Long total) {
this.total = total;
}
public Long getTotal() {
return total;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
package com.keymobile.tagmanager.model;
import java.io.Serializable;
import javax.persistence.Id;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.mongodb.core.mapping.Document;
import com.keymobile.tagmanager.util.Constants;
@Document(collection="Tag")
public class Tag implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
private String id;
private String name;
private String nameEn;
private String path;
private String desc;
private String imgId;
private Integer order;
private Integer level;
private String tagType; //0, 系统标签, 1 ,自定义标签
private String creator;
private String isOpen = Constants.TAG_CLOSE_STATUS; //0 不公开, 1, 公开
private Integer domain;
public Tag() {}
public Tag(String name, String desc) {
this.name = name;
this.desc = desc;
this.path = name;
}
public Tag(String parentPath, String name, String desc, String imgId) {
this.name = name;
this.desc = desc;
if (StringUtils.isEmpty(parentPath)) {
this.path = name;
} else {
this.path = parentPath + Constants.TAG_PATH_SEPARATOR + name;
}
this.imgId = imgId;
}
public Tag(String parentPath, String name, String id) {
this(parentPath, name, "", "");
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameEn() {
return nameEn;
}
public void setNameEn(String nameEn) {
this.nameEn = nameEn;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getImgId() {
return imgId;
}
public void setImgId(String imgId) {
this.imgId = imgId;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public String getTagType() {
return tagType;
}
public void setTagType(String tagType) {
this.tagType = tagType;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getIsOpen() {
return isOpen;
}
public void setIsOpen(String isOpen) {
this.isOpen = isOpen;
}
public Integer getDomain() {
return domain;
}
public void setDomain(Integer domain) {
this.domain = domain;
}
}
package com.keymobile.tagmanager.persistence;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.keymobile.tagmanager.model.Tag;
public interface TagRepository extends MongoRepository<Tag, String> {
}
package com.keymobile.tagmanager.service;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
@Service
public class CacheService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
RedisConnectionFactory redisConnectionFactory;
@Autowired
private MongoOperations mongoOperations;
@Value("${tableModel.redisKey.prefix:cmb}")
private String redisKeyPrefix;
@PostConstruct
public void init() {
}
}
package com.keymobile.tagmanager.util;
public final class Constants {
private Constants() {};
public static final Integer TABLEMODEL_PUBLISH_TYPE_ENABLE = 1;
public static final Integer TABLEMODEL_PUBLISH_TYPE_DISABLE = 2;
public static final Integer TABLEMODEL_PUBLISH_TYPE_INIT = 0;
public static final Integer TABLEMODEL_PREVIEW_STATUS_INIT = 0;
public static final Integer TABLEMODEL_PREVIEW_STATUS_SUCCESS = 1;
public static final Integer TABLEMODEL_PREVIEW_STATUS_RUNNING = 2;
public static final Integer TABLEMODEL_PREVIEW_STATUS_FAIL = 3;
public static final Integer TABLEMODEL_PREVIEW_SAMPLE_COUNT = 20;
public static final String TABLEMODEL_REDIS_KEY = "tableModel";
public static final String TABLEMODEL_HOTWORD_REDIS_TIME = "tableModel_hotword_time";
public static final String TABLEMODEL_HOTWORD_REDIS_KEY = "tableModel_hotword_key";
public static final String TABLEMODEL_DATABASE_REDIS_KEY = "database_key";
public static final String TABLEMODEL_USERDOMAIN_REDIS_KEY = "userDomain_key";
public static final String TABLEMODEL_USERROLE_REDIS_KEY = "userRole_key";
public static final long TABLEMODEL_REDIS_EXPIRE_TIME = 1000 * 60 * 60 * 24 * 1l;// 1 day
public static final long DATABASE_REDIS_EXPIRE_TIME = 1000 * 60 * 5l; //5 minute
public static final long USERDOMAIN_REDIS_EXPIRE_TIME = 1000 * 60 * 3l; //3 minute
public static final long USERROLE_REDIS_EXPIRE_TIME = 1000 * 60 * 3l; //3 minute
public static final String TABLEMODEL_INNERTYPE_SIMPLE = "simple";
public static final String TABLEMODEL_INNERTYPE_VIEW = "view";
public static final String TABLEMODEL_INNERTYPE_QUICK = "quick";
public static final String TABLEMODEL_DBTYPE_HANAVIEW = "HanaView";
public static final String TABLEMODEL_DBTYPE_TABLE = "Table";
public static final String DIR_ROOT_NODE_ID = "002c4155d13149a092129382e89a413f";
public static final String TAG_PERSONAL_TYPE = "1";
public static final String TAG_SYSTEM_TYPE = "0";
public static final String TAG_PATH_SEPARATOR = ",";
public static final String TAG_OPEN_STATUS = "1";
public static final String TAG_CLOSE_STATUS = "0";
public static final String PROCESS_AUDITSTATUS_APPLYING = "applying";
public static final String PROCESS_AUDITSTATUS_APPROVE = "approve";
public static final String PROCESS_AUDITSTATUS_REJECT = "reject";
public static final String PRIVILEGE_EXPIRE_TIME_STR = "3000-01-01";
public static final String REDIS_OPERATYPE_ADD = "add";
public static final String REDIS_OPERATYPE_DELETE = "delete";
public static final String REDIS_OPERATYPE_UPDATE = "update";
public static final String REDIS_OPERATYPE_FIND = "find";
public static final String MQ_METADATA_CREATE = "metadataCreate";
public static final String MQ_METADATA_UPDATE = "metadataUpdate";
public static final String MQ_METADATA_DELETE = "metadataDelete";
public static final String MQ_DATACATALOG_CREATE = "dataCatalogCreate";
public static final String MQ_DATACATALOG_DELETE = "dataCatalogDelete";
public static final String MQ_DATACATALOG_SAMPLE_CREATE = "dataCatalogSampleCreate";
public static final String MQ_DATACATALOG_ONCATALOG = "dataCatalogOnCatalog";
public static final String MQ_DATACATALOG_OFFCATALOG = "dataCatalogOffCatalog";
public static final String MQ_DATACATALOG_MODIFY = "dataCatalogModify";
public static final String MQ_DATACATALOG_TYPE_KEY = "type";
public static final String MQ_DATACATALOG_TIMESTAMP_KEY = "timestamp";
public static final String MQ_DATACATALOG_CONTENT_KEY = "content";
public static final String OPELOG_DAY_RESOURCE_VISIT_REDIS_KEY = "dailyResourceVisitState";
public static final String OPELOG_MONTH_RESOUCE_VISIT_REDIS_KEY = "monthlyResourceVisitState";
public static final String OPELOG_DAY_USER_VISIT_REDIS_KEY = "dailyUserVisitState";
public static final String OPELOG_MONTH_TOPVISIT_USER_REDIS_KEY = "monthlyTopVisitUserState";
public static final String ORG_QUERY_SQL = "select SPP_ID, SUBSPP_TYPE, SUBSPP_NAM, SUBSPP_ID FROM DIM_SUBSPP";
}
package com.keymobile.tagmanager.util;
import java.util.List;
public class JsonTreeHelper {
public static class JsonNode {
public String text;
public JsonNode[] children;
public String nodeId;
public String tagType;
public String path;
public JsonNode(String text) {
this.text = text;
}
public JsonNode(String text, String nodeId, String path) {
this.text = text;
this.path = path;
this.nodeId = nodeId;
}
public void addChild(JsonNode child) {
if (children == null) {
children = new JsonNode[] { child };
} else {
JsonNode[] origin = children;
children = new JsonNode[origin.length + 1];
for (int i = 0; i < origin.length; i++) {
children[i] = origin[i];
}
children[origin.length] = child;
}
}
public int getChildSize() {
if (children == null)
return 0;
else
return children.length;
}
}
public static JsonNode toJsonTree(List<JsonNode> jsonNodes, String separator) {
JsonNode root = new JsonNode("root");
for (JsonNode jsonNode : jsonNodes) {
JsonNode current = root;
String[] parts = jsonNode.text.split(separator);
for (String part : parts) {
JsonNode subNode = null;
if (current.getChildSize() == 0) {
subNode = new JsonNode(part, jsonNode.nodeId, jsonNode.path);
current.addChild(subNode);
} else {
for (JsonNode node : current.children) {
if (node.text.equals(part))
subNode = node;
}
if (subNode == null) {
subNode = new JsonNode(part, jsonNode.nodeId, jsonNode.path);
current.addChild(subNode);
}
}
current = subNode;
}
}
return root;
}
}
package com.keymobile.tagmanager.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import com.keymobile.tagmanager.model.Page;
public class MongoOperationsUtil {
private static final String splitMarker = "::";
public static Query createQueryWithSpecifiedField(Map<String, Object> condition, List<String> specifields) {
Document fieldsObject = new Document();
specifields.forEach(field -> fieldsObject.put(field, 1));
Document dbObject = new Document();
condition.forEach((k, v) -> {
dbObject.put(k, v);
});
return new BasicQuery(dbObject, fieldsObject);
}
public static Query createQueryWithSpecifiedField(Map<String, Object> condition, List<String> specifields, Page page) {
return createQueryWithSpecifiedField(condition, specifields, page, new ArrayList<>());
}
public static Query createBasicQuery(Map<String, Object> condition,List<String> specifields) {
Document fieldsObject = new Document();
specifields.forEach(field -> fieldsObject.put(field, 1));
Document dbObject = new Document();
condition.forEach((k, v) -> {
dbObject.put(k, v);
});
return new BasicQuery(dbObject, fieldsObject);
}
public static Query createQueryWithSpecifiedField(Map<String, Object> condition, List<String> specifields, Page page, List<Order> orderList) {
Document fieldsObject = new Document();
specifields.forEach(field -> fieldsObject.put(field, 1));
Document dbObject = new Document();
condition.forEach((k, v) -> {
dbObject.put(k, v);
});
Query q = new BasicQuery(dbObject, fieldsObject);
q.skip(page.getOffset());
q.limit(page.getPageSize());
if (orderList != null && !orderList.isEmpty()) {
q.with(Sort.by(orderList));
}
return q;
}
public static Query createQueryWithSpecifiedField(List<String> specifields) {
Map<String, Object> condition = new HashMap<>();
return createQueryWithSpecifiedField(condition, specifields);
}
private static void buildQuery(String key, Object value, Query query) {
if (key.contains("_id")) {
query.addCriteria(Criteria.where(key).is(new ObjectId(value.toString())));
} else {
if (value instanceof Integer || value instanceof Float
|| value instanceof Double || value instanceof Boolean) {
query.addCriteria(Criteria.where(key).is(value));
} else if (value instanceof List) {
query.addCriteria(Criteria.where(key).in(value));
}else {
query.addCriteria(Criteria.where(key).is(value));
}
}
}
public static Query buildQuery(Map<String, Object> paramMap) {
Query query = new Query();
for (String key : paramMap.keySet()) {
buildQuery(key, paramMap.get(key), query);
}
return query;
}
public static Query buildQueryByKV(String key, Object value) {
Query query = new Query();
buildQuery(key, value, query);
return query;
}
public static Query buildQueryByOrder(Map<String, Object> paramMap, List<Order> orderList) {
Query query = new Query();
for (String key : paramMap.keySet()) {
buildQuery(key, paramMap.get(key), query);
}
if (orderList != null && orderList.size() > 0) {
query.with(Sort.by(orderList));
}
return query;
}
public static Map<String, Object> addSearchCriteria(List<String> searchColumns, String keyword, Map<String, Object> condition) {
Pattern pattern = Pattern.compile("^.*" + keyword + ".*$");
List<Document> documents = new ArrayList<>();
searchColumns.forEach(column -> {
Document value = new Document("$regex", pattern);
value.put("$options", "i");
documents.add(new Document(column, value));
});
condition.put("$or", documents);
return condition;
}
public static Query buildQueryByPage(Map<String, Object> paramMap, List<Order> orderList, Integer pageSize, Integer startIndex) {
Query query = new Query();
if (paramMap != null && paramMap.size() > 0) {
for (String key : paramMap.keySet()) {
Object value = paramMap.get(key);
if (key.contains(splitMarker)) {/*// 处理关联查询的情况
String[] arr = key.split(this.splitMarker);
if (arr.length != 2) {
continue;
}
String p1 = arr[0];
String p2 = arr[1];
Class<T> clazz = ReflectUtils.getSuperClassGenricType(getClass());
Field[] fs = this.getAllFields(clazz);
// ReflectUtils.getAllFields(clazz);
Class<?> clazz1 = null;
for (Field f : fs) {
if (f.getName().equals(p1)) {
clazz1 = f.getType();
break;
}
}
Query query0 = new Query();
this.buildQuery(p2, value, query0);
query.addCriteria(Criteria.where(p1).in(mongoOper.find(query0, clazz1)));
*/} else {
buildQuery(key, value, query);
}
}
}
if (orderList != null && orderList.size() > 0) {
query.with(Sort.by(orderList));
}
if (pageSize != 0) {
query.skip(startIndex);
query.limit(pageSize);
}
return query;
}
}
package com.keymobile.tagmanager.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
public class UserInfoUtils {
public final static String ADMIN = "ROLE_dataCatalog_admin";
public final static String OPERATOR = "ROLE_dataCatalog_operator";
public final static String USER= "ROLE_dataCatalog_user";
public static List<String> getUserRoles() {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
List<String> roles = new ArrayList<>();
userDetails.getAuthorities().forEach(auth -> roles.add(auth.getAuthority()));
return roles;
}
public static List<Integer> getUserDomains() {
List<String> roles = UserInfoUtils.getUserRoles();
String role = "";
for (String r : roles) {
if (r.startsWith(UserInfoUtils.ADMIN) || r.startsWith(UserInfoUtils.OPERATOR)) {
role = r;
break;
}
}
// ADMIN:1,2
List<Integer> domainIds = new ArrayList<>();
if (StringUtils.isEmpty(role)) return domainIds;
if (role.split(":")[1].equals("*")) return domainIds;
for (String domain : role.split(":")[1].split(",")) {
domainIds.add(Integer.valueOf(domain));
}
return domainIds;
}
public static String getUserName() {
return SecurityContextHolder.getContext().getAuthentication().getName().split(":")[0];
}
public static Integer getUserId() {
return Integer.valueOf(SecurityContextHolder.getContext().getAuthentication().getName().split(":")[1]);
}
}
#Generated by Maven Integration for Eclipse #Generated by Maven Integration for Eclipse
#Tue Nov 26 16:11:31 CST 2019 #Thu Nov 28 10:08:13 CST 2019
version=1.0.2-SNAPSHOT version=1.0.2-SNAPSHOT
groupId=com.keymobile groupId=com.keymobile
m2e.projectName=tagManager m2e.projectName=tagManager
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment