#83: Tag DAO refactoring

This commit is contained in:
jendib 2016-05-05 02:34:33 +02:00
parent ddf9e83a9b
commit 27027ec412
7 changed files with 333 additions and 227 deletions

View File

@ -212,7 +212,7 @@ public class DocumentDao {
sb.append(" (select count(f.FIL_ID_C) from T_FILE f where f.FIL_DELETEDATE_D is null and f.FIL_IDDOC_C = d.DOC_ID_C) c6 ");
sb.append(" from T_DOCUMENT d ");
// Adds search criteria
// Add search criterias
if (criteria.getTargetIdList() != null) {
// Read permission is enough for searching
sb.append(" left join T_ACL a on a.ACL_TARGETID_C in (:targetIdList) and a.ACL_SOURCEID_C = d.DOC_ID_C and a.ACL_PERM_C = 'READ' and a.ACL_DELETEDATE_D is null ");

View File

@ -1,21 +1,24 @@
package com.sismics.docs.core.dao.jpa;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.*;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import com.google.common.base.Joiner;
import com.sismics.docs.core.constant.AuditLogType;
import com.sismics.docs.core.dao.jpa.criteria.GroupCriteria;
import com.sismics.docs.core.dao.jpa.criteria.TagCriteria;
import com.sismics.docs.core.dao.jpa.dto.GroupDto;
import com.sismics.docs.core.dao.jpa.dto.TagDto;
import com.sismics.docs.core.dao.jpa.dto.TagStatDto;
import com.sismics.docs.core.model.jpa.DocumentTag;
import com.sismics.docs.core.model.jpa.Tag;
import com.sismics.docs.core.util.AuditLogUtil;
import com.sismics.docs.core.util.jpa.QueryParam;
import com.sismics.docs.core.util.jpa.QueryUtil;
import com.sismics.docs.core.util.jpa.SortCriteria;
import com.sismics.util.context.ThreadLocalContext;
/**
@ -39,20 +42,6 @@ public class TagDao {
}
}
/**
* Returns the list of all tags.
*
* @return List of tags
*/
@SuppressWarnings("unchecked")
public List<Tag> getByUserId(String userId) {
// TODO Use ACLs
EntityManager em = ThreadLocalContext.get().getEntityManager();
Query q = em.createQuery("select t from Tag t where t.userId = :userId and t.deleteDate is null order by t.name");
q.setParameter("userId", userId);
return q.getResultList();
}
/**
* Update tags on a document.
*
@ -94,42 +83,6 @@ public class TagDao {
}
}
}
/**
* Returns tag list on a document.
*
* @param documentId Document ID
* @return List of tags
*/
@SuppressWarnings("unchecked")
public List<TagDto> getByDocumentId(String documentId, String userId) {
// TODO Use ACLs
EntityManager em = ThreadLocalContext.get().getEntityManager();
StringBuilder sb = new StringBuilder("select t.TAG_ID_C, t.TAG_NAME_C, t.TAG_COLOR_C, t.TAG_IDPARENT_C from T_DOCUMENT_TAG dt ");
sb.append(" join T_TAG t on t.TAG_ID_C = dt.DOT_IDTAG_C ");
sb.append(" where dt.DOT_IDDOCUMENT_C = :documentId and t.TAG_DELETEDATE_D is null ");
sb.append(" and t.TAG_IDUSER_C = :userId and dt.DOT_DELETEDATE_D is null ");
sb.append(" order by t.TAG_NAME_C ");
// Perform the query
Query q = em.createNativeQuery(sb.toString());
q.setParameter("documentId", documentId);
q.setParameter("userId", userId);
List<Object[]> l = q.getResultList();
// Assemble results
List<TagDto> tagDtoList = new ArrayList<>();
for (Object[] o : l) {
int i = 0;
TagDto tagDto = new TagDto();
tagDto.setId((String) o[i++]);
tagDto.setName((String) o[i++]);
tagDto.setColor((String) o[i++]);
tagDto.setParentId((String) o[i]);
tagDtoList.add(tagDto);
}
return tagDtoList;
}
/**
* Returns stats on tags.
@ -189,46 +142,6 @@ public class TagDao {
return tag.getId();
}
/**
* Returns a tag by name.
*
* @param userId User ID
* @param name Name
* @return Tag
*/
public Tag getByName(String userId, String name) {
// TODO Use ACLs
EntityManager em = ThreadLocalContext.get().getEntityManager();
Query q = em.createQuery("select t from Tag t where t.name = :name and t.userId = :userId and t.deleteDate is null");
q.setParameter("userId", userId);
q.setParameter("name", name);
try {
return (Tag) q.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
/**
* Returns a tag by ID.
*
* @param userId User ID
* @param tagId Tag ID
* @return Tag
*/
public Tag getByTagId(String userId, String tagId) {
// TODO Use ACLs
EntityManager em = ThreadLocalContext.get().getEntityManager();
Query q = em.createQuery("select t from Tag t where t.id = :tagId and t.userId = :userId and t.deleteDate is null");
q.setParameter("userId", userId);
q.setParameter("tagId", tagId);
try {
return (Tag) q.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
/**
* Deletes a tag.
@ -262,22 +175,6 @@ public class TagDao {
// Create audit log
AuditLogUtil.create(tagDb, AuditLogType.DELETE, userId);
}
/**
* Search tags by name.
*
* @param name Tag name
* @return List of found tags
*/
@SuppressWarnings("unchecked")
public List<Tag> findByName(String userId, String name) {
// TODO Use ACLs
EntityManager em = ThreadLocalContext.get().getEntityManager();
Query q = em.createQuery("select t from Tag t where t.name like :name and t.userId = :userId and t.deleteDate is null");
q.setParameter("userId", userId);
q.setParameter("name", "%" + name + "%");
return q.getResultList();
}
/**
* Update a tag.
@ -304,5 +201,70 @@ public class TagDao {
return tagFromDb;
}
/**
* Returns the list of all tags.
*
* @param criteria Search criteria
* @param sortCriteria Sort criteria
* @return List of groups
*/
public List<TagDto> findByCriteria(TagCriteria criteria, SortCriteria sortCriteria) {
Map<String, Object> parameterMap = new HashMap<>();
List<String> criteriaList = new ArrayList<>();
StringBuilder sb = new StringBuilder("select t.TAG_ID_C as c0, t.TAG_NAME_C as c1, t.TAG_COLOR_C as c2, t.TAG_IDPARENT_C as c3 ");
sb.append(" from T_TAG t ");
// TODO Use ACLs
// Add search criterias
if (criteria.getId() != null) {
criteriaList.add("t.TAG_ID_C = :id");
parameterMap.put("id", criteria.getId());
}
if (criteria.getUserId() != null) {
criteriaList.add("t.TAG_IDUSER_C = :userId");
parameterMap.put("userId", criteria.getUserId());
}
if (criteria.getDocumentId() != null) {
sb.append(" join T_DOCUMENT_TAG dt on dt.DOT_IDTAG_C = t.TAG_ID_C and dt.DOT_DELETEDATE_D is null ");
criteriaList.add("dt.DOT_IDDOCUMENT_C = :documentId");
parameterMap.put("documentId", criteria.getDocumentId());
}
if (criteria.getName() != null) {
criteriaList.add("t.TAG_NAME_C = :name");
parameterMap.put("name", criteria.getName());
}
if (criteria.getNameLike() != null) {
criteriaList.add("t.TAG_NAME_C like :nameLike");
parameterMap.put("nameLike", "%" + criteria.getNameLike() + "%");
}
criteriaList.add("t.TAG_DELETEDATE_D is null");
if (!criteriaList.isEmpty()) {
sb.append(" where ");
sb.append(Joiner.on(" and ").join(criteriaList));
}
// Perform the search
QueryParam queryParam = QueryUtil.getSortedQueryParam(new QueryParam(sb.toString(), parameterMap), sortCriteria);
@SuppressWarnings("unchecked")
List<Object[]> l = QueryUtil.getNativeQuery(queryParam).getResultList();
// Assemble results
List<TagDto> tagDtoList = new ArrayList<>();
for (Object[] o : l) {
int i = 0;
TagDto tagDto = new TagDto()
.setId((String) o[i++])
.setName((String) o[i++])
.setColor((String) o[i++])
.setParentId((String) o[i]);
tagDtoList.add(tagDto);
}
return tagDtoList;
}
}

View File

@ -0,0 +1,78 @@
package com.sismics.docs.core.dao.jpa.criteria;
/**
* Tag criteria.
*
* @author bgamard
*/
public class TagCriteria {
/**
* Tag ID.
*/
private String id;
/**
* User ID.
*/
private String userId;
/**
* Document ID.
*/
private String documentId;
/**
* Tag name.
*/
private String name;
/**
* Approximate tag name.
*/
private String nameLike;
public String getId() {
return id;
}
public TagCriteria setId(String id) {
this.id = id;
return this;
}
public String getUserId() {
return userId;
}
public TagCriteria setUserId(String userId) {
this.userId = userId;
return this;
}
public String getDocumentId() {
return documentId;
}
public TagCriteria setDocumentId(String documentId) {
this.documentId = documentId;
return this;
}
public String getName() {
return name;
}
public TagCriteria setName(String name) {
this.name = name;
return this;
}
public String getNameLike() {
return nameLike;
}
public TagCriteria setNameLike(String nameLike) {
this.nameLike = nameLike;
return this;
}
}

View File

@ -30,31 +30,35 @@ public class TagDto {
return id;
}
public void setId(String id) {
public TagDto setId(String id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
public TagDto setName(String name) {
this.name = name;
return this;
}
public String getColor() {
return color;
}
public void setColor(String color) {
public TagDto setColor(String color) {
this.color = color;
return this;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
public TagDto setParentId(String parentId) {
this.parentId = parentId;
return this;
}
}

View File

@ -18,18 +18,13 @@ import javax.ws.rs.core.Response;
import com.google.common.collect.Lists;
import com.sismics.docs.core.constant.AclTargetType;
import com.sismics.docs.core.constant.PermType;
import com.sismics.docs.core.dao.jpa.AclDao;
import com.sismics.docs.core.dao.jpa.DocumentDao;
import com.sismics.docs.core.dao.jpa.GroupDao;
import com.sismics.docs.core.dao.jpa.UserDao;
import com.sismics.docs.core.dao.jpa.*;
import com.sismics.docs.core.dao.jpa.criteria.GroupCriteria;
import com.sismics.docs.core.dao.jpa.criteria.UserCriteria;
import com.sismics.docs.core.dao.jpa.dto.GroupDto;
import com.sismics.docs.core.dao.jpa.dto.TagDto;
import com.sismics.docs.core.dao.jpa.dto.UserDto;
import com.sismics.docs.core.model.jpa.Acl;
import com.sismics.docs.core.model.jpa.Document;
import com.sismics.docs.core.model.jpa.Group;
import com.sismics.docs.core.model.jpa.User;
import com.sismics.docs.core.model.jpa.*;
import com.sismics.docs.core.util.jpa.SortCriteria;
import com.sismics.rest.exception.ClientException;
import com.sismics.rest.exception.ForbiddenClientException;
@ -156,7 +151,14 @@ public class AclResource extends BaseResource {
if (document != null && document.getUserId().equals(targetId)) {
throw new ClientException("AclError", "Cannot delete base ACL on a document");
}
// Cannot delete R/W on a source tag if the target is the creator
TagDao tagDao = new TagDao();
Tag tag = tagDao.getById(sourceId);
if (tag != null && tag.getUserId().equals(targetId)) {
throw new ClientException("AclError", "Cannot delete base ACL on a tag");
}
// Delete the ACL
aclDao.delete(sourceId, perm, targetId, principal.getId());

View File

@ -27,6 +27,7 @@ import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.StreamingOutput;
import com.sismics.docs.core.dao.jpa.criteria.TagCriteria;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
@ -83,6 +84,7 @@ public class DocumentResource extends BaseResource {
* Returns a document.
*
* @param documentId Document ID
* @param shareId Share ID
* @return Response
*/
@GET
@ -114,7 +116,7 @@ public class DocumentResource extends BaseResource {
} else {
// Add tags added by the current user on this document
TagDao tagDao = new TagDao();
List<TagDto> tagDtoList = tagDao.getByDocumentId(documentId, principal.getId());
List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setDocumentId(documentId), new SortCriteria(1, true));
JsonArrayBuilder tags = Json.createArrayBuilder();
for (TagDto tagDto : tagDtoList) {
tags.add(Json.createObjectBuilder()
@ -188,6 +190,11 @@ public class DocumentResource extends BaseResource {
* Export a document to PDF.
*
* @param documentId Document ID
* @param shareId Share ID
* @param metadata Export metadata
* @param comments Export comments
* @param fitImageToPage Fit images to page
* @param marginStr Margins
* @return Response
*/
@GET
@ -231,7 +238,11 @@ public class DocumentResource extends BaseResource {
} catch (Exception e) {
throw new IOException(e);
} finally {
outputStream.close();
try {
outputStream.close();
} catch (IOException e) {
// Ignore
}
}
}
};
@ -247,6 +258,9 @@ public class DocumentResource extends BaseResource {
*
* @param limit Page limit
* @param offset Page offset
* @param sortColumn Sort column
* @param asc Sorting
* @param search Search query
* @return Response
*/
@GET
@ -278,7 +292,7 @@ public class DocumentResource extends BaseResource {
for (DocumentDto documentDto : paginatedList.getResultList()) {
// Get tags added by the current user on this document
List<TagDto> tagDtoList = tagDao.getByDocumentId(documentDto.getId(), principal.getId());
List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setDocumentId(documentDto.getId()), new SortCriteria(1, true));
JsonArrayBuilder tags = Json.createArrayBuilder();
for (TagDto tagDto : tagDtoList) {
tags.add(Json.createObjectBuilder()
@ -337,77 +351,87 @@ public class DocumentResource extends BaseResource {
query.add(criteria);
continue;
}
if (params[0].equals("tag")) {
// New tag criteria
List<Tag> tagList = tagDao.findByName(principal.getId(), params[1]);
if (documentCriteria.getTagIdList() == null) {
documentCriteria.setTagIdList(new ArrayList<String>());
}
if (tagList.size() == 0) {
// No tag found, the request must returns nothing
documentCriteria.getTagIdList().add(UUID.randomUUID().toString());
}
for (Tag tag : tagList) {
documentCriteria.getTagIdList().add(tag.getId());
}
} else if (params[0].equals("after") || params[0].equals("before")) {
// New date span criteria
try {
DateTime date = formatter.parseDateTime(params[1]);
if (params[0].equals("before")) documentCriteria.setCreateDateMax(date.toDate());
else documentCriteria.setCreateDateMin(date.toDate());
} catch (IllegalArgumentException e) {
// Invalid date, returns no documents
if (params[0].equals("before")) documentCriteria.setCreateDateMax(new Date(0));
else documentCriteria.setCreateDateMin(new Date(Long.MAX_VALUE / 2));
}
} else if (params[0].equals("at")) {
// New specific date criteria
try {
if (params[1].length() == 10) {
DateTime date = dayFormatter.parseDateTime(params[1]);
documentCriteria.setCreateDateMin(date.toDate());
documentCriteria.setCreateDateMax(date.plusDays(1).minusSeconds(1).toDate());
} else if (params[1].length() == 7) {
DateTime date = monthFormatter.parseDateTime(params[1]);
documentCriteria.setCreateDateMin(date.toDate());
documentCriteria.setCreateDateMax(date.plusMonths(1).minusSeconds(1).toDate());
} else if (params[1].length() == 4) {
DateTime date = yearFormatter.parseDateTime(params[1]);
documentCriteria.setCreateDateMin(date.toDate());
documentCriteria.setCreateDateMax(date.plusYears(1).minusSeconds(1).toDate());
switch (params[0]) {
case "tag":
// New tag criteria
List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setNameLike(params[1]), null);
if (documentCriteria.getTagIdList() == null) {
documentCriteria.setTagIdList(new ArrayList<String>());
}
} catch (IllegalArgumentException e) {
// Invalid date, returns no documents
documentCriteria.setCreateDateMin(new Date(0));
documentCriteria.setCreateDateMax(new Date(0));
}
} else if (params[0].equals("shared")) {
// New shared state criteria
if (params[1].equals("yes")) {
documentCriteria.setShared(true);
}
} else if (params[0].equals("lang")) {
// New language criteria
if (Constants.SUPPORTED_LANGUAGES.contains(params[1])) {
documentCriteria.setLanguage(params[1]);
}
} else if (params[0].equals("by")) {
// New creator criteria
User user = userDao.getActiveByUsername(params[1]);
if (user == null) {
// This user doesn't exists, return nothing
documentCriteria.setCreatorId(UUID.randomUUID().toString());
} else {
// This user exists, search its documents
documentCriteria.setCreatorId(user.getId());
}
} else if (params[0].equals("full")) {
// New full content search criteria
fullQuery.add(params[1]);
} else {
query.add(criteria);
if (tagDtoList.size() == 0) {
// No tag found, the request must returns nothing
documentCriteria.getTagIdList().add(UUID.randomUUID().toString());
}
for (TagDto tagDto : tagDtoList) {
documentCriteria.getTagIdList().add(tagDto.getId());
}
break;
case "after":
case "before":
// New date span criteria
try {
DateTime date = formatter.parseDateTime(params[1]);
if (params[0].equals("before")) documentCriteria.setCreateDateMax(date.toDate());
else documentCriteria.setCreateDateMin(date.toDate());
} catch (IllegalArgumentException e) {
// Invalid date, returns no documents
if (params[0].equals("before")) documentCriteria.setCreateDateMax(new Date(0));
else documentCriteria.setCreateDateMin(new Date(Long.MAX_VALUE / 2));
}
break;
case "at":
// New specific date criteria
try {
if (params[1].length() == 10) {
DateTime date = dayFormatter.parseDateTime(params[1]);
documentCriteria.setCreateDateMin(date.toDate());
documentCriteria.setCreateDateMax(date.plusDays(1).minusSeconds(1).toDate());
} else if (params[1].length() == 7) {
DateTime date = monthFormatter.parseDateTime(params[1]);
documentCriteria.setCreateDateMin(date.toDate());
documentCriteria.setCreateDateMax(date.plusMonths(1).minusSeconds(1).toDate());
} else if (params[1].length() == 4) {
DateTime date = yearFormatter.parseDateTime(params[1]);
documentCriteria.setCreateDateMin(date.toDate());
documentCriteria.setCreateDateMax(date.plusYears(1).minusSeconds(1).toDate());
}
} catch (IllegalArgumentException e) {
// Invalid date, returns no documents
documentCriteria.setCreateDateMin(new Date(0));
documentCriteria.setCreateDateMax(new Date(0));
}
break;
case "shared":
// New shared state criteria
if (params[1].equals("yes")) {
documentCriteria.setShared(true);
}
break;
case "lang":
// New language criteria
if (Constants.SUPPORTED_LANGUAGES.contains(params[1])) {
documentCriteria.setLanguage(params[1]);
}
break;
case "by":
// New creator criteria
User user = userDao.getActiveByUsername(params[1]);
if (user == null) {
// This user doesn't exists, return nothing
documentCriteria.setCreatorId(UUID.randomUUID().toString());
} else {
// This user exists, search its documents
documentCriteria.setCreatorId(user.getId());
}
break;
case "full":
// New full content search criteria
fullQuery.add(params[1]);
break;
default:
query.add(criteria);
break;
}
}
@ -421,7 +445,16 @@ public class DocumentResource extends BaseResource {
*
* @param title Title
* @param description Description
* @param tags Tags
* @param subject Subject
* @param identifier Identifier
* @param publisher Publisher
* @param format Format
* @param source Source
* @param type Type
* @param coverage Coverage
* @param rights Rights
* @param tagList Tags
* @param relationList Relations
* @param language Language
* @param createDateStr Creation date
* @return Response
@ -594,7 +627,7 @@ public class DocumentResource extends BaseResource {
document.setCreateDate(createDate);
}
document = documentDao.update(document, principal.getId());
documentDao.update(document, principal.getId());
// Update tags
updateTagList(id, tagList);
@ -624,9 +657,9 @@ public class DocumentResource extends BaseResource {
TagDao tagDao = new TagDao();
Set<String> tagSet = new HashSet<>();
Set<String> tagIdSet = new HashSet<>();
List<Tag> tagDbList = tagDao.getByUserId(principal.getId());
for (Tag tagDb : tagDbList) {
tagIdSet.add(tagDb.getId());
List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()), null);
for (TagDto tagDto : tagDtoList) {
tagIdSet.add(tagDto.getId());
}
for (String tagId : tagList) {
if (!tagIdSet.contains(tagId)) {

View File

@ -15,6 +15,11 @@ import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import com.sismics.docs.core.constant.PermType;
import com.sismics.docs.core.dao.jpa.AclDao;
import com.sismics.docs.core.dao.jpa.criteria.TagCriteria;
import com.sismics.docs.core.dao.jpa.dto.TagDto;
import com.sismics.docs.core.model.jpa.Acl;
import org.apache.commons.lang.StringUtils;
import com.sismics.docs.core.dao.jpa.TagDao;
@ -33,7 +38,7 @@ import com.sismics.rest.util.ValidationUtil;
@Path("/tag")
public class TagResource extends BaseResource {
/**
* Returns the list of all tags.
* Returns the list of all visible tags.
*
* @return Response
*/
@ -45,14 +50,14 @@ public class TagResource extends BaseResource {
}
TagDao tagDao = new TagDao();
List<Tag> tagList = tagDao.getByUserId(principal.getId());
List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()), null);
JsonArrayBuilder items = Json.createArrayBuilder();
for (Tag tag : tagList) {
for (TagDto tagDto : tagDtoList) {
items.add(Json.createObjectBuilder()
.add("id", tag.getId())
.add("name", tag.getName())
.add("color", tag.getColor())
.add("parent", JsonUtil.nullable(tag.getParentId())));
.add("id", tagDto.getId())
.add("name", tagDto.getName())
.add("color", tagDto.getColor())
.add("parent", JsonUtil.nullable(tagDto.getParentId())));
}
JsonObjectBuilder response = Json.createObjectBuilder()
@ -93,6 +98,8 @@ public class TagResource extends BaseResource {
* Creates a new tag.
*
* @param name Name
* @param color Color
* @param parentId Parent ID
* @return Response
*/
@PUT
@ -115,8 +122,8 @@ public class TagResource extends BaseResource {
// Get the tag
TagDao tagDao = new TagDao();
Tag tag = tagDao.getByName(principal.getId(), name);
if (tag != null) {
List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setName(name), null);
if (tagDtoList.size() > 0) {
throw new ClientException("AlreadyExistingTag", MessageFormat.format("Tag already exists: {0}", name));
}
@ -124,19 +131,35 @@ public class TagResource extends BaseResource {
if (StringUtils.isEmpty(parentId)) {
parentId = null;
} else {
Tag parentTag = tagDao.getByTagId(principal.getId(), parentId);
if (parentTag == null) {
tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setId(parentId), null);
if (tagDtoList.size() == 0) {
throw new ClientException("ParentNotFound", MessageFormat.format("Parent not found: {0}", parentId));
}
parentId = tagDtoList.get(0).getId();
}
// Create the tag
tag = new Tag();
Tag tag = new Tag();
tag.setName(name);
tag.setColor(color);
tag.setUserId(principal.getId());
tag.setParentId(parentId);
String id = tagDao.create(tag, principal.getId());
// Create read ACL
AclDao aclDao = new AclDao();
Acl acl = new Acl();
acl.setPerm(PermType.READ);
acl.setSourceId(id);
acl.setTargetId(principal.getId());
aclDao.create(acl, principal.getId());
// Create write ACL
acl = new Acl();
acl.setPerm(PermType.WRITE);
acl.setSourceId(id);
acl.setTargetId(principal.getId());
aclDao.create(acl, principal.getId());
JsonObjectBuilder response = Json.createObjectBuilder()
.add("id", id);
@ -147,6 +170,8 @@ public class TagResource extends BaseResource {
* Update a tag.
*
* @param name Name
* @param color Color
* @param parentId Parent ID
* @return Response
*/
@POST
@ -171,8 +196,8 @@ public class TagResource extends BaseResource {
// Get the tag
TagDao tagDao = new TagDao();
Tag tag = tagDao.getByTagId(principal.getId(), id);
if (tag == null) {
List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setId(id), null);
if (tagDtoList.size() == 0) {
throw new ClientException("TagNotFound", MessageFormat.format("Tag not found: {0}", id));
}
@ -180,19 +205,21 @@ public class TagResource extends BaseResource {
if (StringUtils.isEmpty(parentId)) {
parentId = null;
} else {
Tag parentTag = tagDao.getByTagId(principal.getId(), parentId);
if (parentTag == null) {
tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setId(parentId), null);
if (tagDtoList.size() == 0) {
throw new ClientException("ParentNotFound", MessageFormat.format("Parent not found: {0}", parentId));
}
parentId = tagDtoList.get(0).getId();
}
// Check for name duplicate
Tag tagDuplicate = tagDao.getByName(principal.getId(), name);
if (tagDuplicate != null && !tagDuplicate.getId().equals(id)) {
tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setName(name), null);
if (tagDtoList.size() > 0 && !tagDtoList.get(0).getId().equals(id)) {
throw new ClientException("AlreadyExistingTag", MessageFormat.format("Tag already exists: {0}", name));
}
// Update the tag
Tag tag = tagDao.getById(id);
if (!StringUtils.isEmpty(name)) {
tag.setName(name);
}
@ -212,26 +239,26 @@ public class TagResource extends BaseResource {
/**
* Delete a tag.
*
* @param tagId Tag ID
* @param id Tag ID
* @return Response
*/
@DELETE
@Path("{id: [a-z0-9\\-]+}")
public Response delete(
@PathParam("id") String tagId) {
@PathParam("id") String id) {
if (!authenticate()) {
throw new ForbiddenClientException();
}
// Get the tag
TagDao tagDao = new TagDao();
Tag tag = tagDao.getByTagId(principal.getId(), tagId);
if (tag == null) {
throw new ClientException("TagNotFound", MessageFormat.format("Tag not found: {0}", tagId));
List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setId(id), null);
if (tagDtoList.size() == 0) {
throw new ClientException("TagNotFound", MessageFormat.format("Tag not found: {0}", id));
}
// Delete the tag
tagDao.delete(tagId, principal.getId());
tagDao.delete(id, principal.getId());
// Always return OK
JsonObjectBuilder response = Json.createObjectBuilder()