#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(" (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 "); sb.append(" from T_DOCUMENT d ");
// Adds search criteria // Add search criterias
if (criteria.getTargetIdList() != null) { if (criteria.getTargetIdList() != null) {
// Read permission is enough for searching // 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 "); 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; package com.sismics.docs.core.dao.jpa;
import java.util.ArrayList; import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.NoResultException; import javax.persistence.NoResultException;
import javax.persistence.Query; import javax.persistence.Query;
import com.google.common.base.Joiner;
import com.sismics.docs.core.constant.AuditLogType; 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.TagDto;
import com.sismics.docs.core.dao.jpa.dto.TagStatDto; import com.sismics.docs.core.dao.jpa.dto.TagStatDto;
import com.sismics.docs.core.model.jpa.DocumentTag; import com.sismics.docs.core.model.jpa.DocumentTag;
import com.sismics.docs.core.model.jpa.Tag; import com.sismics.docs.core.model.jpa.Tag;
import com.sismics.docs.core.util.AuditLogUtil; 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; 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. * Update tags on a document.
* *
@ -95,42 +84,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. * Returns stats on tags.
* *
@ -190,46 +143,6 @@ public class TagDao {
return tag.getId(); 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. * Deletes a tag.
* *
@ -263,22 +176,6 @@ public class TagDao {
AuditLogUtil.create(tagDb, AuditLogType.DELETE, userId); 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. * Update a tag.
* *
@ -304,5 +201,70 @@ public class TagDao {
return tagFromDb; 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; return id;
} }
public void setId(String id) { public TagDto setId(String id) {
this.id = id; this.id = id;
return this;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public TagDto setName(String name) {
this.name = name; this.name = name;
return this;
} }
public String getColor() { public String getColor() {
return color; return color;
} }
public void setColor(String color) { public TagDto setColor(String color) {
this.color = color; this.color = color;
return this;
} }
public String getParentId() { public String getParentId() {
return parentId; return parentId;
} }
public void setParentId(String parentId) { public TagDto setParentId(String parentId) {
this.parentId = 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.google.common.collect.Lists;
import com.sismics.docs.core.constant.AclTargetType; import com.sismics.docs.core.constant.AclTargetType;
import com.sismics.docs.core.constant.PermType; import com.sismics.docs.core.constant.PermType;
import com.sismics.docs.core.dao.jpa.AclDao; import com.sismics.docs.core.dao.jpa.*;
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.criteria.GroupCriteria; 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.criteria.UserCriteria;
import com.sismics.docs.core.dao.jpa.dto.GroupDto; 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.dao.jpa.dto.UserDto;
import com.sismics.docs.core.model.jpa.Acl; import com.sismics.docs.core.model.jpa.*;
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.util.jpa.SortCriteria; import com.sismics.docs.core.util.jpa.SortCriteria;
import com.sismics.rest.exception.ClientException; import com.sismics.rest.exception.ClientException;
import com.sismics.rest.exception.ForbiddenClientException; import com.sismics.rest.exception.ForbiddenClientException;
@ -157,6 +152,13 @@ public class AclResource extends BaseResource {
throw new ClientException("AclError", "Cannot delete base ACL on a document"); 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 // Delete the ACL
aclDao.delete(sourceId, perm, targetId, principal.getId()); 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.Response.Status;
import javax.ws.rs.core.StreamingOutput; import javax.ws.rs.core.StreamingOutput;
import com.sismics.docs.core.dao.jpa.criteria.TagCriteria;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatter;
@ -83,6 +84,7 @@ public class DocumentResource extends BaseResource {
* Returns a document. * Returns a document.
* *
* @param documentId Document ID * @param documentId Document ID
* @param shareId Share ID
* @return Response * @return Response
*/ */
@GET @GET
@ -114,7 +116,7 @@ public class DocumentResource extends BaseResource {
} else { } else {
// Add tags added by the current user on this document // Add tags added by the current user on this document
TagDao tagDao = new TagDao(); 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(); JsonArrayBuilder tags = Json.createArrayBuilder();
for (TagDto tagDto : tagDtoList) { for (TagDto tagDto : tagDtoList) {
tags.add(Json.createObjectBuilder() tags.add(Json.createObjectBuilder()
@ -188,6 +190,11 @@ public class DocumentResource extends BaseResource {
* Export a document to PDF. * Export a document to PDF.
* *
* @param documentId Document ID * @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 * @return Response
*/ */
@GET @GET
@ -231,7 +238,11 @@ public class DocumentResource extends BaseResource {
} catch (Exception e) { } catch (Exception e) {
throw new IOException(e); throw new IOException(e);
} finally { } finally {
try {
outputStream.close(); outputStream.close();
} catch (IOException e) {
// Ignore
}
} }
} }
}; };
@ -247,6 +258,9 @@ public class DocumentResource extends BaseResource {
* *
* @param limit Page limit * @param limit Page limit
* @param offset Page offset * @param offset Page offset
* @param sortColumn Sort column
* @param asc Sorting
* @param search Search query
* @return Response * @return Response
*/ */
@GET @GET
@ -278,7 +292,7 @@ public class DocumentResource extends BaseResource {
for (DocumentDto documentDto : paginatedList.getResultList()) { for (DocumentDto documentDto : paginatedList.getResultList()) {
// Get tags added by the current user on this document // 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(); JsonArrayBuilder tags = Json.createArrayBuilder();
for (TagDto tagDto : tagDtoList) { for (TagDto tagDto : tagDtoList) {
tags.add(Json.createObjectBuilder() tags.add(Json.createObjectBuilder()
@ -338,20 +352,23 @@ public class DocumentResource extends BaseResource {
continue; continue;
} }
if (params[0].equals("tag")) { switch (params[0]) {
case "tag":
// New tag criteria // New tag criteria
List<Tag> tagList = tagDao.findByName(principal.getId(), params[1]); List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()).setNameLike(params[1]), null);
if (documentCriteria.getTagIdList() == null) { if (documentCriteria.getTagIdList() == null) {
documentCriteria.setTagIdList(new ArrayList<String>()); documentCriteria.setTagIdList(new ArrayList<String>());
} }
if (tagList.size() == 0) { if (tagDtoList.size() == 0) {
// No tag found, the request must returns nothing // No tag found, the request must returns nothing
documentCriteria.getTagIdList().add(UUID.randomUUID().toString()); documentCriteria.getTagIdList().add(UUID.randomUUID().toString());
} }
for (Tag tag : tagList) { for (TagDto tagDto : tagDtoList) {
documentCriteria.getTagIdList().add(tag.getId()); documentCriteria.getTagIdList().add(tagDto.getId());
} }
} else if (params[0].equals("after") || params[0].equals("before")) { break;
case "after":
case "before":
// New date span criteria // New date span criteria
try { try {
DateTime date = formatter.parseDateTime(params[1]); DateTime date = formatter.parseDateTime(params[1]);
@ -362,7 +379,8 @@ public class DocumentResource extends BaseResource {
if (params[0].equals("before")) documentCriteria.setCreateDateMax(new Date(0)); if (params[0].equals("before")) documentCriteria.setCreateDateMax(new Date(0));
else documentCriteria.setCreateDateMin(new Date(Long.MAX_VALUE / 2)); else documentCriteria.setCreateDateMin(new Date(Long.MAX_VALUE / 2));
} }
} else if (params[0].equals("at")) { break;
case "at":
// New specific date criteria // New specific date criteria
try { try {
if (params[1].length() == 10) { if (params[1].length() == 10) {
@ -383,17 +401,20 @@ public class DocumentResource extends BaseResource {
documentCriteria.setCreateDateMin(new Date(0)); documentCriteria.setCreateDateMin(new Date(0));
documentCriteria.setCreateDateMax(new Date(0)); documentCriteria.setCreateDateMax(new Date(0));
} }
} else if (params[0].equals("shared")) { break;
case "shared":
// New shared state criteria // New shared state criteria
if (params[1].equals("yes")) { if (params[1].equals("yes")) {
documentCriteria.setShared(true); documentCriteria.setShared(true);
} }
} else if (params[0].equals("lang")) { break;
case "lang":
// New language criteria // New language criteria
if (Constants.SUPPORTED_LANGUAGES.contains(params[1])) { if (Constants.SUPPORTED_LANGUAGES.contains(params[1])) {
documentCriteria.setLanguage(params[1]); documentCriteria.setLanguage(params[1]);
} }
} else if (params[0].equals("by")) { break;
case "by":
// New creator criteria // New creator criteria
User user = userDao.getActiveByUsername(params[1]); User user = userDao.getActiveByUsername(params[1]);
if (user == null) { if (user == null) {
@ -403,11 +424,14 @@ public class DocumentResource extends BaseResource {
// This user exists, search its documents // This user exists, search its documents
documentCriteria.setCreatorId(user.getId()); documentCriteria.setCreatorId(user.getId());
} }
} else if (params[0].equals("full")) { break;
case "full":
// New full content search criteria // New full content search criteria
fullQuery.add(params[1]); fullQuery.add(params[1]);
} else { break;
default:
query.add(criteria); query.add(criteria);
break;
} }
} }
@ -421,7 +445,16 @@ public class DocumentResource extends BaseResource {
* *
* @param title Title * @param title Title
* @param description Description * @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 language Language
* @param createDateStr Creation date * @param createDateStr Creation date
* @return Response * @return Response
@ -594,7 +627,7 @@ public class DocumentResource extends BaseResource {
document.setCreateDate(createDate); document.setCreateDate(createDate);
} }
document = documentDao.update(document, principal.getId()); documentDao.update(document, principal.getId());
// Update tags // Update tags
updateTagList(id, tagList); updateTagList(id, tagList);
@ -624,9 +657,9 @@ public class DocumentResource extends BaseResource {
TagDao tagDao = new TagDao(); TagDao tagDao = new TagDao();
Set<String> tagSet = new HashSet<>(); Set<String> tagSet = new HashSet<>();
Set<String> tagIdSet = new HashSet<>(); Set<String> tagIdSet = new HashSet<>();
List<Tag> tagDbList = tagDao.getByUserId(principal.getId()); List<TagDto> tagDtoList = tagDao.findByCriteria(new TagCriteria().setUserId(principal.getId()), null);
for (Tag tagDb : tagDbList) { for (TagDto tagDto : tagDtoList) {
tagIdSet.add(tagDb.getId()); tagIdSet.add(tagDto.getId());
} }
for (String tagId : tagList) { for (String tagId : tagList) {
if (!tagIdSet.contains(tagId)) { if (!tagIdSet.contains(tagId)) {

View File

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