Commit c4f847cf authored by Piotr Gawron's avatar Piotr Gawron
Browse files

CommentSerializer implemented

parent a1e3d12f
......@@ -3,7 +3,13 @@ package lcsb.mapviewer.model.map;
import java.awt.geom.Point2D;
import java.io.Serializable;
import javax.persistence.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import org.hibernate.annotations.Type;
......@@ -46,7 +52,7 @@ public class Comment implements Serializable {
/**
* The model that was commented.
*/
@ManyToOne(fetch = FetchType.LAZY, optional=false)
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private ModelData model;
/**
......@@ -79,7 +85,8 @@ public class Comment implements Serializable {
private Class<?> tableName;
/**
* If feedback is located on the element, what is the identifier of the element.
* If feedback is located on the element, what is the identifier of the
* element.
*/
private Integer tableId;
/**
......
package lcsb.mapviewer.modelutils.serializer.model.map;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyFilter;
import lcsb.mapviewer.common.Configuration;
import lcsb.mapviewer.common.geometry.PointTransformation;
import lcsb.mapviewer.model.map.Comment;
import lcsb.mapviewer.model.map.reaction.Reaction;
import lcsb.mapviewer.model.map.species.Element;
import lcsb.mapviewer.modelutils.serializer.CustomExceptFilter;
public class CommentSerializer extends JsonSerializer<Comment> {
private Logger logger = LogManager.getLogger();
private Function<Integer, Reaction> getReaction;
private Function<Integer, Element> getElement;
private PointTransformation pt = new PointTransformation();
public CommentSerializer(Function<Integer, Reaction> getReaction, Function<Integer, Element> getElement) {
this.getElement = getElement;
this.getReaction = getReaction;
}
@Override
public void serialize(final Comment comment, final JsonGenerator gen,
final SerializerProvider serializers)
throws IOException {
PropertyFilter filter = null;
FilterProvider provider = serializers.getConfig().getFilterProvider();
if (provider != null) {
filter = provider.findPropertyFilter("commentFilter", null);
}
gen.writeStartObject();
for (String string : availableColumns()) {
String column = string.toLowerCase();
Object value = null;
switch (column) {
case "id":
case "idobject":
value = comment.getId();
break;
case "elementid":
value = getId(comment);
break;
case "modelid":
value = comment.getModelData().getId();
break;
case "title":
value = getTitle(comment);
break;
case "pinned":
value = comment.isPinned();
break;
case "content":
value = comment.getContent();
break;
case "removed":
value = comment.isDeleted();
break;
case "coord":
value = getCoordinates(comment);
break;
case "removereason":
value = comment.getRemoveReason();
break;
case "type":
value = getType(comment);
break;
case "icon":
value = "icons/comment.png?v=" + Configuration.getSystemBuildVersion(null);
break;
case "email":
value = comment.getEmail();
break;
case "owner":
if (comment.getUser() != null) {
value = comment.getUser().getLogin();
} else {
value = null;
}
break;
default:
value = "Unknown column";
}
writeField(gen, string, value, filter);
}
gen.writeEndObject();
}
private void writeField(JsonGenerator gen, String field, Object value, PropertyFilter filter) throws IOException {
if (filter == null ||
(filter instanceof CustomExceptFilter && ((CustomExceptFilter) filter).includeField(field))) {
gen.writeObjectField(field, value);
}
}
public static List<String> availableColumns() {
return Arrays.asList("title", "icon", "type", "content", "removed", "coord", "modelId", "elementId", "id", "pinned", "email", "owner", "removeReason");
}
private Object getId(Comment comment) {
if (comment.getTableName() == null) {
return String.format("%.2f", comment.getCoordinates().getX()) + ","
+ String.format("%.2f", comment.getCoordinates().getY());
} else {
return comment.getTableId();
}
}
private Point2D getCoordinates(Comment comment) {
Point2D coordinates = comment.getCoordinates();
if (comment.getCoordinates() != null) {
coordinates = comment.getCoordinates();
}
if (comment.getTableName() != null) {
if (comment.getTableName().getName().contains("Reaction")) {
Reaction reaction = getReaction.apply(comment.getTableId());
if (reaction != null) {
Line2D centerLine = reaction.getLine().getLines().get(reaction.getLine().getLines().size() / 2);
coordinates = pt.getPointOnLine(centerLine.getP1(), centerLine.getP2(), 0.5);
} else {
logger.warn("Invalid reaction dbID: " + comment.getTableId());
}
} else {
Element alias = getElement.apply(comment.getTableId());
if (alias != null) {
coordinates = alias.getCenter();
} else {
logger.warn("Invalid alias dbID: " + comment.getTableId());
}
}
}
return coordinates;
}
private ElementIdentifierType getType(Comment comment) {
if (comment.getTableName() != null) {
if (comment.getTableName().getName().contains("Reaction")) {
return ElementIdentifierType.REACTION;
} else {
return ElementIdentifierType.ALIAS;
}
} else {
return ElementIdentifierType.POINT;
}
}
private String getTitle(Comment comment) {
String title = "";
if (comment.getCoordinates() != null) {
title = "Comment (coord: " + String.format("%.2f", comment.getCoordinates().getX()) + ", "
+ String.format("%.2f", comment.getCoordinates().getY()) + ")";
}
if (comment.getTableName() != null) {
if (comment.getTableName().getName().contains("Reaction")) {
Reaction reaction = getReaction.apply(comment.getTableId());
if (reaction != null) {
title = "Reaction " + reaction.getIdReaction();
} else {
logger.warn("Invalid reaction dbID: " + comment.getTableId());
}
} else {
Element alias = getElement.apply(comment.getTableId());
if (alias != null) {
title = alias.getName();
} else {
logger.warn("Invalid alias dbID: " + comment.getTableId());
}
}
}
return title;
}
}
\ No newline at end of file
......@@ -24,6 +24,8 @@ import org.springframework.web.bind.annotation.RestController;
import lcsb.mapviewer.api.BaseController;
import lcsb.mapviewer.common.Configuration;
import lcsb.mapviewer.common.exception.NotImplementedException;
import lcsb.mapviewer.model.map.Comment;
import lcsb.mapviewer.model.security.PrivilegeType;
import lcsb.mapviewer.model.user.User;
import lcsb.mapviewer.modelutils.serializer.model.map.ElementIdentifierType;
......@@ -52,7 +54,7 @@ public class CommentController extends BaseController {
" or filterObject['owner'] == authentication.name" +
" or filterObject['isPinned']")
@GetMapping(value = "/models/{modelId}/")
public List<Map<String, Object>> getComments(
public List<Comment> getComments(
Authentication authentication,
@PathVariable(value = "projectId") String projectId,
@RequestParam(value = "columns", defaultValue = "") String columns,
......@@ -65,14 +67,16 @@ public class CommentController extends BaseController {
&& authentication.getAuthorities()
.contains(new SimpleGrantedAuthority(PrivilegeType.READ_PROJECT.name() + ":" + projectId));
List<Map<String, Object>> comments = commentController.getCommentList(
List<Comment> comments = commentController.getCommentList(
projectId, columns, "", null, removed, modelId);
if (!isAdmin && !isProjectCurator) {
comments.forEach(comment -> {
comment.remove("author");
comment.remove("email");
comment.remove("removeReason");
});
throw new NotImplementedException();
// comments.forEach(comment -> {
// comment.remove("author");
// comment.remove("email");
// comment.remove("removeReason");
// });
}
return comments;
}
......@@ -96,7 +100,7 @@ public class CommentController extends BaseController {
" or filterObject['owner'] == authentication.name" +
" or filterObject['isPinned']")
@GetMapping(value = "/models/{modelId}/bioEntities/reactions/{reactionId}")
public List<Map<String, Object>> getCommentsByReaction(
public List<Comment> getCommentsByReaction(
@PathVariable(value = "projectId") String projectId,
@RequestParam(value = "columns", defaultValue = "") String columns,
@PathVariable(value = "modelId") String modelId,
......@@ -112,7 +116,7 @@ public class CommentController extends BaseController {
" or filterObject['owner'] == authentication.name" +
" or filterObject['isPinned']")
@GetMapping(value = "/models/{modelId}/bioEntities/elements/{elementId}")
public List<Map<String, Object>> getCommentsByElement(
public List<Comment> getCommentsByElement(
@PathVariable(value = "projectId") String projectId,
@RequestParam(value = "columns", defaultValue = "") String columns,
@PathVariable(value = "elementId") String elementId,
......@@ -128,7 +132,7 @@ public class CommentController extends BaseController {
" or filterObject['owner'] == authentication.name" +
" or filterObject['isPinned']")
@GetMapping(value = "/models/{modelId}/points/{coordinates:.+}")
public List<Map<String, Object>> getCommentsByPoint(
public List<Comment> getCommentsByPoint(
@PathVariable(value = "projectId") String projectId,
@RequestParam(value = "columns", defaultValue = "") String columns,
@PathVariable(value = "coordinates") String coordinates,
......
......@@ -58,48 +58,42 @@ public class CommentRestImpl extends BaseRestImpl {
this.reactionService = reactionService;
}
public List<Map<String, Object>> getCommentList(
public List<Comment> getCommentList(
String projectId, String columns, String elementId,
ElementIdentifierType elementType, Boolean removed, String modelId) throws QueryException {
Project project = getProjectService().getProjectByProjectId(projectId);
if (project == null) {
throw new ObjectNotFoundException("Project with given id doesn't exist");
}
Set<String> columnsSet = createCommentColumnSet(columns);
List<Map<String, Object>> result = new ArrayList<>();
List<Comment> comments = commentService.getCommentsByModel(project, modelId);
for (Comment comment : comments) {
boolean reject = false;
if (elementType != null) {
List<Comment> result = commentService.getCommentsByModel(project, modelId);
if (elementType != null) {
result.removeIf(comment -> {
switch (elementType) {
case POINT: {
reject = comment.getTableName() != null;
break;
return comment.getTableName() != null;
}
case REACTION: {
reject = comment.getTableName() == null || !comment.getTableName().getName().contains("Reaction");
break;
return comment.getTableName() == null || !comment.getTableName().getName().contains("Reaction");
}
case ALIAS: {
reject = comment.getTableName() == null || comment.getTableName().getName().contains("Reaction");
break;
return comment.getTableName() == null || comment.getTableName().getName().contains("Reaction");
}
default:
throw new QueryException("Unknown element type: " + elementType);
logger.error("Unknown element type: " + elementType);
return true;
}
}
if (!"".equals(elementId)) {
});
}
if (!"".equals(elementId)) {
result.removeIf(comment -> {
Object id = getId(comment).toString();
reject |= (!elementId.equals(id));
}
if (removed != null) {
reject |= (comment.isDeleted() != removed);
}
if (!reject) {
result.add(preparedComment(comment, columnsSet));
}
return (!elementId.equals(id));
});
}
if (removed != null) {
result.removeIf(comment -> {
return comment.isDeleted() != removed;
});
}
return result;
......
......@@ -33,11 +33,17 @@ import lcsb.mapviewer.annotation.services.PubmedSearchException;
import lcsb.mapviewer.annotation.services.annotators.AnnotatorException;
import lcsb.mapviewer.api.SpringRestApiConfig;
import lcsb.mapviewer.model.Article;
import lcsb.mapviewer.model.map.Comment;
import lcsb.mapviewer.model.map.MiriamData;
import lcsb.mapviewer.model.map.reaction.Reaction;
import lcsb.mapviewer.model.map.species.Element;
import lcsb.mapviewer.modelutils.serializer.CalendarSerializer;
import lcsb.mapviewer.modelutils.serializer.model.map.CommentSerializer;
import lcsb.mapviewer.modelutils.serializer.model.map.MiriamDataSerializer;
import lcsb.mapviewer.services.interfaces.IElementService;
import lcsb.mapviewer.services.interfaces.IMeshService;
import lcsb.mapviewer.services.interfaces.IMiriamService;
import lcsb.mapviewer.services.interfaces.IReactionService;
@Configuration
@EnableWebMvc
......@@ -51,12 +57,17 @@ public class SpringWebConfig implements WebMvcConfigurer {
private IMiriamService miriamService;
private IMeshService meshService;
private IElementService elementService;
private IReactionService reactionService;
@Autowired
public SpringWebConfig(List<HandlerInterceptor> interceptors, IMiriamService miriamConnector, IMeshService meshService) {
public SpringWebConfig(List<HandlerInterceptor> interceptors, IMiriamService miriamConnector, IMeshService meshService,
IElementService elementService, IReactionService reactionService) {
this.interceptors = interceptors;
this.miriamService = miriamConnector;
this.meshService = meshService;
this.elementService = elementService;
this.reactionService = reactionService;
}
@Override
......@@ -101,6 +112,20 @@ public class SpringWebConfig implements WebMvcConfigurer {
}
}));
module.addSerializer(Comment.class, new CommentSerializer(
new Function<Integer, Reaction>() {
@Override
public Reaction apply(Integer arg0) {
return reactionService.getById(arg0);
}
},
new Function<Integer, Element>() {
@Override
public Element apply(Integer arg0) {
return elementService.getById(arg0);
}
}));
m.getObjectMapper().registerModule(module);
}
}
......
......@@ -169,7 +169,7 @@ public class CommentControllerIntegrationTest extends ControllerIntegrationTest
.description("should the comment be visible to everybody on the map")
.optional()
.type("boolean"),
fieldWithPath("isPinned").ignored(),
fieldWithPath("isPinned").ignored().optional(),
fieldWithPath("removed")
.description("is the comment removed")
.optional()
......
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