Optimize mindmap list query.

This commit is contained in:
Paulo Gustavo Veiga 2022-01-18 13:16:39 -08:00
parent f844692e66
commit 6307af005c
19 changed files with 252 additions and 288 deletions

View File

@ -69,4 +69,6 @@ public interface MindmapManager {
void updateCollaboration(@NotNull Collaboration collaboration);
void purgeHistory(int mapId) throws IOException;
List<Mindmap> findMindmapByUser(User user);
}

View File

@ -21,7 +21,6 @@ package com.wisemapping.dao;
import com.wisemapping.model.*;
import com.wisemapping.util.ZipUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Junction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
@ -31,6 +30,7 @@ import org.jetbrains.annotations.Nullable;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import javax.persistence.Query;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
@ -45,7 +45,7 @@ public class MindmapManagerImpl
Query query = currentSession().createQuery("from com.wisemapping.model.Collaborator collaborator where email=:email");
query.setParameter("email", email);
final List<Collaborator> collaborators = query.list();
final List<Collaborator> collaborators = query.getResultList();
if (collaborators != null && !collaborators.isEmpty()) {
assert collaborators.size() == 1 : "More than one user with the same email!";
collaborator = collaborators.get(0);
@ -114,6 +114,16 @@ public class MindmapManagerImpl
}
}
@Override
public List<Mindmap> findMindmapByUser(@NotNull User user) {
final Mindmap collaborator;
final Query query = currentSession()
.createQuery("from com.wisemapping.model.Mindmap m where m.id in (select c.mindMap.id from com.wisemapping.model.Collaboration as c where c.collaborator.id=:collabId )");
query.setParameter("collabId", user.getId());
return query.getResultList();
}
@Override
public List<Mindmap> search(MindMapCriteria criteria, int maxResult) {
final Criteria hibernateCriteria = currentSession().createCriteria(Mindmap.class);
@ -156,27 +166,27 @@ public class MindmapManagerImpl
@Override
public List<Collaboration> findCollaboration(final int collaboratorId) {
Query query = currentSession().createQuery("from com.wisemapping.model.Collaboration collaboration where colaborator_id=:colaboratorId");
query.setParameter("colaboratorId", collaboratorId);
return query.list();
Query query = currentSession().createQuery("from com.wisemapping.model.Collaboration c where c.collaborator.id=:collaboratorId");
query.setParameter("collaboratorId", collaboratorId);
return query.getResultList();
}
@Override
public List<Collaboration> findCollaboration(final CollaborationRole collaborationRole) {
Query query = currentSession().createQuery("from com.wisemapping.model.Collaboration collaboration where roleId=:roleId");
Query query = currentSession().createQuery("from com.wisemapping.model.Collaboration c where c.role=:roleId");
query.setParameter("roleId", collaborationRole.ordinal());
return query.list();
return query.getResultList();
}
@Override
public Collaboration findCollaboration(final int mindmapId, final User user) {
final Collaboration result;
Query query = currentSession().createQuery("from com.wisemapping.model.Collaboration collaboration where mindMap.id=:mindMapId and colaborator_id=:collaboratorId");
query.setParameter("mindMap", mindmapId);
Query query = currentSession().createQuery("from com.wisemapping.model.Collaboration c where c.mindMap.id=:mindmapId and c.id=:collaboratorId");
query.setParameter("mindmapId", mindmapId);
query.setParameter("collaboratorId", user.getId());
final List<Collaboration> mindMaps = query.list();
final List<Collaboration> mindMaps = query.getResultList();
if (mindMaps != null && !mindMaps.isEmpty()) {
result = mindMaps.get(0);
@ -222,7 +232,7 @@ public class MindmapManagerImpl
query.setParameter("title", title);
query.setParameter("creator", user);
List<Mindmap> mindMaps = query.list();
List<Mindmap> mindMaps = query.getResultList();
if (mindMaps != null && !mindMaps.isEmpty()) {
result = mindMaps.get(0);

View File

@ -1,6 +1,7 @@
package com.wisemapping.model;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ -9,6 +10,8 @@ import java.io.Serializable;
@Entity
@Table(name = "LABEL")
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Label implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ -16,7 +19,7 @@ public class Label implements Serializable {
@NotNull private String title;
@NotNull private String color;
@NotNull private String iconName;
@Nullable private String iconName;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="creator_id",nullable = true,unique = true)
@ -70,7 +73,7 @@ public class Label implements Serializable {
this.color = color;
}
@NotNull
@Nullable
public String getIconName() {
return iconName;
}
@ -94,7 +97,7 @@ public class Label implements Serializable {
public int hashCode() {
long result = id;
result = 31 * result + title.hashCode();
result = 31 * result + creator.hashCode();
result = 31 * result + (creator!=null?creator.hashCode():0);
result = 31 * result + (parent != null ? parent.hashCode() : 0);
return (int) result;
}

View File

@ -47,11 +47,11 @@ public class Mindmap implements Serializable {
private Calendar lastModificationTime;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "creator_id", unique = true, nullable = true)
@JoinColumn(name = "creator_id", unique = true)
private User creator;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "last_editor_id", unique = false, nullable = false)
@JoinColumn(name = "last_editor_id", nullable = false)
private User lastEditor;
private String description;
@ -62,14 +62,13 @@ public class Mindmap implements Serializable {
@OneToMany(mappedBy="mindMap",orphanRemoval = true, cascade = {CascadeType.ALL},fetch = FetchType.LAZY)
private Set<Collaboration> collaborations = new HashSet<>();
@ManyToMany
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "R_LABEL_MINDMAP",
joinColumns = @JoinColumn(name = "mindmap_id"),
inverseJoinColumns = @JoinColumn(name = "label_id"))
private Set<Label> labels = new LinkedHashSet<>();
private String tags;
private String title;
@Column(name = "xml")
@ -153,16 +152,11 @@ public class Mindmap implements Serializable {
this.labels.add(label);
}
@Nullable
public Collaboration findCollaboration(@NotNull Collaborator collaborator) {
Collaboration result = null;
for (Collaboration collaboration : collaborations) {
if (collaboration.getCollaborator().identityEquality(collaborator)) {
result = collaboration;
break;
}
}
return result;
public Optional<Collaboration> findCollaboration(@NotNull Collaborator collaborator) {
return this.collaborations
.stream()
.filter(c->c.getCollaborator().identityEquality(collaborator))
.findAny();
}
@Nullable
@ -228,30 +222,20 @@ public class Mindmap implements Serializable {
public String getXmlAsJsLiteral()
throws IOException {
String xml = this.getXmlStr();
if (xml != null) {
xml = xml.replace("'", "\\'");
xml = xml.replace("\n", "\\n");
xml = xml.replace("\r", "");
xml = xml.replace("\\b", "\\\\b");
xml = xml.replace("\\t", "\\\\t");
xml = xml.replace("\\r", "\\\\r");
xml = xml.replace("\\f", "\\\\f");
xml = xml.replace("'", "\\'");
xml = xml.replace("\n", "\\n");
xml = xml.replace("\r", "");
xml = xml.trim();
}
xml = xml.replace("\\b", "\\\\b");
xml = xml.replace("\\t", "\\\\t");
xml = xml.replace("\\r", "\\\\r");
xml = xml.replace("\\f", "\\\\f");
xml = xml.trim();
return xml;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getTags() {
return tags;
}
public String getDescription() {
return description;
}
@ -276,9 +260,10 @@ public class Mindmap implements Serializable {
return creator;
}
@Nullable
private CollaborationProperties findUserProperty(@NotNull Collaborator collaborator) {
final Collaboration collaboration = this.findCollaboration(collaborator);
return collaboration != null ? collaboration.getCollaborationProperties() : null;
final Optional<Collaboration> collaboration = this.findCollaboration(collaborator);
return collaboration.map(Collaboration::getCollaborationProperties).orElse(null);
}
public void setStarred(@NotNull Collaborator collaborator, boolean value) throws WiseMappingException {
@ -297,10 +282,10 @@ public class Mindmap implements Serializable {
throw new IllegalStateException("Collaborator can not be null");
}
final Collaboration collaboration = this.findCollaboration(collaborator);
final Optional<Collaboration> collaboration = this.findCollaboration(collaborator);
CollaborationProperties result = null;
if (collaboration != null) {
result = collaboration.getCollaborationProperties();
if (collaboration.isPresent()) {
result = collaboration.get().getCollaborationProperties();
} else {
if (forceCheck)
throw new AccessDeniedSecurityException("Collaborator " + collaborator.getEmail() + " could not access " + this.getId());
@ -328,7 +313,6 @@ public class Mindmap implements Serializable {
result.setDescription(this.getDescription());
result.setTitle(this.getTitle());
result.setUnzipXml(this.getUnzipXml());
result.setTags(this.getTags());
return result;
}
@ -336,9 +320,9 @@ public class Mindmap implements Serializable {
public boolean hasPermissions(@Nullable Collaborator collaborator, @NotNull CollaborationRole role) {
boolean result = false;
if (collaborator != null) {
final Collaboration collaboration = this.findCollaboration(collaborator);
if (collaboration != null) {
result = collaboration.hasPermissions(role);
final Optional<Collaboration> collaboration = this.findCollaboration(collaborator);
if (collaboration.isPresent()) {
result = collaboration.get().hasPermissions(role);
}
}
return result;

View File

@ -59,7 +59,7 @@ public class LabelController extends BaseController {
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void deleteLabelById(@PathVariable int id) throws WiseMappingException {
final User user = Utils.getUser();
final Label label = labelService.getLabelById(id, user);
final Label label = labelService.findLabelById(id, user);
if (label == null) {
throw new LabelCouldNotFoundException("Label could not be found. Id: " + id);
}

View File

@ -71,16 +71,12 @@ public class MindmapController extends BaseController {
final User user = Utils.getUser();
final MindmapFilter filter = MindmapFilter.parse(q);
final List<Collaboration> collaborations = mindmapService.findCollaborations(user);
logger.debug("Collaborators list: " + collaborations.size());
List<Mindmap> mindmaps = mindmapService.findMindmapsByUser(user);
mindmaps = mindmaps
.stream()
.filter(m->filter.accept(m, user))
.collect(Collectors.toUnmodifiableList());
final List<Mindmap> mindmaps = new ArrayList<>();
for (Collaboration collaboration : collaborations) {
final Mindmap mindmap = collaboration.getMindMap();
if (filter.accept(mindmap, user)) {
mindmaps.add(mindmap);
}
}
return new RestMindmapList(mindmaps, user);
}
@ -175,7 +171,7 @@ public class MindmapController extends BaseController {
}
mindmap.setXmlStr(xmlDoc);
saveMindmapDocument(false,mindmap,user);
saveMindmapDocument(false, mindmap, user);
}
@ -247,11 +243,6 @@ public class MindmapController extends BaseController {
mindmap.setDescription(description);
}
final String tags = restMindmap.getTags();
if (tags != null) {
mindmap.setTags(tags);
}
// Update document properties ...
final String properties = restMindmap.getProperties();
if (properties != null) {
@ -350,16 +341,16 @@ public class MindmapController extends BaseController {
restCollabs
.getCollaborations()
.forEach(collab->{
.forEach(collab -> {
final String email = collab.getEmail();
if(mapsByEmail.containsKey(email)){
if (mapsByEmail.containsKey(email)) {
try {
mindmapService.removeCollaboration(mindMap, mapsByEmail.get(email));
} catch (CollaborationException e) {
logger.error(e);
logger.error(e);
}
}
});
});
// Great, let's add all the collabs again ...
@ -450,7 +441,7 @@ public class MindmapController extends BaseController {
}
final Collaboration collab = mindmap.findCollaboration(email);
if(collab!=null) {
if (collab != null) {
CollaborationRole role = collab.getRole();
// Owner collab can not be removed ...
@ -471,12 +462,12 @@ public class MindmapController extends BaseController {
// Update map status ...
final boolean starred = Boolean.parseBoolean(value);
final Collaboration collaboration = mindmap.findCollaboration(user);
if (collaboration == null) {
final Optional<Collaboration> collaboration = mindmap.findCollaboration(user);
if (!collaboration.isPresent()) {
throw new WiseMappingException("No enough permissions.");
}
collaboration.getCollaborationProperties().setStarred(starred);
mindmapService.updateCollaboration(user, collaboration);
collaboration.get().getCollaborationProperties().setStarred(starred);
mindmapService.updateCollaboration(user, collaboration.get());
}
@RequestMapping(method = RequestMethod.PUT, value = "/maps/{id}/lock", consumes = {"text/plain"}, produces = {"application/json", "application/xml"})
@ -509,7 +500,7 @@ public class MindmapController extends BaseController {
@ResponseStatus(value = HttpStatus.CREATED)
public void createMap(@RequestBody(required = false) RestMindmap restMindmap, @NotNull HttpServletResponse response, @RequestParam(required = false) String title, @RequestParam(required = false) String description) throws IOException, WiseMappingException {
// If a default maps has not been defined, just create one ...
if(restMindmap==null){
if (restMindmap == null) {
restMindmap = new RestMindmap();
}
@ -519,7 +510,7 @@ public class MindmapController extends BaseController {
}
if (description != null && !description.isEmpty()) {
restMindmap.setDescription(description);
}else {
} else {
restMindmap.setDescription("");
}
@ -547,7 +538,7 @@ public class MindmapController extends BaseController {
response.setHeader("ResourceId", Integer.toString(delegated.getId()));
}
@RequestMapping(method = RequestMethod.POST, value = "/maps/{id}", consumes = {"application/xml", "application/json"},produces = {"application/xml", "application/json","text/plain"})
@RequestMapping(method = RequestMethod.POST, value = "/maps/{id}", consumes = {"application/xml", "application/json"}, produces = {"application/xml", "application/json", "text/plain"})
@ResponseStatus(value = HttpStatus.CREATED)
public void createDuplicate(@RequestBody RestMindmapInfo restMindmap, @PathVariable int id, @NotNull HttpServletResponse response) throws IOException, WiseMappingException {
// Validate ...
@ -586,38 +577,33 @@ public class MindmapController extends BaseController {
result.rejectValue(fieldName, "error.not-specified", null, message);
return new ValidationException(result);
}
@RequestMapping(method = RequestMethod.DELETE, value = "/labels/maps/{id}")
@RequestMapping(method = RequestMethod.DELETE, value = "/maps/{id}/labels/{lid)}")
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void removeLabel(@RequestBody RestLabel restLabel, @PathVariable int id) throws WiseMappingException {
final Mindmap mindmap = findMindmapById(id);
final User currentUser = Utils.getUser();
final Label delegated = restLabel.getDelegated();
assert currentUser != null;
delegated.setCreator(currentUser);
mindmapService.removeLabel(mindmap, delegated);
}
@RequestMapping(method = RequestMethod.POST, value = "/labels/maps", consumes = { "application/xml","application/json"})
@ResponseStatus(value = HttpStatus.OK)
public void addLabel(@RequestBody RestLabel restLabel, @RequestParam(required = true) String ids) throws WiseMappingException {
int labelId = restLabel.getId();
public void removeLabelFromMap(@PathVariable int id, @RequestBody int lid) throws WiseMappingException {
final User user = Utils.getUser();
final Label delegated = restLabel.getDelegated();
delegated.setCreator(user);
final Mindmap mindmap = findMindmapById(id);
final Label label = labelService.findLabelById(lid, user);
final Label found = labelService.getLabelById(labelId, user);
if (found == null) {
throw new LabelCouldNotFoundException("Label could not be found. Id: " + labelId);
}
for (String id : ids.split(",")) {
final int mindmapId = Integer.parseInt(id);
final Mindmap mindmap = findMindmapById(mindmapId);
final Label label = mindmap.findLabel(labelId);
if (label == null) {
mindmapService.linkLabel(mindmap, delegated);
}
if (label == null) {
throw new LabelCouldNotFoundException("Label could not be found. Id: " + lid);
}
mindmap.removeLabel(label);
mindmapService.updateMindmap(mindmap,false);
}
@RequestMapping(method = RequestMethod.POST, value = "/maps/{id}/labels", consumes = {"application/xml", "application/json"})
@ResponseStatus(value = HttpStatus.OK)
public void updateLabel(@PathVariable int id, @RequestBody int lid) throws WiseMappingException {
final User user = Utils.getUser();
final Label label = labelService.findLabelById(lid, user);
if (label == null) {
throw new LabelCouldNotFoundException("Label could not be found. Id: " + lid);
}
final Mindmap mindmap = findMindmapById(id);
mindmap.addLabel(label);
mindmapService.updateMindmap(mindmap,false);
}
}

View File

@ -24,6 +24,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.wisemapping.exceptions.WiseMappingException;
import com.wisemapping.model.*;
import com.wisemapping.security.Utils;
import com.wisemapping.util.TimeUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@ -33,6 +34,10 @@ import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import java.util.Calendar;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@XmlRootElement(name = "map")
@XmlAccessorType(XmlAccessType.PROPERTY)
@ -87,14 +92,6 @@ public class RestMindmap {
mindmap.setDescription(description);
}
public String getTags() {
return mindmap.getTags();
}
public void setTags(String tags) {
mindmap.setTags(tags);
}
public String getTitle() {
return mindmap.getTitle();
}

View File

@ -1,20 +1,20 @@
/*
* Copyright [2015] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
* Copyright [2015] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wisemapping.rest.model;
@ -32,8 +32,10 @@ import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Calendar;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@XmlRootElement(name = "mapinfo")
@XmlAccessorType(XmlAccessType.PROPERTY)
@ -46,8 +48,15 @@ import java.util.Set;
@JsonIgnoreProperties(ignoreUnknown = true)
public class RestMindmapInfo {
public static final String ROLE_NONE = "none";
@JsonIgnore
private final Mindmap mindmap;
@JsonIgnore
private Set<RestLabel> restLabels;
@JsonIgnore
private int mapId = -1;
private final Collaborator collaborator;
public RestMindmapInfo() {
@ -60,7 +69,7 @@ public class RestMindmapInfo {
this.collaborator = collaborator;
}
public void setCreationTime(String value){
public void setCreationTime(String value) {
// Ignore
}
@ -77,14 +86,6 @@ public class RestMindmapInfo {
mindmap.setDescription(description);
}
public String getTags() {
return mindmap.getTags();
}
public void setTags(String tags) {
mindmap.setTags(tags);
}
public String getTitle() {
return mindmap.getTitle();
}
@ -92,27 +93,40 @@ public class RestMindmapInfo {
public void setTitle(String title) {
mindmap.setTitle(title);
}
public Set<RestLabel> getLabels() {
final Set<RestLabel> result = new LinkedHashSet<>();
final User me = Utils.getUser();
for (Label label : mindmap.getLabels()) {
if (label.getCreator().equals(me)) {
result.add(new RestLabel(label));
}
}
return result;
}
public Set<RestLabel> getLabels() {
// Support test deserialization...
Set<RestLabel> result = this.restLabels;
if(result==null) {
final User me = Utils.getUser();
result = mindmap.getLabels().
stream()
.filter(l -> l.getCreator().equals(me))
.map(RestLabel::new)
.collect(Collectors.toSet());
}
return result;
}
public void setLabels(Set<RestLabel> restLabels) {
this.restLabels = restLabels;
}
public int getId() {
return mindmap.getId();
int result = this.mapId;
if(mapId==-1) {
result = mindmap.getId();
}
return result;
}
public void setId(int id) {
this.mapId = id;
}
public String getCreator() {
final User creator = mindmap.getCreator();
return creator!=null?creator.getFullName():null;
return creator != null ? creator.getFullName() : null;
}
public void setCreator(String email) {
@ -124,8 +138,8 @@ public class RestMindmapInfo {
}
public String getRole() {
final Collaboration collaboration = mindmap.findCollaboration(Utils.getUser());
return collaboration != null ? collaboration.getRole().getLabel() : "none";
final Optional<Collaboration> collaboration = mindmap.findCollaboration(Utils.getUser());
return collaboration.map(value -> value.getRole().getLabel()).orElse(ROLE_NONE);
}
public void setRole(String value) {
@ -142,7 +156,7 @@ public class RestMindmapInfo {
public String getLastModificationTime() {
final Calendar calendar = mindmap.getLastModificationTime();
return calendar!=null?TimeUtils.toISO8601(calendar.getTime()):null;
return calendar != null ? TimeUtils.toISO8601(calendar.getTime()) : null;
}
public void setLastModificationTime(String value) {

View File

@ -31,6 +31,7 @@ import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@XmlRootElement(name = "maps")
@XmlAccessorType(XmlAccessType.PROPERTY)
@ -47,10 +48,9 @@ public class RestMindmapList {
}
public RestMindmapList(@NotNull List<Mindmap> mindmaps, @NotNull Collaborator collaborator) {
this.mindmapsInfo = new ArrayList<>(mindmaps.size());
for (Mindmap mindMap : mindmaps) {
this.mindmapsInfo.add(new RestMindmapInfo(mindMap, collaborator));
}
this.mindmapsInfo = mindmaps.stream()
.map(m->new RestMindmapInfo(m, collaborator))
.collect(Collectors.toList());
}
public int getCount() {

View File

@ -15,7 +15,7 @@ public interface LabelService {
@NotNull List<Label> getAll(@NotNull final User user);
@Nullable
Label getLabelById(int id, @NotNull final User user);
Label findLabelById(int id, @NotNull final User user);
Label getLabelByTitle(@NotNull String title, @NotNull final User user);

View File

@ -31,7 +31,7 @@ public class LabelServiceImpl implements LabelService {
}
@Override @Nullable
public Label getLabelById(int id, @NotNull final User user) {
public Label findLabelById(int id, @NotNull final User user) {
return labelManager.getLabelById(id, user);
}

View File

@ -20,9 +20,9 @@ package com.wisemapping.service;
import com.wisemapping.exceptions.WiseMappingException;
import com.wisemapping.model.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;
@ -31,6 +31,9 @@ public interface MindmapService {
@Nullable
Mindmap findMindmapById(int id);
@NotNull
List<Mindmap> findMindmapsByUser(@NotNull User user);
Mindmap getMindmapByTitle(@NotNull String title, User user);
List<Collaboration> findCollaborations(@NotNull User user);
@ -65,8 +68,4 @@ public interface MindmapService {
boolean isAdmin(@Nullable User user);
void purgeHistory(int mapId) throws IOException;
void linkLabel(@NotNull final Mindmap mindmap, @NotNull final Label label);
void removeLabel(@NotNull final Mindmap mindmap, @NotNull final Label label);
}

View File

@ -32,6 +32,7 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.List;
import java.util.Optional;
import java.util.Set;
@ -68,9 +69,11 @@ public class MindmapServiceImpl
if ((map.isPublic() && role == CollaborationRole.VIEWER) || isAdmin(user)) {
result = true;
} else if (user != null) {
final Collaboration collaboration = map.findCollaboration(user);
if (collaboration != null) {
result = collaboration.hasPermissions(role);
final Optional<Collaboration> collaboration = map.findCollaboration(user);
if (collaboration .isPresent()) {
result = collaboration
.get()
.hasPermissions(role);
}
}
@ -87,16 +90,6 @@ public class MindmapServiceImpl
mindmapManager.purgeHistory(mapId);
}
@Override
public void linkLabel(@NotNull Mindmap mindmap, @NotNull final Label label) {
mindmap.addLabel(label);
}
@Override
public void removeLabel(@NotNull Mindmap mindmap, @NotNull Label label) {
mindmap.removeLabel(label);
}
@Override
public Mindmap getMindmapByTitle(String title, User user) {
return mindmapManager.getMindmapByTitle(title, user);
@ -108,6 +101,12 @@ public class MindmapServiceImpl
return mindmapManager.getMindmapById(id);
}
@NotNull
@Override
public List<Mindmap> findMindmapsByUser(@NotNull User user) {
return mindmapManager.findMindmapByUser(user);
}
@Override
public List<Collaboration> findCollaborations(@NotNull User user) {
return mindmapManager.findCollaboration(user.getId());
@ -160,9 +159,9 @@ public class MindmapServiceImpl
if (mindmap.getCreator().identityEquality(user) || isAdmin(user)) {
mindmapManager.removeMindmap(mindmap);
} else {
final Collaboration collaboration = mindmap.findCollaboration(user);
if (collaboration != null) {
this.removeCollaboration(mindmap, collaboration);
final Optional<Collaboration> collaboration = mindmap.findCollaboration(user);
if (collaboration.isPresent()) {
this.removeCollaboration(mindmap, collaboration.get());
}
}
}

View File

@ -28,6 +28,7 @@ import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
public class MindMapBean {
@ -90,10 +91,6 @@ public class MindMapBean {
return DateFormat.getInstance().format(mindmap.getCreationTime().getTime());
}
public String getTags() {
return mindmap.getTags();
}
private List<CollaboratorBean> filterCollaboratorBy(Set<Collaboration> source, CollaborationRole role) {
List<CollaboratorBean> col = new ArrayList<CollaboratorBean>();
if (source != null) {
@ -167,8 +164,8 @@ public class MindMapBean {
}
public String getRole() {
final Collaboration collaboration = this.mindmap.findCollaboration(collaborator);
return collaboration.getRole().getLabel();
final Optional<Collaboration> collaboration = this.mindmap.findCollaboration(collaborator);
return collaboration.map(value -> value.getRole().getLabel()).orElse("none");
}

View File

@ -8,4 +8,7 @@
<cache name="com.wisemapping.model.User"
maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600"
timeToLiveSeconds="3600" overflowToDisk="false"/>
<cache name="com.wisemapping.model.Label"
maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600"
timeToLiveSeconds="3600" overflowToDisk="false"/>
</ehcache>

View File

@ -1,6 +1,6 @@
log4j.rootLogger=INFI, stdout, R
log4j.rootLogger=DEBUG, stdout, R
log4j.logger.com.wisemapping=DEBUG,R
log4j.logger.org.springframework=INFO,R
log4j.logger.org.springframework=DEBUG,R
log4j.logger.org.hibernate=DEBUG,R
# Stdout logger <20>

View File

@ -1,56 +0,0 @@
package com.wisemapping.test.model;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wisemapping.rest.model.RestCollaboration;
import com.wisemapping.rest.model.RestCollaborationList;
import com.wisemapping.rest.model.RestMindmap;
import com.wisemapping.rest.model.RestUser;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.List;
@Test
public class JsonTest {
@Test
void deserialize() throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json1 = "{\"id\":\"1\",\"xml\":\"<map name=\\\"1\\\" version=\\\"tango\\\"><topic central=\\\"true\\\" text=\\\"ss\\\" id=\\\"1\\\"/></map>\",\"properties\":\"{\\\"zoom\\\":0.85}\"}";
mapper.readValue(json1, RestMindmap.class);
String json2 = "{\"title\":\"some title\",\"description\":\"description here\"}";
mapper.readValue(json2, RestMindmap.class);
String userJson = "{\"email\":\"admin@wisemapping.org\",\"tags\":[],\"creationDate\":1329706800000,\"firstname\":\"Wise\",\"lastname\":\"test\",\"password\":\"test\"}";
final RestUser restUser = mapper.readValue(userJson, RestUser.class);
}
@Test
void serialize() throws IOException {
ObjectMapper mapper = new ObjectMapper();
//
// final RestMindmap value = new RestMindmap();
// value.setTitle("titl");
// value.setTitle("desck");
// final String restMindmap = mapper.writeValueAsString(value);
}
@Test
void deserializeCollbsList() throws IOException {
String collbsJson = "{\"count\":1,\"collaborations\":[{\"email\":\"paulo@pveiga.com.ar\",\"role\":\"editor\"}]}";
ObjectMapper mapper = new ObjectMapper();
final RestCollaborationList list = mapper.readValue(collbsJson, RestCollaborationList.class);
final List<RestCollaboration> collaborations = list.getCollaborations();
for (RestCollaboration collaboration : collaborations) {
final String role = collaboration.getRole();
final String email = collaboration.getEmail();
}
}
}

View File

@ -10,6 +10,7 @@ import org.springframework.http.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.testng.Assert;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@ -35,10 +36,10 @@ public class RestLabelITCase {
userEmail = restAdminITCase.createNewUser(MediaType.APPLICATION_JSON);
}
@Test(dataProviderClass = RestHelper.class, dataProvider="ContentType-Provider-Function")
@Test(dataProviderClass = RestHelper.class, dataProvider = "ContentType-Provider-Function")
public void createLabel(final @NotNull MediaType mediaType) throws IOException, WiseMappingException { // Configure media types ...
final HttpHeaders requestHeaders = RestHelper.createHeaders(mediaType);
final RestTemplate template = RestHelper.createTemplate( userEmail + ":" + "admin");
final RestTemplate template = RestHelper.createTemplate(userEmail + ":" + "admin");
// Create a new label
final String title1 = "Label 1 - " + mediaType.toString();
@ -74,17 +75,17 @@ public class RestLabelITCase {
return response.getBody();
}
@Test(dataProviderClass = RestHelper.class, dataProvider="ContentType-Provider-Function")
@Test(dataProviderClass = RestHelper.class, dataProvider = "ContentType-Provider-Function")
public void createLabelWithoutRequiredField(final @NotNull MediaType mediaType) throws IOException, WiseMappingException {
final HttpHeaders requestHeaders = RestHelper.createHeaders(mediaType);
final RestTemplate template = RestHelper.createTemplate( userEmail + ":" + "admin");
final RestTemplate template = RestHelper.createTemplate(userEmail + ":" + "admin");
try {
addNewLabel(requestHeaders, template, null, COLOR, ICON);
fail("Wrong response");
} catch (HttpClientErrorException e) {
final String responseBodyAsString = e.getResponseBodyAsString();
assertTrue (responseBodyAsString.contains("Required field cannot be left blank"));
assertTrue(responseBodyAsString.contains("Required field cannot be left blank"));
}
try {
@ -102,13 +103,17 @@ public class RestLabelITCase {
final String responseBodyAsString = e.getResponseBodyAsString();
assert (responseBodyAsString.contains("Required field cannot be left blank"));
}
}
@Test(dataProviderClass = RestHelper.class, dataProvider="ContentType-Provider-Function")
@Test(dataProviderClass = RestHelper.class, dataProvider = "ContentType-Provider-Function")
public void validateLabelsUserIsolation(final @NotNull MediaType mediaType) throws IOException, WiseMappingException { // Configure media types ...
throw new SkipException("missing test: labels belong to users");
}
@Test(dataProviderClass = RestHelper.class, dataProvider = "ContentType-Provider-Function")
public void deleteLabel(final @NotNull MediaType mediaType) throws IOException, WiseMappingException {
final HttpHeaders requestHeaders = RestHelper.createHeaders(mediaType);
final RestTemplate template = RestHelper.createTemplate( userEmail + ":" + "admin");
final RestTemplate template = RestHelper.createTemplate(userEmail + ":" + "admin");
final String title = "title to delete";
final URI resourceUri = addNewLabel(requestHeaders, template, title, COLOR, ICON);

View File

@ -40,10 +40,10 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final String title1 = "List Maps 1 - " + mediaType.toString();
final String title1 = "List Maps 1 - " + mediaType;
addNewMap(requestHeaders, template, title1);
final String title2 = "List Maps 2 - " + mediaType.toString();
final String title2 = "List Maps 2 - " + mediaType;
addNewMap(requestHeaders, template, title2);
// Check that the map has been created ...
@ -73,7 +73,7 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final String title1 = "Map to delete - " + mediaType.toString();
final String title1 = "Map to delete - " + mediaType;
final URI resourceUri = addNewMap(requestHeaders, template, title1);
// Now remove it ...
@ -93,11 +93,11 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final URI resourceUri = addNewMap(requestHeaders, template, "Map to change title - " + mediaType.toString());
final URI resourceUri = addNewMap(requestHeaders, template, "Map to change title - " + mediaType);
// Change map title ...
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
final String newTitle = "New map to change title - " + mediaType.toString();
final String newTitle = "New map to change title - " + mediaType;
final HttpEntity<String> updateEntity = new HttpEntity<String>(newTitle, requestHeaders);
template.put(HOST_PORT + resourceUri + "/title", updateEntity);
@ -112,7 +112,7 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final String title = "Map to Validate Creation - " + mediaType.toString();
final String title = "Map to Validate Creation - " + mediaType;
final URI resourceUri = addNewMap(requestHeaders, template, title);
// Try to create a map with the same title ..
@ -139,11 +139,11 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final URI resourceUri = addNewMap(requestHeaders, template, "Map to change Description - " + mediaType.toString());
final URI resourceUri = addNewMap(requestHeaders, template, "Map to change Description - " + mediaType);
// Change map title ...
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
final String newDescription = "New map to change description - " + mediaType.toString();
final String newDescription = "New map to change description - " + mediaType;
final HttpEntity<String> updateEntity = new HttpEntity<String>(newDescription, requestHeaders);
template.put(HOST_PORT + resourceUri + "/description", updateEntity);
@ -158,7 +158,7 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final String title = "Update XML sample " + mediaType.toString();
final String title = "Update XML sample " + mediaType;
final URI resourceUri = addNewMap(requestHeaders, template, title);
// Update map xml content ...
@ -179,13 +179,13 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final String title = "Map to clone sample " + mediaType.toString();
final String title = "Map to clone sample " + mediaType;
final String xml = "<map><node text='this is a cloned map'></map>";
final URI newMapUri = addNewMap(requestHeaders, template, title, xml);
// Clone map ...
final RestMindmapInfo restMindmap = new RestMindmapInfo();
restMindmap.setTitle("Cloned map but with previous content." + mediaType.toString());
restMindmap.setTitle("Cloned map but with previous content." + mediaType);
restMindmap.setDescription("Cloned map desc");
// Create a new map ...
@ -197,10 +197,14 @@ public class RestMindmapITCase {
assertEquals(response.getXml(), xml);
}
@Test(dataProviderClass = RestHelper.class, dataProvider = "ContentType-Provider-Function")
public void verifyMapOwnership(final @NotNull MediaType mediaType) throws IOException, WiseMappingException { // Configure media types ...
throw new SkipException("missing test: removeUserShouldOnlyDeleteOnwedMap");
}
@Test(dataProviderClass = RestHelper.class, dataProvider = "ContentType-Provider-Function")
public void updateMap(final @NotNull MediaType mediaType) throws IOException, WiseMappingException { // Configure media types ...
if(MediaType.APPLICATION_XML==mediaType){
if (MediaType.APPLICATION_XML == mediaType) {
throw new SkipException("Some research need to check why it's falling.");
}
@ -208,7 +212,7 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final String title = "Update sample " + mediaType.toString();
final String title = "Update sample " + mediaType;
final URI resourceUri = addNewMap(requestHeaders, template, title);
// Build map to update ...
@ -224,7 +228,7 @@ public class RestMindmapITCase {
// Check that the map has been updated ...
HttpEntity<RestUser> findMapEntity = new HttpEntity<RestUser>(requestHeaders);
final ResponseEntity<RestMindmap> response = template.exchange(HOST_PORT + resourceUri.toString(), HttpMethod.GET, findMapEntity, RestMindmap.class);
final ResponseEntity<RestMindmap> response = template.exchange(HOST_PORT + resourceUri, HttpMethod.GET, findMapEntity, RestMindmap.class);
assertEquals(response.getBody().getXml(), mapToUpdate.getXml());
assertEquals(response.getBody().getProperties(), mapToUpdate.getProperties());
}
@ -235,7 +239,7 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final URI resourceUri = addNewMap(requestHeaders, template, "Map for addCollabs - " + mediaType.toString());
final URI resourceUri = addNewMap(requestHeaders, template, "Map for addCollabs - " + mediaType);
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
@ -271,7 +275,7 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final URI resourceUri = addNewMap(requestHeaders, template, "Map for updateCollabType - " + mediaType.toString());
final URI resourceUri = addNewMap(requestHeaders, template, "Map for updateCollabType - " + mediaType);
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
@ -294,7 +298,7 @@ public class RestMindmapITCase {
RestCollaborationList responseCollbs = response.getBody();
assertEquals(responseCollbs.getCount(), 2);
// Update the collaboration type ...
// Update the collaboration type ...
collab.setRole("viewer");
template.put(HOST_PORT + resourceUri + "/collabs/", updateEntity);
@ -311,7 +315,7 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final URI resourceUri = addNewMap(requestHeaders, template, "Map for deleteCollabs - " + mediaType.toString());
final URI resourceUri = addNewMap(requestHeaders, template, "Map for deleteCollabs - " + mediaType);
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
@ -357,7 +361,7 @@ public class RestMindmapITCase {
final RestTemplate template = createTemplate(userEmail);
// Create a sample map ...
final URI resourceUri = addNewMap(requestHeaders, template, "Map for Collaboration - " + mediaType.toString());
final URI resourceUri = addNewMap(requestHeaders, template, "Map for Collaboration - " + mediaType);
// Add a new collaboration ...
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
@ -375,34 +379,50 @@ public class RestMindmapITCase {
template.put(HOST_PORT + resourceUri + "/collabs/", updateEntity);
}
@Test(dataProviderClass = RestHelper.class, dataProvider = "ContentType-Provider-Function")
public void removeLabelFromMindmap(final @NotNull MediaType mediaType) throws IOException, WiseMappingException { // Configure media types ...
throw new SkipException("missing test: label removal from map");
}
@Test(dataProviderClass = RestHelper.class, dataProvider = "ContentType-Provider-Function")
public void deleteMapAndCheckLabels(final @NotNull MediaType mediaType) throws IOException, WiseMappingException { // Configure media types ...
throw new SkipException("missing test: delete map should not affects others labels");
}
@Test(dataProviderClass = RestHelper.class, dataProvider = "ContentType-Provider-Function")
public void addLabelToMindmap(final @NotNull MediaType mediaType) throws IOException, WiseMappingException { // Configure media types ...
if (MediaType.APPLICATION_XML == mediaType) {
throw new SkipException("Some research need to check why it's falling.");
}
final HttpHeaders requestHeaders = createHeaders(mediaType);
final RestTemplate template = createTemplate(userEmail);
// Create a new label
final String titleLabel = "Label 1 - " + mediaType.toString();
final String titleLabel = "Label 1 - " + mediaType;
final URI labelUri = RestLabelITCase.addNewLabel(requestHeaders, template, titleLabel, COLOR, ICON);
// Create a sample map ...
final String mapTitle = "Maps 1 - " + mediaType.toString();
final String mapTitle = "Maps 1 - " + mediaType;
final URI mindmapUri = addNewMap(requestHeaders, template, mapTitle);
final String mapId = mindmapUri.getPath().replace("/service/maps/", "");
final RestLabel restLabel = new RestLabel();
restLabel.setColor(COLOR);
// Assign label to map ...
String labelId = labelUri.getPath().replace("/service/labels/", "");
restLabel.setId(Integer.parseInt(labelId));
restLabel.setTitle(titleLabel);
HttpEntity<String> labelEntity = new HttpEntity<>(labelId, requestHeaders);
template.postForLocation(BASE_REST_URL + "/maps/" + mapId + "/labels", labelEntity);
HttpEntity<RestLabel> labelEntity = new HttpEntity<>(restLabel, requestHeaders);
template.postForLocation(BASE_REST_URL + "/labels/maps?ids=" + mapId, labelEntity);
// Check that the label has been assigned ...
final HttpEntity findMapEntity = new HttpEntity(requestHeaders);
final ResponseEntity<RestMindmapList> mindmapList = template.exchange(BASE_REST_URL + "/maps/", HttpMethod.GET, findMapEntity, RestMindmapList.class);
// Load map again ..
final RestMindmap withLabel = findMap(requestHeaders, template, mindmapUri);
final List<RestMindmapInfo> mindmapsInfo = mindmapList.getBody().getMindmapsInfo();
Optional<RestMindmapInfo> mindmapInfo = mindmapsInfo
.stream()
.filter(m -> m.getId() == Integer.parseInt(mapId))
.findAny();
// assertTrue(withLabel.getDelegated().getLabels().size() == 1);
assertTrue(mindmapInfo.get().getLabels().size() == 1);
}
private RestMindmap findMap(HttpHeaders requestHeaders, RestTemplate template, URI resourceUri) {
@ -411,6 +431,7 @@ public class RestMindmapITCase {
return response.getBody();
}
private URI addNewMap(@NotNull HttpHeaders requestHeaders, @NotNull RestTemplate template, @NotNull String title, @Nullable String xml) throws IOException, WiseMappingException {
final RestMindmap restMindmap = new RestMindmap();
restMindmap.setTitle(title);