Commit 367267a8 by lanmw

deleteTag

parent e2de8df7
package com.keymobile.tagmanager.api; package com.keymobile.tagmanager.api;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; 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.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.keymobile.tagmanager.model.Page; import com.keymobile.tagmanager.model.Page;
import com.keymobile.tagmanager.model.Tag; import com.keymobile.tagmanager.model.Tag;
import com.keymobile.tagmanager.service.TagService; import com.keymobile.tagmanager.service.TagService;
import com.keymobile.tagmanager.util.Constants;
import com.keymobile.tagmanager.util.JsonTreeHelper.JsonNode; import com.keymobile.tagmanager.util.JsonTreeHelper.JsonNode;
import com.keymobile.tagmanager.util.UserInfoUtils; import com.keymobile.tagmanager.util.UserInfoUtils;
...@@ -32,36 +31,49 @@ public class TagCtrl { ...@@ -32,36 +31,49 @@ public class TagCtrl {
@RequestBody Tag tag) throws Exception { @RequestBody Tag tag) throws Exception {
String userName = UserInfoUtils.getUserName(); String userName = UserInfoUtils.getUserName();
tag.setCreator(userName); tag.setCreator(userName);
return tagService.addOrUpdateTag(parentId, tag); return tagService.addOrUpdateTag(parentId, tag, userName);
} }
@ApiOperation(value = "删除标签", notes = "删除标签")
@PostMapping(value = "/deleteTag")
public void deleteTag(@RequestParam(value = "tagId") String tagId) throws Exception {
String userName = UserInfoUtils.getUserName();
tagService.deleteTag(tagId, userName);
}
@ApiOperation(value = "存在节点", notes = "存在节点")
@GetMapping(value = "/hasChild")
public boolean hasChild(@RequestParam(value = "tagId") String tagId) throws Exception {
String userName = UserInfoUtils.getUserName();
return tagService.hasChild(tagId, userName);
}
// @PreAuthorize("principal.authorities.?[authority.startsWith('ROLE_tagmanager_admin')].size() > 0") // @PreAuthorize("principal.authorities.?[authority.startsWith('ROLE_tagmanager_admin')].size() > 0")
@ApiOperation(value = "查询系统标签树", notes = "查询系统标签树") @ApiOperation(value = "查询系统标签树", notes = "查询系统标签树")
@PostMapping(value = "/querySystemTagAsTree") @GetMapping(value = "/querySystemTagAsTree")
public JsonNode[] querySystemTagAsTree(@RequestParam(value = "parentId", required = false) String parentId) throws Exception { public JsonNode[] querySystemTagAsTree(@RequestParam(value = "parentId", required = false) String parentId) throws Exception {
String userName = UserInfoUtils.getUserName(); return tagService.querySystemTagAsTree(parentId);
return tagService.queryTagAsTreeByTagType(Constants.TAG_SYSTEM_TYPE, parentId, userName);
} }
@ApiOperation(value = "查询个人标签树", notes = "查询个人标签树") @ApiOperation(value = "查询个人标签树", notes = "查询个人标签树")
@PostMapping(value = "/queryPersonalTagAsTree") @GetMapping(value = "/queryPersonalTagAsTree")
public JsonNode[] queryPersonalTagAsTree(@RequestParam(value = "parentId", required = false) String parentId) throws Exception { public JsonNode[] queryPersonalTagAsTree(@RequestParam(value = "parentId", required = false) String parentId) throws Exception {
String userName = UserInfoUtils.getUserName(); String userName = UserInfoUtils.getUserName();
return tagService.queryTagAsTreeByTagType(Constants.TAG_PERSONAL_TYPE, parentId, userName); return tagService.queryPersonalTagAsTree(parentId, userName);
} }
@ApiOperation(value = "搜索系統标签", notes = "搜索系統标签") @ApiOperation(value = "搜索系統标签", notes = "搜索系統标签")
@PostMapping(value = "/searchSystemTagByPage") @GetMapping(value = "/searchSystemTagByPage")
public Page searchSystemTagByPage(@RequestParam(required = false, value = "keyword") String keyword, public Page searchSystemTagByPage(@RequestParam(required = false, value = "keyword") String keyword,
@RequestParam(required = false, value = "domain") Integer domain, @RequestParam(required = false, value = "domain") Integer domain,
@RequestParam("pageNo") Integer pageNo, @RequestParam("pageNo") Integer pageNo,
@RequestParam("pageSize") Integer pageSize) throws Exception { @RequestParam("pageSize") Integer pageSize) throws Exception {
String userName = UserInfoUtils.getUserName(); return tagService.searchSystemTagByPage(keyword, domain, new Page(pageSize, pageNo));
return tagService.searchSystemTagByPage(userName, keyword, domain, new Page(pageSize, pageNo));
} }
@ApiOperation(value = "搜索个人标签", notes = "搜索个人标签") @ApiOperation(value = "搜索个人标签", notes = "搜索个人标签")
@PostMapping(value = "/searchPersonalTagByPage") @GetMapping(value = "/searchPersonalTagByPage")
public Page searchPersonalTagByPage(@RequestParam(required = false, value = "keyword") String keyword, public Page searchPersonalTagByPage(@RequestParam(required = false, value = "keyword") String keyword,
@RequestParam(required = false , value = "domain") Integer domain, @RequestParam(required = false , value = "domain") Integer domain,
@RequestParam("pageNo") Integer pageNo, @RequestParam("pageNo") Integer pageNo,
......
package com.keymobile.tagmanager.service; package com.keymobile.tagmanager.service;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -18,11 +15,8 @@ import org.springframework.data.domain.Sort.Order; ...@@ -18,11 +15,8 @@ import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.keymobile.tagmanager.exception.TagDuplicateException; import com.keymobile.tagmanager.exception.TagDuplicateException;
import com.keymobile.tagmanager.exception.TagException; import com.keymobile.tagmanager.exception.TagException;
import com.keymobile.tagmanager.exception.TagNotExistException; import com.keymobile.tagmanager.exception.TagNotExistException;
...@@ -39,114 +33,31 @@ public class TagService { ...@@ -39,114 +33,31 @@ public class TagService {
@Autowired @Autowired
private MongoOperations mongoOperations; private MongoOperations mongoOperations;
@Autowired
private GridFsTemplate gridFsTemplate;
@Autowired @Autowired
private TagRepository tagRepository; private TagRepository tagRepository;
private Logger logger = LoggerFactory.getLogger(TagService.class); private Logger logger = LoggerFactory.getLogger(TagService.class);
public Tag addOrUpdateTag(Tag tag, MultipartFile file) throws Exception { public Tag addOrUpdateTag(String parentId, Tag tag, String userName) throws TagNotExistException, TagDuplicateException, TagException {
checkTagValid(tag); tag.setPath(tag.getName());
if (!StringUtils.isEmpty(parentId)) {
Tag parent = getTagById(parentId);
tag.setPath(parent.getPath() + Constants.TAG_PATH_SEPARATOR + tag.getName());
}
checkTagValid(tag, userName);
if (!StringUtils.isEmpty(tag.getId())) { if (!StringUtils.isEmpty(tag.getId())) {
Tag origin = mongoOperations.findOne(Query.query(Criteria.where("_id").is(tag.getId())), Tag.class); Tag origin = mongoOperations.findOne(Query.query(Criteria.where("_id").is(tag.getId())), Tag.class);
List<Tag> relationTags = mongoOperations.find( List<Tag> relationTags = mongoOperations.find(
Query.query(Criteria.where("path").regex("^" + origin.getPath() + Constants.TAG_PATH_SEPARATOR)), Query.query(Criteria.where("path").regex("^" + origin.getPath() + Constants.TAG_PATH_SEPARATOR)
Tag.class); .and("creator").is(userName)), Tag.class);
relationTags.forEach(p -> { relationTags.forEach(p -> {
p.setPath(p.getPath().replaceAll(origin.getPath(), tag.getPath())); p.setPath(p.getPath().replaceAll(origin.getPath(), tag.getPath()));
}); });
tagRepository.saveAll(relationTags); tagRepository.saveAll(relationTags);
if (!StringUtils.isEmpty(file)) {
removeFileInMongoDB(Arrays.asList(origin.getImgId()));
}
}
if (!StringUtils.isEmpty(file)) {
String fileId = saveFileInMongoDB(file);
tag.setImgId(fileId);
} }
tag.setLevel(tag.getPath().split(",").length); tag.setLevel(tag.getPath().split(",").length);
return tagRepository.save(tag); return tagRepository.save(tag);
} }
public void removeFileInMongoDB(List<String> fileIds) {
gridFsTemplate.delete(Query.query(Criteria.where("_id").in(fileIds)));
}
public String saveFileInMongoDB(MultipartFile file) throws Exception {
ObjectId gridFSFile = gridFsTemplate.store(file.getInputStream(), file.getOriginalFilename(),
file.getContentType());
return gridFSFile.toString();
}
private void checkTagValid(Tag tag) throws TagDuplicateException, TagException {
if (!Constants.TAG_PERSONAL_TYPE.equals(tag.getTagType())
&& !Constants.TAG_SYSTEM_TYPE.equals(tag.getTagType())) {
throw new TagException(String.format("No such tagType %s", tag.getTagType()));
}
Tag t = mongoOperations.findOne(Query.query(Criteria.where("path").is(tag.getPath())), Tag.class);
if (t != null && !t.getId().equals(tag.getId()))
throw new TagDuplicateException("tag [" + tag.getName() + "] is already exist in target!");
}
public JsonNode[] querySubTagAsTree(String dirId) {
List<Tag> tags = new ArrayList<>();
List<Order> orders = new ArrayList<>();
orders.add(new Order(Direction.ASC, "level"));
orders.add(new Order(Direction.DESC, "order"));
if (StringUtils.isEmpty(dirId)) {
tags = mongoOperations.find(new Query().with(Sort.by(orders)), Tag.class);
} else {
Tag t = mongoOperations.findOne(Query.query(Criteria.where("_id").is(dirId)), Tag.class);
tags = getSubTagByParentDir(t);
tags.forEach(d -> d.setPath(d.getPath().replaceAll(t.getPath(), t.getName())));
}
List<JsonNode> nodes = new ArrayList<>();
tags.forEach(p -> {
JsonNode node = new JsonNode(p.getPath(), p.getId(), p.getPath());
nodes.add(node);
});
JsonNode root = JsonTreeHelper.toJsonTree(nodes, Constants.TAG_PATH_SEPARATOR);
if (root.children != null)
return root.children;
else
return new JsonNode[] {};
}
public int deleteTags(List<String> tagIds) {
int success = 0;
List<Tag> tags = mongoOperations.find(Query.query(Criteria.where("_id").in(tagIds)), Tag.class);
for (Tag t : tags) {
try {
List<Tag> subTags = getSubTagByParentDir(t);
List<String> subTagIds = subTags.stream().map(subTag -> subTag.getId()).collect(Collectors.toList());
List<String> subTagImgIds = subTags.stream().map(subTag -> subTag.getImgId())
.collect(Collectors.toList());
removeFileInMongoDB(subTagImgIds);
mongoOperations.findAllAndRemove(Query.query(Criteria.where("_id").in(subTagIds)), Tag.class);
success++;
} catch (Exception e) {
logger.error("deleteTag error.", e);
}
}
return success;
}
private List<Tag> getSubTagByParentDir(Tag parentTag) {
List<Order> orders = new ArrayList<>();
orders.add(new Order(Direction.ASC, "level"));
orders.add(new Order(Direction.DESC, "order"));
List<Tag> dirs = mongoOperations.find(new Query()
.addCriteria(Criteria.where("path").regex("^" + parentTag.getPath() + Constants.TAG_PATH_SEPARATOR))
.with(Sort.by(orders)), Tag.class);
dirs.add(parentTag);
return dirs;
}
public Tag getTagById(String tagId) throws TagNotExistException { public Tag getTagById(String tagId) throws TagNotExistException {
Tag t = mongoOperations.findOne(Query.query(Criteria.where("_id").is(tagId)), Tag.class); Tag t = mongoOperations.findOne(Query.query(Criteria.where("_id").is(tagId)), Tag.class);
...@@ -155,53 +66,26 @@ public class TagService { ...@@ -155,53 +66,26 @@ public class TagService {
return t; return t;
} }
public boolean checkDirExistTags(String dirId) {
Tag origin = mongoOperations.findOne(Query.query(Criteria.where("_id").is(dirId)), Tag.class); private void checkTagValid(Tag tag, String userName) throws TagDuplicateException, TagException {
List<Tag> relationTags = mongoOperations.find( if (!Constants.TAG_PERSONAL_TYPE.equals(tag.getTagType())
Query.query(Criteria.where("path") && !Constants.TAG_SYSTEM_TYPE.equals(tag.getTagType())) {
.regex("^" + origin.getPath() + Constants.TAG_PATH_SEPARATOR) throw new TagException(String.format("No such tagType %s", tag.getTagType()));
.and("level").is(origin.getLevel() + 1)),
Tag.class);
for (Tag childTag : relationTags) {
if (childTag.getTagType().equals(Constants.TAG_PERSONAL_TYPE))
return true;
} }
return false; Tag t = mongoOperations.findOne(Query.query(Criteria.where("path").is(tag.getPath())
} .and("creator").is(userName)), Tag.class);
if (t != null && !t.getId().equals(tag.getId()))
throw new TagDuplicateException("tag [" + tag.getName() + "] is already exist in target!");
public Tag addOrUpdateTag(String parentId, Tag tag) throws TagNotExistException, TagDuplicateException, TagException {
tag.setPath(tag.getName());
if (!StringUtils.isEmpty(parentId) && StringUtils.isEmpty(tag.getId())) {
Tag parent = getTagById(parentId);
tag.setPath(parent.getPath() + Constants.TAG_PATH_SEPARATOR + tag.getName());
}
checkTagValid(tag);
if (!StringUtils.isEmpty(tag.getId())) {
Tag origin = mongoOperations.findOne(Query.query(Criteria.where("_id").is(tag.getId())), Tag.class);
List<Tag> relationTags = mongoOperations.find(
Query.query(Criteria.where("path").regex("^" + origin.getPath() + Constants.TAG_PATH_SEPARATOR)),
Tag.class);
relationTags.forEach(p -> {
p.setPath(p.getPath().replaceAll(origin.getPath(), tag.getPath()));
});
tagRepository.saveAll(relationTags);
}
tag.setLevel(tag.getPath().split(",").length);
return tagRepository.save(tag);
} }
public JsonNode[] queryTagAsTreeByTagType(String tagType, String parentId, String userName) throws TagNotExistException { public JsonNode[] queryPersonalTagAsTree(String parentId, String userName) throws TagNotExistException {
List<Tag> tags = new ArrayList<>(); List<Tag> tags = new ArrayList<>();
if (StringUtils.isEmpty(parentId)) { if (StringUtils.isEmpty(parentId)) {
tags = mongoOperations.find(Query.query(Criteria tags = mongoOperations.find(createPersonalTagQuery(userName), Tag.class);
.where("tagType").is(tagType)
.orOperator(
Criteria.where("openStatus").is(Constants.TAG_OPEN_STATUS),
Criteria.where("creator").is(userName)))
.with(Sort.by(getDefaultTagOrders())), Tag.class);
} else { } else {
Tag parentTag = getTagById(parentId); Tag parentTag = getTagById(parentId);
tags = getSubDirByParentDir(parentTag, tagType, userName); tags = getPersonSubTag(parentTag, userName);
tags.forEach(tag -> tag.setPath(tag.getPath().replaceAll(parentTag.getPath(), parentTag.getName()))); tags.forEach(tag -> tag.setPath(tag.getPath().replaceAll(parentTag.getPath(), parentTag.getName())));
} }
List<JsonNode> nodes = new ArrayList<>(); List<JsonNode> nodes = new ArrayList<>();
...@@ -215,6 +99,14 @@ public class TagService { ...@@ -215,6 +99,14 @@ public class TagService {
else else
return new JsonNode[] {}; return new JsonNode[] {};
} }
private Query createPersonalTagQuery(String userName) {
return Query.query(Criteria.where("tagType").is(Constants.TAG_PERSONAL_TYPE)
.orOperator(
Criteria.where("isOpen").is(Constants.TAG_OPEN_STATUS),
Criteria.where("creator").is(userName)))
.with(Sort.by(getDefaultTagOrders()));
}
private List<Order> getDefaultTagOrders() { private List<Order> getDefaultTagOrders() {
List<Order> orders = new ArrayList<>(); List<Order> orders = new ArrayList<>();
...@@ -223,38 +115,28 @@ public class TagService { ...@@ -223,38 +115,28 @@ public class TagService {
return orders; return orders;
} }
public List<Tag> getSubDirByParentDir(Tag parentTag, String tagType, String userName) { public List<Tag> getPersonSubTag(Tag parentTag, String userName) {
List<Tag> dirs = mongoOperations.find(new Query().addCriteria(Criteria.where("path") List<Tag> dirs = mongoOperations.find(new Query().addCriteria(Criteria.where("path")
.regex("^"+parentTag.getPath() + Constants.TAG_PATH_SEPARATOR) .regex("^"+parentTag.getPath() + Constants.TAG_PATH_SEPARATOR)
.and("tagType").is(tagType) .and("tagType").is(Constants.TAG_PERSONAL_TYPE)
.orOperator( .orOperator(
Criteria.where("openStatus").is(Constants.TAG_OPEN_STATUS), Criteria.where("openStatus").is(Constants.TAG_OPEN_STATUS),
Criteria.where("creator").is(userName))) Criteria.where("creator").is(userName)))
.with(Sort.by(getDefaultTagOrders())), Tag.class); .with(Sort.by(getDefaultTagOrders())), Tag.class);
dirs.add(parentTag); dirs.add(parentTag);
return dirs; return dirs;
} }
public Page searchPersonalTagByPage(String userName, String keyword, Integer domain, public Page searchPersonalTagByPage(String userName, String keyword, Integer domain, Page page) {
com.keymobile.tagmanager.model.Page page) { Query q = createPersonalTagQuery(userName);
Map<String, Object> or1 = new HashMap<>(); if (org.apache.commons.lang.StringUtils.isNotBlank(keyword) && !"*".equals(keyword)) {
Map<String, Object> or2 = new HashMap<>(); Criteria c = new Criteria();
if (org.apache.commons.lang.StringUtils.isNotBlank(keyword) && !"*".equals(keyword)) { c.orOperator(createRegexQuery(Arrays.asList("name", "nameEn", "desc"), keyword));
MongoOperationsUtil.addSearchCriteria(Arrays.asList("name", "nameEn", "desc"), keyword, or1); q.addCriteria(c);
MongoOperationsUtil.addSearchCriteria(Arrays.asList("name", "nameEn", "desc"), keyword, or2);
} }
or1.put("tagType", Constants.TAG_PERSONAL_TYPE); q.skip(page.getOffset());
or1.put("creator", userName); q.limit(page.getPageSize());
or2.put("tagType", Constants.TAG_PERSONAL_TYPE);
or2.put("openStatus", Constants.TAG_OPEN_STATUS);
Map<String, Object> condition = new HashMap<>();
condition.put("$or", Arrays.asList(or1, or2));
Query q = MongoOperationsUtil.createQueryWithSpecifiedField(condition,
Arrays.asList("name", "nameEN", "isOpen", "creator", "desc"),
page, Arrays.asList(new Order(Direction.ASC, "name")));
List<Tag> tags = mongoOperations List<Tag> tags = mongoOperations
.find(q, Tag.class); .find(q, Tag.class);
long count = mongoOperations.count(q, Tag.class); long count = mongoOperations.count(q, Tag.class);
...@@ -263,24 +145,82 @@ public class TagService { ...@@ -263,24 +145,82 @@ public class TagService {
return page; return page;
} }
private Criteria[] createRegexQuery(List<String> asList, String keyword) {
return asList.stream().map(col -> {
return Criteria.where(col).regex(keyword, "i");
}).collect(Collectors.toList()).toArray(new Criteria[0]);
}
public JsonNode[] querySystemTagAsTree(String parentId) throws TagNotExistException {
List<Tag> tags = new ArrayList<>();
if (StringUtils.isEmpty(parentId)) {
tags = mongoOperations.find(Query.query(Criteria
.where("tagType").is(Constants.TAG_SYSTEM_TYPE)).with(Sort.by(getDefaultTagOrders())), Tag.class);
} else {
Tag parentTag = getTagById(parentId);
tags = getSystemSubTag(parentTag);
tags.forEach(tag -> tag.setPath(tag.getPath().replaceAll(parentTag.getPath(), parentTag.getName())));
}
List<JsonNode> nodes = new ArrayList<>();
tags.forEach(p -> {
JsonNode node = new JsonNode(p.getPath(), p.getId(), p.getPath());
nodes.add(node);
});
JsonNode root = JsonTreeHelper.toJsonTree(nodes, Constants.TAG_PATH_SEPARATOR);
if (root.children != null)
return root.children;
else
return new JsonNode[] {};
}
public Page searchSystemTagByPage(String userName, String keyword, Integer domain, Page page) { public Page searchSystemTagByPage(String keyword, Integer domain, Page page) {
Map<String, Object> condition = new HashMap<>(); Map<String, Object> condition = new HashMap<>();
if (org.apache.commons.lang.StringUtils.isNotBlank(keyword) && !"*".equals(keyword)) { if (org.apache.commons.lang.StringUtils.isNotBlank(keyword) && !"*".equals(keyword)) {
MongoOperationsUtil.addSearchCriteria(Arrays.asList("name", "nameEn", "desc"), keyword, condition); MongoOperationsUtil.addSearchCriteria(Arrays.asList("name", "nameEn", "desc"), keyword, condition);
} }
condition.put("tagType", Constants.TAG_SYSTEM_TYPE); condition.put("tagType", Constants.TAG_SYSTEM_TYPE);
Query q = MongoOperationsUtil.createQueryWithSpecifiedField(condition, Query q = MongoOperationsUtil.createQueryWithSpecifiedField(condition, page, getDefaultTagOrders());
Arrays.asList("name", "nameEN", "isOpen", "creator", "desc"), List<Tag> tags = mongoOperations.find(q, Tag.class);
page, Arrays.asList(new Order(Direction.ASC, "name")));
List<Tag> tags = mongoOperations
.find(q, Tag.class);
long count = mongoOperations.count(q, Tag.class); long count = mongoOperations.count(q, Tag.class);
page.setData(tags); page.setData(tags);
page.setTotal(count); page.setTotal(count);
return page; return page;
} }
private List<Tag> getSystemSubTag(Tag parentTag) {
List<Tag> dirs = mongoOperations.find(new Query().addCriteria(Criteria.where("path")
.regex("^"+parentTag.getPath() + Constants.TAG_PATH_SEPARATOR)
.and("tagType").is(Constants.TAG_SYSTEM_TYPE))
.with(Sort.by(getDefaultTagOrders())), Tag.class);
dirs.add(parentTag);
return dirs;
}
public void deleteTag(String tagId, String userName) throws TagException {
Optional<Tag> optional = tagRepository.findById(tagId);
if (optional.isPresent()) {
Tag parentTag = optional.get();
List<Tag> childs = mongoOperations.find(Query.query(Criteria.where("path")
.regex("^"+parentTag.getPath() + Constants.TAG_PATH_SEPARATOR)
.and("creator").is(userName)), Tag.class);
if (!childs.isEmpty()) {
throw new TagException("存在子节点,不允许删除!");
}
tagRepository.deleteById(tagId);
}
}
public boolean hasChild(String tagId, String userName) throws TagException {
Optional<Tag> optional = tagRepository.findById(tagId);
if (optional.isPresent()) {
Tag parentTag = optional.get();
List<Tag> childs = mongoOperations.find(Query.query(Criteria.where("path")
.regex("^"+parentTag.getPath() + Constants.TAG_PATH_SEPARATOR)
.and("creator").is(userName)), Tag.class);
return !childs.isEmpty();
}
return false;
}
} }
package com.keymobile.tagmanager.util; package com.keymobile.tagmanager.util;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.bson.Document; import org.bson.Document;
import org.bson.types.ObjectId; import org.bson.types.ObjectId;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order; import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.query.BasicQuery; import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Query;
import com.keymobile.tagmanager.model.Page; import com.keymobile.tagmanager.model.Page;
public class MongoOperationsUtil { public class MongoOperationsUtil {
private static final String splitMarker = "::"; private static final String splitMarker = "::";
public static Query createQueryWithSpecifiedField(Map<String, Object> condition, List<String> specifields) { public static Query createQueryWithSpecifiedField(Map<String, Object> condition, List<String> specifields) {
Document fieldsObject = new Document(); Document fieldsObject = new Document();
specifields.forEach(field -> fieldsObject.put(field, 1)); specifields.forEach(field -> fieldsObject.put(field, 1));
Document dbObject = new Document(); Document dbObject = new Document();
condition.forEach((k, v) -> { condition.forEach((k, v) -> {
dbObject.put(k, v); dbObject.put(k, v);
}); });
return new BasicQuery(dbObject, fieldsObject); return new BasicQuery(dbObject, fieldsObject);
} }
public static Query createQueryWithSpecifiedField(Map<String, Object> condition, List<String> specifields, Page page) { public static Query createQueryWithSpecifiedField(Map<String, Object> condition, List<String> specifields, Page page) {
return createQueryWithSpecifiedField(condition, specifields, page, new ArrayList<>()); return createQueryWithSpecifiedField(condition, specifields, page, new ArrayList<>());
} }
public static Query createBasicQuery(Map<String, Object> condition,List<String> specifields) { public static Query createBasicQuery(Map<String, Object> condition,List<String> specifields) {
Document fieldsObject = new Document(); Document fieldsObject = new Document();
specifields.forEach(field -> fieldsObject.put(field, 1)); specifields.forEach(field -> fieldsObject.put(field, 1));
Document dbObject = new Document(); Document dbObject = new Document();
condition.forEach((k, v) -> { condition.forEach((k, v) -> {
dbObject.put(k, v); dbObject.put(k, v);
}); });
return new BasicQuery(dbObject, fieldsObject); return new BasicQuery(dbObject, fieldsObject);
} }
public static Query createQueryWithSpecifiedField(Map<String, Object> condition, List<String> specifields, Page page, List<Order> orderList) { public static Query createQueryWithSpecifiedField(Map<String, Object> condition, List<String> specifields, Page page, List<Order> orderList) {
Document fieldsObject = new Document(); Document fieldsObject = new Document();
specifields.forEach(field -> fieldsObject.put(field, 1)); specifields.forEach(field -> fieldsObject.put(field, 1));
Document dbObject = new Document(); Document dbObject = new Document();
condition.forEach((k, v) -> { condition.forEach((k, v) -> {
dbObject.put(k, v); dbObject.put(k, v);
}); });
Query q = new BasicQuery(dbObject, fieldsObject); Query q = new BasicQuery(dbObject, fieldsObject);
q.skip(page.getOffset()); q.skip(page.getOffset());
q.limit(page.getPageSize()); q.limit(page.getPageSize());
if (orderList != null && !orderList.isEmpty()) { if (orderList != null && !orderList.isEmpty()) {
q.with(Sort.by(orderList)); q.with(Sort.by(orderList));
} }
return q; return q;
} }
public static Query createQueryWithSpecifiedField(List<String> specifields) { public static Query createQueryWithSpecifiedField(Map<String, Object> condition, Page page, List<Order> orderList) {
Map<String, Object> condition = new HashMap<>(); Document dbObject = new Document();
return createQueryWithSpecifiedField(condition, specifields); condition.forEach((k, v) -> {
} dbObject.put(k, v);
});
Query q = new BasicQuery(dbObject);
private static void buildQuery(String key, Object value, Query query) { q.skip(page.getOffset());
if (key.contains("_id")) { q.limit(page.getPageSize());
query.addCriteria(Criteria.where(key).is(new ObjectId(value.toString()))); if (orderList != null && !orderList.isEmpty()) {
} else { q.with(Sort.by(orderList));
if (value instanceof Integer || value instanceof Float }
|| value instanceof Double || value instanceof Boolean) { return q;
query.addCriteria(Criteria.where(key).is(value)); }
} else if (value instanceof List) {
query.addCriteria(Criteria.where(key).in(value)); public static Query createQueryWithSpecifiedField(List<String> specifields) {
}else { Map<String, Object> condition = new HashMap<>();
query.addCriteria(Criteria.where(key).is(value)); return createQueryWithSpecifiedField(condition, specifields);
} }
}
}
private static void buildQuery(String key, Object value, Query query) {
public static Query buildQuery(Map<String, Object> paramMap) { if (key.contains("_id")) {
Query query = new Query(); query.addCriteria(Criteria.where(key).is(new ObjectId(value.toString())));
for (String key : paramMap.keySet()) { } else {
buildQuery(key, paramMap.get(key), query); if (value instanceof Integer || value instanceof Float
} || value instanceof Double || value instanceof Boolean) {
return query; query.addCriteria(Criteria.where(key).is(value));
} } else if (value instanceof List) {
query.addCriteria(Criteria.where(key).in(value));
public static Query buildQueryByKV(String key, Object value) { }else {
Query query = new Query(); query.addCriteria(Criteria.where(key).is(value));
buildQuery(key, value, query); }
return query; }
} }
public static Query buildQueryByOrder(Map<String, Object> paramMap, List<Order> orderList) { public static Query buildQuery(Map<String, Object> paramMap) {
Query query = new Query(); Query query = new Query();
for (String key : paramMap.keySet()) { for (String key : paramMap.keySet()) {
buildQuery(key, paramMap.get(key), query); buildQuery(key, paramMap.get(key), query);
} }
return query;
if (orderList != null && orderList.size() > 0) { }
query.with(Sort.by(orderList));
} public static Query buildQueryByKV(String key, Object value) {
return query; Query query = new Query();
} buildQuery(key, value, query);
return query;
}
public static Map<String, Object> addSearchCriteria(List<String> searchColumns, String keyword, Map<String, Object> condition) {
Pattern pattern = Pattern.compile("^.*" + keyword + ".*$"); public static Query buildQueryByOrder(Map<String, Object> paramMap, List<Order> orderList) {
List<Document> documents = new ArrayList<>(); Query query = new Query();
searchColumns.forEach(column -> { for (String key : paramMap.keySet()) {
Document value = new Document("$regex", pattern); buildQuery(key, paramMap.get(key), query);
value.put("$options", "i"); }
documents.add(new Document(column, value));
}); if (orderList != null && orderList.size() > 0) {
condition.put("$or", documents); query.with(Sort.by(orderList));
return condition; }
} return query;
}
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) { public static Map<String, Object> addSearchCriteria(List<String> searchColumns, String keyword, Map<String, Object> condition) {
for (String key : paramMap.keySet()) { Pattern pattern = Pattern.compile("^.*" + keyword + ".*$");
Object value = paramMap.get(key); List<Document> documents = new ArrayList<>();
if (key.contains(splitMarker)) {/*// 处理关联查询的情况 searchColumns.forEach(column -> {
String[] arr = key.split(this.splitMarker); Document value = new Document("$regex", pattern);
if (arr.length != 2) { value.put("$options", "i");
continue; documents.add(new Document(column, value));
} });
String p1 = arr[0]; condition.put("$or", documents);
String p2 = arr[1]; return condition;
}
Class<T> clazz = ReflectUtils.getSuperClassGenricType(getClass());
public static Query buildQueryByPage(Map<String, Object> paramMap, List<Order> orderList, Integer pageSize, Integer startIndex) {
Field[] fs = this.getAllFields(clazz); Query query = new Query();
// ReflectUtils.getAllFields(clazz); if (paramMap != null && paramMap.size() > 0) {
for (String key : paramMap.keySet()) {
Class<?> clazz1 = null; Object value = paramMap.get(key);
for (Field f : fs) { if (key.contains(splitMarker)) {/*// 处理关联查询的情况
if (f.getName().equals(p1)) { String[] arr = key.split(this.splitMarker);
clazz1 = f.getType(); if (arr.length != 2) {
break; continue;
} }
} String p1 = arr[0];
Query query0 = new Query(); String p2 = arr[1];
this.buildQuery(p2, value, query0);
query.addCriteria(Criteria.where(p1).in(mongoOper.find(query0, clazz1))); Class<T> clazz = ReflectUtils.getSuperClassGenricType(getClass());
*/} else { Field[] fs = this.getAllFields(clazz);
buildQuery(key, value, query); // ReflectUtils.getAllFields(clazz);
}
} Class<?> clazz1 = null;
} for (Field f : fs) {
if (f.getName().equals(p1)) {
if (orderList != null && orderList.size() > 0) { clazz1 = f.getType();
query.with(Sort.by(orderList)); break;
} }
if (pageSize != 0) { }
query.skip(startIndex); Query query0 = new Query();
query.limit(pageSize); this.buildQuery(p2, value, query0);
} query.addCriteria(Criteria.where(p1).in(mongoOper.find(query0, clazz1)));
return query;
} */} 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;
}
}
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