Commit 4e638a6c authored by Piotr Gawron's avatar Piotr Gawron
Browse files

MiriamDataSerializer and ProjectSerializer implemented

parent fc65cddf
......@@ -10,10 +10,15 @@ import org.apache.logging.log4j.Logger;
import org.hibernate.AnnotationException;
import org.springframework.stereotype.Service;
import lcsb.mapviewer.annotation.cache.*;
import lcsb.mapviewer.annotation.cache.CachableInterface;
import lcsb.mapviewer.annotation.cache.GeneralCacheInterface;
import lcsb.mapviewer.annotation.cache.SourceNotAvailable;
import lcsb.mapviewer.annotation.cache.WebPageDownloader;
import lcsb.mapviewer.common.exception.InvalidArgumentException;
import lcsb.mapviewer.converter.annotation.XmlAnnotationParser;
import lcsb.mapviewer.model.map.*;
import lcsb.mapviewer.model.map.MiriamData;
import lcsb.mapviewer.model.map.MiriamRelationType;
import lcsb.mapviewer.model.map.MiriamType;
/**
* Class responsible for connection to Miriam DB. It allows to update URI of
......
package lcsb.mapviewer.model;
import java.io.Serializable;
import java.util.*;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.*;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lcsb.mapviewer.common.exception.InvalidArgumentException;
import lcsb.mapviewer.model.cache.UploadedFileEntry;
......@@ -20,11 +40,15 @@ import lcsb.mapviewer.model.map.MiriamData;
import lcsb.mapviewer.model.map.OverviewImage;
import lcsb.mapviewer.model.map.layout.ProjectBackground;
import lcsb.mapviewer.model.map.layout.graphics.Glyph;
import lcsb.mapviewer.model.map.model.*;
import lcsb.mapviewer.model.map.model.Model;
import lcsb.mapviewer.model.map.model.ModelData;
import lcsb.mapviewer.model.map.model.ModelFullIndexed;
import lcsb.mapviewer.model.overlay.DataOverlay;
import lcsb.mapviewer.model.user.User;
import lcsb.mapviewer.modelutils.serializer.model.ProjectSerializer;
@Entity
@JsonSerialize(using = ProjectSerializer.class)
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
......
package lcsb.mapviewer.modelutils.serializer.model;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
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 lcsb.mapviewer.model.Project;
import lcsb.mapviewer.model.map.OverviewImage;
import lcsb.mapviewer.model.map.OverviewImageLink;
import lcsb.mapviewer.model.map.OverviewLink;
public class ProjectSerializer extends JsonSerializer<Project> {
private static transient Logger logger = LogManager.getLogger();
@Override
public void serialize(final Project entry, final JsonGenerator gen,
final SerializerProvider serializers)
throws IOException {
gen.writeStartObject();
gen.writeStringField("version", entry.getVersion());
gen.writeObjectField("disease", entry.getDisease());
gen.writeObjectField("organism", entry.getOrganism());
gen.writeNumberField("idObject", entry.getId());
if (entry.getStatus() != null) {
gen.writeStringField("status", entry.getStatus().toString());
}
gen.writeStringField("directory", entry.getDirectory());
gen.writeNumberField("progress", entry.getProgress());
gen.writeStringField("notifyEmail", entry.getNotifyEmail());
gen.writeBooleanField("logEntries", entry.getLogEntries().size() > 0);
gen.writeStringField("directory", entry.getDirectory());
gen.writeStringField("name", entry.getName());
gen.writeStringField("owner", entry.getOwner().getLogin());
gen.writeStringField("projectId", entry.getProjectId());
gen.writeObjectField("creationDate", entry.getCreationDate());
gen.writeObjectField("mapCanvasType", entry.getMapCanvasType());
gen.writeObjectField("overviewImageViews", entry.getOverviewImages());
Set<OverviewImage> set = new LinkedHashSet<>();
set.addAll(entry.getOverviewImages());
for (OverviewImage image : entry.getOverviewImages()) {
for (OverviewLink ol : image.getLinks()) {
if (ol instanceof OverviewImageLink) {
set.remove(((OverviewImageLink) ol).getLinkedOverviewImage());
}
}
}
if (set.size() > 0) {
gen.writeObjectField("topOverviewImage", set.iterator().next());
} else if (entry.getOverviewImages().size() > 0) {
logger.warn("Cannot determine top level image. Taking first one. " + entry.getOverviewImages().get(0).getFilename());
gen.writeObjectField("topOverviewImage", entry.getOverviewImages().get(0));
} else {
gen.writeObjectField("topOverviewImage", null);
}
gen.writeEndObject();
}
}
\ No newline at end of file
package lcsb.mapviewer.modelutils.serializer.model.map;
import java.io.IOException;
import java.util.function.Function;
import org.apache.commons.lang3.math.NumberUtils;
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.google.common.base.Objects;
import lcsb.mapviewer.model.Article;
import lcsb.mapviewer.model.map.MiriamData;
import lcsb.mapviewer.model.map.MiriamType;
public class MiriamDataSerializer extends JsonSerializer<MiriamData> {
private static transient Logger logger = LogManager.getLogger();
private Function<MiriamData, String> getUrl;
private Function<MiriamData, Article> getArticle;
public MiriamDataSerializer(Function<MiriamData, String> getUrl, Function<MiriamData, Article> getArticle) {
this.getUrl = getUrl;
this.getArticle = getArticle;
}
@Override
public void serialize(final MiriamData annotation, final JsonGenerator gen,
final SerializerProvider serializers)
throws IOException {
gen.writeStartObject();
if (annotation.getDataType() != null && annotation.getDataType().getUris().size() > 0) {
try {
gen.writeStringField("link", getUrl.apply(annotation));
} catch (Exception e) {
logger.error("Problem with miriam: " + annotation, e);
}
}
if (Objects.equal(MiriamType.PUBMED, annotation.getDataType())) {
if (NumberUtils.isDigits(annotation.getResource())) {
try {
gen.writeObjectField("article", getArticle.apply(annotation));
} catch (Exception e) {
logger.error("Problem with accessing info about pubmed", e);
}
} else {
logger.error("Invalid pubmed identifier: " + annotation.getResource());
}
}
gen.writeObjectField("type", annotation.getDataType());
gen.writeStringField("resource", annotation.getResource());
gen.writeNumberField("id", annotation.getId());
if (annotation.getAnnotator() != null) {
gen.writeStringField("annotatorClassName", annotation.getAnnotator().getName());
} else {
gen.writeStringField("annotatorClassName", "");
}
gen.writeEndObject();
}
}
\ No newline at end of file
package lcsb.mapviewer.modelutils.serializer.model.map;
import static org.junit.Assert.assertNotNull;
import java.util.function.Function;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import lcsb.mapviewer.model.Article;
import lcsb.mapviewer.model.map.MiriamData;
import lcsb.mapviewer.model.map.MiriamType;
public class MiriamDataSerializerTest {
ObjectMapper objectMapper;
public MiriamDataSerializerTest() {
objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MiriamData.class, new MiriamDataSerializer(
new Function<MiriamData, String>() {
@Override
public String apply(MiriamData miriamData) {
return null;
}
},
new Function<MiriamData, Article>() {
@Override
public Article apply(MiriamData miriamData) {
return null;
}
}));
objectMapper.registerModule(module);
}
@Test
public void testCreateAnnotationWithWhitespace() throws Exception {
String response = objectMapper.writeValueAsString(new MiriamData(MiriamType.PUBMED, "28255955 "));
assertNotNull(response);
}
@Test
public void testCreateAnnotationWithNonNumericValues() throws Exception {
String response = objectMapper.writeValueAsString(new MiriamData(MiriamType.PUBMED, "28255955PG"));
assertNotNull(response);
}
@Test
public void testCreateAnnotationWithEmptyValue() throws Exception {
String response = objectMapper.writeValueAsString(new MiriamData(MiriamType.PUBMED, ""));
assertNotNull(response);
}
}
package lcsb.mapviewer.api;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.xml.transform.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
......@@ -19,17 +34,26 @@ import lcsb.mapviewer.annotation.data.Target;
import lcsb.mapviewer.annotation.services.MiriamConnector;
import lcsb.mapviewer.annotation.services.PubmedParser;
import lcsb.mapviewer.common.comparator.StringComparator;
import lcsb.mapviewer.common.exception.*;
import lcsb.mapviewer.common.exception.InvalidArgumentException;
import lcsb.mapviewer.common.exception.InvalidStateException;
import lcsb.mapviewer.common.exception.InvalidXmlSchemaException;
import lcsb.mapviewer.converter.Converter;
import lcsb.mapviewer.model.Article;
import lcsb.mapviewer.model.Project;
import lcsb.mapviewer.model.map.*;
import lcsb.mapviewer.model.map.BioEntity;
import lcsb.mapviewer.model.map.MiriamData;
import lcsb.mapviewer.model.map.MiriamType;
import lcsb.mapviewer.model.map.reaction.Reaction;
import lcsb.mapviewer.model.map.species.Element;
import lcsb.mapviewer.modelutils.map.ElementUtils;
import lcsb.mapviewer.persist.dao.map.species.ElementProperty;
import lcsb.mapviewer.services.QueryException;
import lcsb.mapviewer.services.interfaces.*;
import lcsb.mapviewer.services.interfaces.IConfigurationService;
import lcsb.mapviewer.services.interfaces.IElementService;
import lcsb.mapviewer.services.interfaces.IMiriamService;
import lcsb.mapviewer.services.interfaces.IModelService;
import lcsb.mapviewer.services.interfaces.IProjectService;
import lcsb.mapviewer.services.interfaces.IUserService;
@Transactional
public abstract class BaseRestImpl {
......@@ -90,10 +114,6 @@ public abstract class BaseRestImpl {
return result;
};
protected Map<String, Object> createAnnotation(MiriamData annotation) {
return miriamService.serializeMiriamData(annotation);
};
protected Map<String, Object> createAnnotation(Article article) {
Map<String, Object> result = new TreeMap<>();
if (article != null) {
......@@ -106,12 +126,10 @@ public abstract class BaseRestImpl {
return result;
}
protected List<Map<String, Object>> createAnnotations(Collection<?> references) {
protected List<Map<String, Object>> createAnnotations(Collection<Article> references) {
List<Map<String, Object>> result = new ArrayList<>();
for (Object miriamData : references) {
if (miriamData instanceof MiriamData) {
result.add(createAnnotation((MiriamData) miriamData));
} else if (miriamData instanceof Article) {
if (miriamData instanceof Article) {
result.add(createAnnotation((Article) miriamData));
} else {
throw new InvalidArgumentException();
......@@ -187,8 +205,8 @@ public abstract class BaseRestImpl {
protected Map<String, Object> prepareTarget(Target target, Project project) {
Map<String, Object> result = new TreeMap<>();
result.put("name", target.getName());
result.put("references", createAnnotations(target.getReferences()));
result.put("targetParticipants", createAnnotations(target.getGenes()));
result.put("references", target.getReferences());
result.put("targetParticipants", target.getGenes());
List<Map<String, Object>> targetedObjects = new ArrayList<>();
List<BioEntity> bioEntities = new ArrayList<>();
......@@ -196,40 +214,40 @@ public abstract class BaseRestImpl {
List<Map<ElementProperty, List<? extends Object>>> searchPropertyList = new ArrayList<>();
switch (target.getType()) {
case COMPLEX_PROTEIN: {
Map<ElementProperty, List<? extends Object>> properties = new HashMap<>();
if (target.getSource() != null) {
properties.put(ElementProperty.ANNOTATION, Arrays.asList(target.getSource()));
} else {
properties.put(ElementProperty.ANNOTATION, new ArrayList<>());
case COMPLEX_PROTEIN: {
Map<ElementProperty, List<? extends Object>> properties = new HashMap<>();
if (target.getSource() != null) {
properties.put(ElementProperty.ANNOTATION, Arrays.asList(target.getSource()));
} else {
properties.put(ElementProperty.ANNOTATION, new ArrayList<>());
}
searchPropertyList.add(properties);
break;
}
searchPropertyList.add(properties);
break;
}
case SINGLE_PROTEIN: {
Map<ElementProperty, List<? extends Object>> properties = getSearchByAnnotationsProperties(target);
searchPropertyList.add(properties);
case SINGLE_PROTEIN: {
Map<ElementProperty, List<? extends Object>> properties = getSearchByAnnotationsProperties(target);
searchPropertyList.add(properties);
properties = getSearchByProteinRnaGeneNameProperties(target);
searchPropertyList.add(properties);
break;
}
case PROTEIN_FAMILY: {
Map<ElementProperty, List<? extends Object>> properties = getSearchByProteinRnaGeneNameProperties(target);
properties = getSearchByProteinRnaGeneNameProperties(target);
searchPropertyList.add(properties);
break;
}
case PROTEIN_FAMILY: {
Map<ElementProperty, List<? extends Object>> properties = getSearchByProteinRnaGeneNameProperties(target);
searchPropertyList.add(properties);
break;
}
case OTHER: {
Map<ElementProperty, List<? extends Object>> properties = getSearchByAnnotationsProperties(target);
searchPropertyList.add(properties);
searchPropertyList.add(properties);
break;
}
case OTHER: {
Map<ElementProperty, List<? extends Object>> properties = getSearchByAnnotationsProperties(target);
searchPropertyList.add(properties);
properties = getSearchByNameProperties(target);
searchPropertyList.add(properties);
break;
}
default:
throw new InvalidArgumentException("Unknown drug target type: " + target.getType());
properties = getSearchByNameProperties(target);
searchPropertyList.add(properties);
break;
}
default:
throw new InvalidArgumentException("Unknown drug target type: " + target.getType());
}
for (Map<ElementProperty, List<? extends Object>> properties : searchPropertyList) {
......
......@@ -81,7 +81,7 @@ public class ReferenceGenomeController extends BaseController {
private Map<String, Object> genomeToMap(ReferenceGenome genome) {
Map<String, Object> result = new TreeMap<>();
result.put("organism", miriamService.serializeMiriamData(genome.getOrganism()));
result.put("organism", genome.getOrganism());
result.put("version", genome.getVersion());
result.put("type", genome.getType());
result.put("downloadProgress", genome.getDownloadProgress());
......@@ -146,17 +146,13 @@ public class ReferenceGenomeController extends BaseController {
}
@GetMapping(value = "/taxonomies/")
public List<Map<String, Object>> getGenomeTaxonomies() throws QueryException {
public Set<MiriamData> getGenomeTaxonomies() throws QueryException {
try {
Set<MiriamData> organisms = new LinkedHashSet<>();
for (ReferenceGenomeType type : ReferenceGenomeType.values()) {
organisms.addAll(referenceGenomeService.getOrganismsByReferenceGenomeType(type));
}
List<Map<String, Object>> result = new ArrayList<>();
for (MiriamData miriamData : organisms) {
result.add(miriamService.serializeMiriamData(miriamData));
}
return result;
return organisms;
} catch (ReferenceGenomeConnectorException e) {
throw new QueryException("Problem with obtaining organism list", e);
}
......
......@@ -24,6 +24,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import lcsb.mapviewer.api.BaseController;
import lcsb.mapviewer.model.Project;
import lcsb.mapviewer.model.cache.FileEntry;
import lcsb.mapviewer.model.map.layout.ProjectBackground;
import lcsb.mapviewer.model.security.PrivilegeType;
......@@ -49,14 +50,14 @@ public class ProjectController extends BaseController {
@PreAuthorize("hasAnyAuthority('IS_ADMIN', 'READ_PROJECT:' + #projectId)")
@GetMapping(value = "/{projectId:.+}")
public Map<String, Object> getProject(@PathVariable(value = "projectId") String projectId)
public Project getProject(@PathVariable(value = "projectId") String projectId)
throws ObjectNotFoundException {
return projectController.getProject(projectId);
}
@PreAuthorize("hasAnyAuthority('IS_ADMIN', 'WRITE_PROJECT:' + #projectId)")
@PatchMapping(value = "/{projectId:.+}")
public Map<String, Object> updateProject(
public Project updateProject(
@RequestBody String body,
@PathVariable(value = "projectId") String projectId) throws IOException, QueryException {
Map<String, Object> node = parseBody(body);
......@@ -86,7 +87,7 @@ public class ProjectController extends BaseController {
@PreAuthorize("hasAnyAuthority('IS_ADMIN', 'IS_CURATOR')")
@PostMapping(value = "/{projectId:.+}")
public Map<String, Object> addProject(
public Project addProject(
Authentication authentication,
@RequestBody MultiValueMap<String, Object> formData,
@PathVariable(value = "projectId") String projectId) throws IOException, QueryException, SecurityException {
......@@ -94,7 +95,7 @@ public class ProjectController extends BaseController {
throw new QueryException("No.");
}
User user = userService.getUserByLogin(authentication.getName());
Map<String, Object> project = projectController.addProject(projectId, formData, context.getRealPath("/"), user);
Project project = projectController.addProject(projectId, formData, context.getRealPath("/"), user);
userService.grantUserPrivilege(user, PrivilegeType.WRITE_PROJECT, projectId);
userService.grantUserPrivilege(user, PrivilegeType.READ_PROJECT, projectId);
......@@ -107,9 +108,9 @@ public class ProjectController extends BaseController {
@PreAuthorize("hasAuthority('IS_ADMIN')" +
" or hasAuthority('IS_CURATOR') and hasAuthority('WRITE_PROJECT:' + #projectId)")
@DeleteMapping(value = "/{projectId:.+}")
public Map<String, Object> removeProject(@PathVariable(value = "projectId") String projectId)
public Project removeProject(@PathVariable(value = "projectId") String projectId)
throws QueryException {
Map<String, Object> response = projectController.removeProject(projectId, context.getRealPath("/"));
Project response = projectController.removeProject(projectId, context.getRealPath("/"));
userService.revokeObjectDomainPrivilegesForAllUsers(PrivilegeType.WRITE_PROJECT, projectId);
userService.revokeObjectDomainPrivilegesForAllUsers(PrivilegeType.READ_PROJECT, projectId);
......@@ -119,7 +120,7 @@ public class ProjectController extends BaseController {
@PostFilter("hasAnyAuthority('IS_ADMIN', 'READ_PROJECT:' + filterObject['projectId'])")
@GetMapping(value = "/")
public List<Map<String, Object>> getProjects() {
public List<Project> getProjects() {
return projectController.getProjects();
}
......
......@@ -8,8 +8,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
......@@ -42,9 +40,6 @@ import lcsb.mapviewer.model.cache.UploadedFileEntry;
import lcsb.mapviewer.model.graphics.MapCanvasType;
import lcsb.mapviewer.model.map.MiriamData;
import lcsb.mapviewer.model.map.MiriamType;
import lcsb.mapviewer.model.map.OverviewImage;
import lcsb.mapviewer.model.map.OverviewImageLink;
import lcsb.mapviewer.model.map.OverviewLink;
import lcsb.mapviewer.model.map.layout.ProjectBackground;
import lcsb.mapviewer.model.map.model.SubmodelType;
import lcsb.mapviewer.model.map.species.Element;
......@@ -116,9 +111,8 @@ public class ProjectRestImpl extends BaseRestImpl {
this.reactionService = reactionService;
}
public Map<String, Object> getProject(String projectId) throws ObjectNotFoundException {
Project project = getProjectByProjectId(projectId);
return createData(project);
public Project getProject(String projectId) throws ObjectNotFoundException {
return getProjectByProjectId(projectId);
}
private Project getProjectByProjectId(String projectId) throws ObjectNotFoundException {
......@@ -129,57 +123,6 @@ public class ProjectRestImpl extends BaseRestImpl {
return project;
}
private Map<String, Object> createData(Project project