diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/BaseRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/BaseRestImpl.java index 88bbff2177235ea9d63129360e3fed75396b1b6a..54e58c6f1d6400437ede3acb2d959bc5bcc07ead 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/BaseRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/BaseRestImpl.java @@ -2,7 +2,6 @@ package lcsb.mapviewer.api; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; -import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -126,31 +125,28 @@ public abstract class BaseRestImpl { result.put("type", annotation.getDataType().name()); result.put("resource", annotation.getResource()); result.put("id", annotation.getId()); - - if (annotation.getAnnotator() != null) { - try { - result.put("annotatorClassName", annotation.getAnnotator().getName()); - result.put("descriptionByType", - ((ElementAnnotator) annotation.getAnnotator().getConstructor().newInstance()).getDescription( annotation.getDataType()) - ); - result.put("descriptionByTypeRelation", - ((ElementAnnotator) annotation.getAnnotator().getConstructor().newInstance()).getDescription( - annotation.getDataType(), - annotation.getRelationType()) - ); - - }catch(Exception e) { - logger.error("Problem with retrieving description from annotator", e); - result.put("annotatorClassName", ""); - result.put("descriptionByType", ""); - result.put("descriptionByTypeRelation", ""); - } + + if (annotation.getAnnotator() != null) { + try { + result.put("annotatorClassName", annotation.getAnnotator().getName()); + result.put("descriptionByType", ((ElementAnnotator) annotation.getAnnotator().getConstructor().newInstance()) + .getDescription(annotation.getDataType())); + result.put("descriptionByTypeRelation", + ((ElementAnnotator) annotation.getAnnotator().getConstructor().newInstance()) + .getDescription(annotation.getDataType(), annotation.getRelationType())); + + } catch (Exception e) { + logger.error("Problem with retrieving description from annotator", e); + result.put("annotatorClassName", ""); + result.put("descriptionByType", ""); + result.put("descriptionByTypeRelation", ""); + } } else { - result.put("annotatorClassName", ""); - result.put("descriptionByType", ""); - result.put("descriptionByTypeRelation", ""); + result.put("annotatorClassName", ""); + result.put("descriptionByType", ""); + result.put("descriptionByTypeRelation", ""); } - + return result; } else { throw new InvalidArgumentException("invalid miriam data: " + annotation); @@ -206,7 +202,7 @@ public abstract class BaseRestImpl { } protected List<Model> getModels(String projectId, String modelId, String token) throws SecurityException { - Model model = modelService.getLastModelByProjectId(projectId, userService.getToken(token)); + Model model = modelService.getLastModelByProjectId(projectId, token); List<Model> models = new ArrayList<>(); if (!modelId.equals("*")) { @@ -384,4 +380,11 @@ public abstract class BaseRestImpl { } return this.mathMlTransformer; } + + protected void verifyToken(String token) throws SecurityException { + if (getUserService().getUserByToken(token) == null) { + throw new SecurityException("Invalid token"); + } + } + } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationRestImpl.java index 3dc7786f2089db07d14fa75b3471fd0a6b7449d7..fcdc73a49ad371a720df56aec65cf62678d77c4e 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationRestImpl.java @@ -55,7 +55,7 @@ public class ConfigurationRestImpl extends BaseRestImpl { private ModelAnnotator modelAnnotator; public List<ConfigurationView> getAllValues(String token) throws SecurityException { - userService.getToken(token); + verifyToken(token); return configurationService.getAllValues(); } @@ -94,7 +94,7 @@ public class ConfigurationRestImpl extends BaseRestImpl { } public List<Map<String, Object>> getImageFormats(String token) throws SecurityException { - userService.getToken(token); + verifyToken(token); List<Map<String, Object>> result = new ArrayList<>(); ImageGenerators imageGenerators = new ImageGenerators(); @@ -112,7 +112,7 @@ public class ConfigurationRestImpl extends BaseRestImpl { } public List<Map<String, Object>> getModelFormats(String token) throws SecurityException { - userService.getToken(token); + verifyToken(token); List<IConverter> converters = getModelConverters(); List<Map<String, Object>> result = new ArrayList<>(); @@ -128,7 +128,7 @@ public class ConfigurationRestImpl extends BaseRestImpl { } public List<Map<String, Object>> getOverlayTypes(String token) throws SecurityException { - userService.getToken(token); + verifyToken(token); List<Map<String, Object>> result = new ArrayList<>(); for (ColorSchemaType type : ColorSchemaType.values()) { Map<String, Object> map = new HashMap<>(); @@ -139,7 +139,7 @@ public class ConfigurationRestImpl extends BaseRestImpl { } public Set<Map<String, String>> getElementTypes(String token) throws SecurityException { - userService.getToken(token); + verifyToken(token); return getClassStringTypesList(Element.class); } @@ -171,7 +171,7 @@ public class ConfigurationRestImpl extends BaseRestImpl { } public Set<Map<String, String>> getReactionTypes(String token) throws SecurityException { - userService.getToken(token); + verifyToken(token); return getClassStringTypesList(Reaction.class); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeRestImpl.java index fc7c4f7ab211e029e9a3573021b9e39976fd238d..e517c1eaad75d97c2ad20b2b68dc7d7e83037ecd 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/genomics/ReferenceGenomeRestImpl.java @@ -10,49 +10,43 @@ import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.interfaces.IReferenceGenomeService; -import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ReferenceGenomeView; @Transactional(value = "txManager") public class ReferenceGenomeRestImpl { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = Logger.getLogger(ReferenceGenomeRestImpl.class); - - @Autowired - private IUserService userService; - - /** - * Service that manages reference genomes. - */ - @Autowired - private IReferenceGenomeService referenceGenomeService; - - public ReferenceGenomeView getReferenceGenome(String token, String organismId, String type, String version) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = userService.getToken(token); - - MiriamData organism = null; - if (organismId != null && !organismId.isEmpty()) { - organism = new MiriamData(MiriamType.TAXONOMY, organismId); - } else { - throw new QueryException("Unknown taxonomy organism: " + organismId); - } - ReferenceGenomeView result = null; - try { - ReferenceGenomeType genomeType = ReferenceGenomeType.valueOf(type); - version = version.replaceAll("\\*", ""); - result = referenceGenomeService.getReferenceGenomeViewByParams(organism, genomeType, version, authenticationToken); - if (result == null) { - throw new QueryException("Cannot find requested reference genome"); - } - } catch (IllegalArgumentException e) { - throw new QueryException("Cannot find type: " + type); - } - return result; - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = Logger.getLogger(ReferenceGenomeRestImpl.class); + + /** + * Service that manages reference genomes. + */ + @Autowired + private IReferenceGenomeService referenceGenomeService; + + public ReferenceGenomeView getReferenceGenome(String token, String organismId, String type, String version) + throws SecurityException, QueryException { + MiriamData organism = null; + if (organismId != null && !organismId.isEmpty()) { + organism = new MiriamData(MiriamType.TAXONOMY, organismId); + } else { + throw new QueryException("Unknown taxonomy organism: " + organismId); + } + ReferenceGenomeView result = null; + try { + ReferenceGenomeType genomeType = ReferenceGenomeType.valueOf(type); + version = version.replaceAll("\\*", ""); + result = referenceGenomeService.getReferenceGenomeViewByParams(organism, genomeType, version, token); + if (result == null) { + throw new QueryException("Cannot find requested reference genome"); + } + } catch (IllegalArgumentException e) { + throw new QueryException("Cannot find type: " + type); + } + return result; + } } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshController.java b/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshController.java index 82d645cb8972bf78ff6ad3934872ba7999c007eb..378fc0ac2994aa633ae36b6ed472f6d5ae749b58 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/mesh/MeshController.java @@ -1,40 +1,18 @@ package lcsb.mapviewer.api.mesh; -import java.io.IOException; -import java.util.Calendar; -import java.util.HashMap; -import java.util.List; import java.util.Map; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; -import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; - import lcsb.mapviewer.api.BaseController; -import lcsb.mapviewer.api.ObjectNotFoundException; -import lcsb.mapviewer.api.QueryException; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.services.SecurityException; -import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.view.AuthenticationToken; @RestController public class MeshController extends BaseController { diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/ProjectRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/ProjectRestImpl.java index 19612ef9238b6ac1ff622c8bd71d2e20135b9b7a..69fb7e38daafb097c0caac1ea35f33f2691762fc 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/ProjectRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/ProjectRestImpl.java @@ -75,7 +75,6 @@ import lcsb.mapviewer.services.utils.ColorSchemaReader; import lcsb.mapviewer.services.utils.CreateProjectParams; import lcsb.mapviewer.services.utils.data.BuildInLayout; import lcsb.mapviewer.services.utils.gmap.CoordinationConverter; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.OverviewImageViewFactory; @Transactional(value = "txManager") @@ -114,8 +113,7 @@ public class ProjectRestImpl extends BaseRestImpl { private UploadedFileEntryDao uploadedFileEntryDao; public ProjectMetaData getProject(String projectId, String token) throws SecurityException, ObjectNotFoundException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); if (project == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } @@ -185,8 +183,7 @@ public class ProjectRestImpl extends BaseRestImpl { } public FileEntry getSource(String token, String projectId) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); if (project == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } @@ -200,10 +197,9 @@ public class ProjectRestImpl extends BaseRestImpl { public FileEntry getModelAsImage(String token, String projectId, String modelId, String handlerClass, String backgroundOverlayId, String overlayIds, String zoomLevel, String polygonString) throws SecurityException, QueryException, IOException, InvalidColorSchemaException, CommandExecutionException, DrawingException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - User user = getUserService().getUserByToken(authenticationToken); + User user = getUserService().getUserByToken(token); - Model topModel = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model topModel = getModelService().getLastModelByProjectId(projectId, token); if (topModel == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } @@ -298,7 +294,7 @@ public class ProjectRestImpl extends BaseRestImpl { } List<Integer> visibleLayoutIds = deserializeIdList(overlayIds); for (Integer integer : visibleLayoutIds) { - Map<Object, ColorSchema> map = layoutService.getElementsForLayout(colorModel, integer, authenticationToken); + Map<Object, ColorSchema> map = layoutService.getElementsForLayout(colorModel, integer, token); params.addVisibleLayout(map); } @@ -332,9 +328,7 @@ public class ProjectRestImpl extends BaseRestImpl { String backgroundOverlayId, String overlayIds, String zoomLevel, String polygonString) throws SecurityException, QueryException, IOException, InvalidColorSchemaException, CommandExecutionException, ConverterException, InconsistentModelException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - - Model topModel = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model topModel = getModelService().getLastModelByProjectId(projectId, token); if (topModel == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } @@ -367,10 +361,8 @@ public class ProjectRestImpl extends BaseRestImpl { public Map<String, Object> getStatistics(String projectId, String token) throws SecurityException, ObjectNotFoundException { - Map<String, Object> result = new HashMap<String, Object>(); - AuthenticationToken authenticationToken = getUserService().getToken(token); - - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Map<String, Object> result = new HashMap<>(); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } @@ -416,8 +408,7 @@ public class ProjectRestImpl extends BaseRestImpl { } public List<ProjectMetaData> getProjects(String token) throws SecurityException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - List<Project> projects = getProjectService().getAllProjects(authenticationToken); + List<Project> projects = getProjectService().getAllProjects(token); List<ProjectMetaData> result = new ArrayList<>(); for (Project project : projects) { result.add(createData(project)); @@ -427,12 +418,11 @@ public class ProjectRestImpl extends BaseRestImpl { public ProjectMetaData updateProject(String token, String projectId, Map<String, Object> data) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); if (project == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } - boolean canModify = getUserService().userHasPrivilege(authenticationToken, PrivilegeType.ADD_MAP); + boolean canModify = getUserService().userHasPrivilege(token, PrivilegeType.ADD_MAP); if (!canModify) { throw new SecurityException("You cannot update projects"); } @@ -497,9 +487,8 @@ public class ProjectRestImpl extends BaseRestImpl { public ProjectMetaData addProject(String token, String projectId, MultiValueMap<String, Object> data, String path) throws SecurityException, QueryException, IOException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - User user = getUserService().getUserByToken(authenticationToken); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + User user = getUserService().getUserByToken(token); + Project project = getProjectService().getProjectByProjectId(projectId, token); if (project != null) { logger.debug(project.getProjectId()); throw new ObjectExistsException("Project with given id already exists"); @@ -532,7 +521,7 @@ public class ProjectRestImpl extends BaseRestImpl { params.addUser(user.getLogin(), null); params.async(true); params.parser(parser); - params.authenticationToken(authenticationToken); + params.authenticationToken(token); params.autoResize(getFirstValue(data.get("auto-resize"))); params.cacheModel(getFirstValue(data.get("cache"))); params.description(getFirstValue(data.get("description"))); @@ -640,9 +629,8 @@ public class ProjectRestImpl extends BaseRestImpl { public ProjectMetaData removeProject(String token, String projectId, String path) throws ObjectNotFoundException, SecurityException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); - getProjectService().removeProject(project, path, true, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); + getProjectService().removeProject(project, path, true, token); return getProject(projectId, token); } @@ -684,8 +672,7 @@ public class ProjectRestImpl extends BaseRestImpl { public Map<String, Object> getLogs(String projectId, String level, String token, String startString, Integer length, String sortColumn, String sortOrder, String search) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); if (project == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImpl.java index 47792473aa7c4192fc605c36963ba95374bfa618..2c8427aaa976c26adb592932767ee679ba4ffec9 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/chemicals/ChemicalRestImpl.java @@ -25,12 +25,9 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.services.SecurityException; -import lcsb.mapviewer.services.interfaces.IModelService; -import lcsb.mapviewer.services.interfaces.IUserService; import lcsb.mapviewer.services.search.data.ElementIdentifier.ElementIdentifierType; import lcsb.mapviewer.services.search.db.DbSearchCriteria; import lcsb.mapviewer.services.search.db.chemical.IChemicalService; -import lcsb.mapviewer.services.view.AuthenticationToken; @Transactional(value = "txManager") public class ChemicalRestImpl extends BaseRestImpl { @@ -51,8 +48,7 @@ public class ChemicalRestImpl extends BaseRestImpl { public List<Map<String, Object>> getChemicalsByQuery(String token, String projectId, String columns, String query) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } @@ -172,8 +168,7 @@ public class ChemicalRestImpl extends BaseRestImpl { public List<Map<String, Object>> getChemicalsByTarget(String token, String projectId, String targetType, String targetId, String columns) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } @@ -220,9 +215,9 @@ public class ChemicalRestImpl extends BaseRestImpl { return result; } - public List<String> getSuggestedQueryList(String projectId, String token) throws SecurityException, ChemicalSearchException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + public List<String> getSuggestedQueryList(String projectId, String token) + throws SecurityException, ChemicalSearchException { + Project project = getProjectService().getProjectByProjectId(projectId, token); return chemicalParser.getSuggestedQueryList(project, project.getDisease()); } } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentRestImpl.java index b42991f0670f18b6f45e501f06c83c25ea39ec5a..4b777b9bc7d8de831338e922d0aac9d8c00a6635 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/comments/CommentRestImpl.java @@ -25,11 +25,8 @@ import lcsb.mapviewer.persist.dao.map.ReactionDao; import lcsb.mapviewer.persist.dao.map.species.ElementDao; import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.interfaces.ICommentService; -import lcsb.mapviewer.services.interfaces.IModelService; -import lcsb.mapviewer.services.interfaces.IUserService; import lcsb.mapviewer.services.overlay.IconManager; import lcsb.mapviewer.services.search.data.ElementIdentifier.ElementIdentifierType; -import lcsb.mapviewer.services.view.AuthenticationToken; @Transactional(value = "txManager") public class CommentRestImpl extends BaseRestImpl { @@ -50,18 +47,16 @@ public class CommentRestImpl extends BaseRestImpl { public List<Map<String, Object>> getCommentList(String token, String projectId, String columns, String elementId, String elementType, String removed) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); if (project == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } - boolean isAdmin = getUserService().userHasPrivilege(authenticationToken, PrivilegeType.EDIT_COMMENTS_PROJECT, - project); + boolean isAdmin = getUserService().userHasPrivilege(token, PrivilegeType.EDIT_COMMENTS_PROJECT, project); Set<String> columnsSet = createCommentColumnSet(columns, isAdmin); List<Map<String, Object>> result = new ArrayList<>(); - List<Comment> comments = commentService.getCommentsByProject(project, authenticationToken); + List<Comment> comments = commentService.getCommentsByProject(project, token); for (Comment comment : comments) { boolean reject = false; if (!"".equals(elementType)) { @@ -291,8 +286,7 @@ public class CommentRestImpl extends BaseRestImpl { public Map<String, Object> addComment(String token, String projectId, String elementType, String elementId, String name, String email, String content, boolean pinned, Point2D pointCoordinates, String submodelId) throws QueryException, SecurityException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } @@ -328,15 +322,13 @@ public class CommentRestImpl extends BaseRestImpl { submodel); Project project = model.getProject(); - boolean isAdmin = getUserService().userHasPrivilege(authenticationToken, PrivilegeType.EDIT_COMMENTS_PROJECT, - project); + boolean isAdmin = getUserService().userHasPrivilege(token, PrivilegeType.EDIT_COMMENTS_PROJECT, project); return preparedComment(comment, createCommentColumnSet("", isAdmin), isAdmin); } public Map<String, Object> removeComment(String token, String projectId, String commentId, String reason) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); if (project == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } @@ -345,7 +337,7 @@ public class CommentRestImpl extends BaseRestImpl { throw new ObjectNotFoundException("Comment with given id doesn't exist"); } - commentService.deleteComment(comment, authenticationToken, reason); + commentService.deleteComment(comment, token, reason); return okStatus(); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugRestImpl.java index a16f3c4565c4bcd939d696248fdb8a2f8e7c251d..af6ef3756fa328319b93fab712a33bee255ebbe4 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/drugs/DrugRestImpl.java @@ -26,7 +26,6 @@ import lcsb.mapviewer.services.interfaces.IUserService; import lcsb.mapviewer.services.search.data.ElementIdentifier.ElementIdentifierType; import lcsb.mapviewer.services.search.db.DbSearchCriteria; import lcsb.mapviewer.services.search.db.drug.IDrugService; -import lcsb.mapviewer.services.view.AuthenticationToken; @Transactional(value = "txManager") public class DrugRestImpl extends BaseRestImpl { @@ -48,8 +47,7 @@ public class DrugRestImpl extends BaseRestImpl { public List<Map<String, Object>> getDrugsByQuery(String token, String projectId, String columns, String query) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = userService.getToken(token); - Model model = modelService.getLastModelByProjectId(projectId, authenticationToken); + Model model = modelService.getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } @@ -180,8 +178,7 @@ public class DrugRestImpl extends BaseRestImpl { public List<Map<String, Object>> getDrugsByTarget(String token, String projectId, String targetType, String targetId, String columns) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = userService.getToken(token); - Model model = modelService.getLastModelByProjectId(projectId, authenticationToken); + Model model = modelService.getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } @@ -225,8 +222,7 @@ public class DrugRestImpl extends BaseRestImpl { public List<String> getSuggestedQueryList(String projectId, String token) throws SecurityException, DrugSearchException { - AuthenticationToken authenticationToken = userService.getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); return drugService.getSuggestedQueryList(project, project.getOrganism()); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImpl.java index 4037cda6cb8d9af3dd88ba0d440a76908f42b68e..a292ef60b5695421607ab7bf498654939303c891 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImpl.java @@ -25,7 +25,6 @@ import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.search.data.ElementIdentifier.ElementIdentifierType; import lcsb.mapviewer.services.search.db.DbSearchCriteria; import lcsb.mapviewer.services.search.db.mirna.IMiRNAService; -import lcsb.mapviewer.services.view.AuthenticationToken; @Transactional(value = "txManager") public class MiRnaRestImpl extends BaseRestImpl { @@ -44,8 +43,7 @@ public class MiRnaRestImpl extends BaseRestImpl { public List<Map<String, Object>> getMiRnasByQuery(String token, String projectId, String columns, String query) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } @@ -127,8 +125,7 @@ public class MiRnaRestImpl extends BaseRestImpl { public List<Map<String, Object>> getMiRnasByTarget(String token, String projectId, String targetType, String targetId, String columns) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } @@ -172,8 +169,7 @@ public class MiRnaRestImpl extends BaseRestImpl { public List<String> getSuggestedQueryList(String projectId, String token) throws SecurityException, MiRNASearchException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); return miRNAParser.getSuggestedQueryList(project); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelRestImpl.java index 7c58d07ffa1272781cacdb2bb5511cf1397ec2ea..b39b48d148e0327efe16cfbbfec66336cae7f0fd 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/ModelRestImpl.java @@ -19,7 +19,6 @@ import lcsb.mapviewer.model.map.model.ModelData; import lcsb.mapviewer.model.user.PrivilegeType; import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.interfaces.ILayoutService; -import lcsb.mapviewer.services.view.AuthenticationToken; @Transactional(value = "txManager") public class ModelRestImpl extends BaseRestImpl { @@ -35,18 +34,16 @@ public class ModelRestImpl extends BaseRestImpl { public List<ModelMetaData> getModels(String projectId, String token) throws SecurityException, ObjectNotFoundException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); if (project == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } - List<ModelMetaData> result = createData(project, authenticationToken); + List<ModelMetaData> result = createData(project, token); return result; } public ModelMetaData getModel(String projectId, String modelId, String token) throws SecurityException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); Model submodel = model.getSubmodelById(modelId); if (submodel == null) { return null; @@ -58,13 +55,12 @@ public class ModelRestImpl extends BaseRestImpl { metaDataToProcess.addAll(result.getSubmodels()); for (ModelMetaData submodelData : metaDataToProcess) { submodelData.setLayouts(layoutService.getGeneralLayouts(model.getSubmodelById(submodelData.getIdObject()))); - logger.debug(submodelData.getLayouts()); } return result; } } - private List<ModelMetaData> createData(Project project, AuthenticationToken token) throws SecurityException { + private List<ModelMetaData> createData(Project project, String token) throws SecurityException { List<ModelMetaData> result = new ArrayList<>(); Model model = getModelService().getLastModelByProjectId(project.getProjectId(), token); if (model != null) { @@ -73,7 +69,7 @@ public class ModelRestImpl extends BaseRestImpl { models.add(model); models.addAll(model.getSubmodels()); for (Model model2 : models) { - result.add(getModel(project.getProjectId(), model2.getId() + "", token.getId())); + result.add(getModel(project.getProjectId(), model2.getId() + "", token)); } } return result; @@ -81,12 +77,11 @@ public class ModelRestImpl extends BaseRestImpl { public ModelMetaData updateModel(String projectId, String modelId, Map<String, Object> data, String token) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Project project = getProjectService().getProjectByProjectId(projectId, authenticationToken); + Project project = getProjectService().getProjectByProjectId(projectId, token); if (project == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } - boolean canModify = getUserService().userHasPrivilege(authenticationToken, PrivilegeType.ADD_MAP); + boolean canModify = getUserService().userHasPrivilege(token, PrivilegeType.ADD_MAP); if (!canModify) { throw new SecurityException("You cannot update projects"); } @@ -118,7 +113,7 @@ public class ModelRestImpl extends BaseRestImpl { throw new QueryException("Unknown field: " + fieldName); } } - getModelService().updateModel(model, authenticationToken); + getModelService().updateModel(model, token); return getModel(projectId, modelId, token); } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesRestImpl.java index b2b1dd3884d242331786a8c1349ff2f8cf9142f6..9e79f1a7f475dd8bdd07c81672da8341e4a3e8f3 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesRestImpl.java @@ -21,107 +21,108 @@ import lcsb.mapviewer.services.interfaces.IUserService; @Transactional(value = "txManager") public class BioEntitiesRestImpl extends BaseRestImpl { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = Logger.getLogger(BioEntitiesRestImpl.class); - - @Autowired - private IUserService userService; - - @Autowired - private IModelService modelService; - - @Autowired - private ISearchService searchService; - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - public List<Map<String, Object>> getClosestElementsByCoordinates(String projectId, String modelId, String token, Point2D coordinates, Integer count, - String perfectMatch) throws UserAccessException, SecurityException { - List<Map<String, Object>> resultMap = new ArrayList<>(); - - Model model = modelService.getLastModelByProjectId(projectId, userService.getToken(token)); - - Model submodel = model.getSubmodelById(modelId); - - List<BioEntity> elements = searchService.getClosestElements(submodel, coordinates, count, perfectMatch.equalsIgnoreCase("true")); - for (Object object : elements) { - Map<String, Object> result = createMinifiedSearchResult(object); - resultMap.add(result); - } - return resultMap; - } - - /** - * @return the modelService - * @see #modelService - */ - public IModelService getModelService() { - return modelService; - } - - /** - * @param modelService - * the modelService to set - * @see #modelService - */ - public void setModelService(IModelService modelService) { - this.modelService = modelService; - } - - /** - * @return the searchService - * @see #searchService - */ - public ISearchService getSearchService() { - return searchService; - } - - /** - * @param searchService - * the searchService to set - * @see #searchService - */ - public void setSearchService(ISearchService searchService) { - this.searchService = searchService; - } - - public List<Map<String, Object>> getElementsByQuery(String projectId, String token, String modelId, String query, Integer maxElements, String perfectMatch) - throws SecurityException { - List<Map<String, Object>> resultMap = new ArrayList<>(); - - Model model = modelService.getLastModelByProjectId(projectId, userService.getToken(token)); - - Integer limit = Integer.valueOf(maxElements); - boolean match = perfectMatch.equals("true"); - List<Object> elements = searchService.searchByQuery(model, query, limit, match); - for (Object object : elements) { - Map<String, Object> result = createMinifiedSearchResult(object); - resultMap.add(result); - } - return resultMap; - } - - public String[] getSuggestedQueryList(String projectId, String token) throws SecurityException { - Model model = modelService.getLastModelByProjectId(projectId, userService.getToken(token)); - return searchService.getSuggestedQueryList(model); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = Logger.getLogger(BioEntitiesRestImpl.class); + + @Autowired + private IUserService userService; + + @Autowired + private IModelService modelService; + + @Autowired + private ISearchService searchService; + + /** + * @return the userService + * @see #userService + */ + public IUserService getUserService() { + return userService; + } + + /** + * @param userService + * the userService to set + * @see #userService + */ + public void setUserService(IUserService userService) { + this.userService = userService; + } + + public List<Map<String, Object>> getClosestElementsByCoordinates(String projectId, String modelId, String token, + Point2D coordinates, Integer count, String perfectMatch) throws UserAccessException, SecurityException { + List<Map<String, Object>> resultMap = new ArrayList<>(); + + Model model = modelService.getLastModelByProjectId(projectId, token); + + Model submodel = model.getSubmodelById(modelId); + + List<BioEntity> elements = searchService.getClosestElements(submodel, coordinates, count, + perfectMatch.equalsIgnoreCase("true")); + for (Object object : elements) { + Map<String, Object> result = createMinifiedSearchResult(object); + resultMap.add(result); + } + return resultMap; + } + + /** + * @return the modelService + * @see #modelService + */ + public IModelService getModelService() { + return modelService; + } + + /** + * @param modelService + * the modelService to set + * @see #modelService + */ + public void setModelService(IModelService modelService) { + this.modelService = modelService; + } + + /** + * @return the searchService + * @see #searchService + */ + public ISearchService getSearchService() { + return searchService; + } + + /** + * @param searchService + * the searchService to set + * @see #searchService + */ + public void setSearchService(ISearchService searchService) { + this.searchService = searchService; + } + + public List<Map<String, Object>> getElementsByQuery(String projectId, String token, String modelId, String query, + Integer maxElements, String perfectMatch) throws SecurityException { + List<Map<String, Object>> resultMap = new ArrayList<>(); + + Model model = modelService.getLastModelByProjectId(projectId, token); + + Integer limit = Integer.valueOf(maxElements); + boolean match = perfectMatch.equals("true"); + List<Object> elements = searchService.searchByQuery(model, query, limit, match); + for (Object object : elements) { + Map<String, Object> result = createMinifiedSearchResult(object); + resultMap.add(result); + } + return resultMap; + } + + public String[] getSuggestedQueryList(String projectId, String token) throws SecurityException { + Model model = modelService.getLastModelByProjectId(projectId, token); + return searchService.getSuggestedQueryList(model); + } } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImpl.java index 0b0d3f1137ae9570e1aa2b87ab4151587b215eeb..4bc6766e04aedad0718514f325159aaa875a89d7 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/projects/overlays/OverlayRestImpl.java @@ -35,7 +35,6 @@ import lcsb.mapviewer.services.search.layout.FullLayoutReactionView; import lcsb.mapviewer.services.search.layout.LightLayoutAliasView; import lcsb.mapviewer.services.search.layout.LightLayoutReactionView; import lcsb.mapviewer.services.utils.data.ColorSchemaType; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.LayoutView; @Transactional(value = "txManager") @@ -58,8 +57,7 @@ public class OverlayRestImpl extends BaseRestImpl { public List<LayoutView> getOverlayList(String token, String projectId, String creatorLogin, String publicOverlay) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { return new ArrayList<>(); } @@ -97,13 +95,12 @@ public class OverlayRestImpl extends BaseRestImpl { public List<Map<String, Object>> getOverlayElements(String token, String projectId, int overlayId, String columns) throws QueryException, SecurityException { List<Map<String, Object>> result = new ArrayList<>(); - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } - List<LightLayoutAliasView> speciesList = layoutService.getAliasesForLayout(model, overlayId, authenticationToken); + List<LightLayoutAliasView> speciesList = layoutService.getAliasesForLayout(model, overlayId, token); for (LightLayoutAliasView lightLayoutAliasView : speciesList) { Map<String, Object> element = new HashMap<>(); element.put("type", ElementIdentifierType.ALIAS); @@ -111,8 +108,7 @@ public class OverlayRestImpl extends BaseRestImpl { result.add(element); } - List<LightLayoutReactionView> reactions = layoutService.getReactionsForLayout(model, overlayId, - authenticationToken); + List<LightLayoutReactionView> reactions = layoutService.getReactionsForLayout(model, overlayId, token); for (LightLayoutReactionView lightReactionView : reactions) { Map<String, Object> element = new HashMap<>(); element.put("type", ElementIdentifierType.REACTION); @@ -124,24 +120,22 @@ public class OverlayRestImpl extends BaseRestImpl { public LayoutView getOverlayById(String token, String projectId, String overlayId) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } - return layoutService.getLayoutById(Integer.valueOf(overlayId), authenticationToken); + return layoutService.getLayoutById(Integer.valueOf(overlayId), token); } public FileEntry getOverlaySource(String token, String projectId, String overlayId) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } try { Integer id = Integer.valueOf(overlayId); - Layout layout = layoutService.getLayoutDataById(id, authenticationToken); + Layout layout = layoutService.getLayoutDataById(id, token); if (layout == null) { throw new QueryException("Invalid overlay id"); } @@ -155,17 +149,16 @@ public class OverlayRestImpl extends BaseRestImpl { public LayoutView updateOverlay(String token, String projectId, String overlayId, Map<String, Object> overlayData) throws QueryException, SecurityException { - AuthenticationToken authenticationToken = getUserService().getToken(token); if (overlayData == null) { throw new QueryException("overlay field cannot be undefined"); } try { Integer id = Integer.valueOf(overlayId); - Layout layout = layoutService.getLayoutDataById(id, authenticationToken); + Layout layout = layoutService.getLayoutDataById(id, token); if (layout == null) { throw new ObjectNotFoundException("overlay doesn't exist"); } - boolean isAdmin = getUserService().userHasPrivilege(authenticationToken, PrivilegeType.LAYOUT_MANAGEMENT, + boolean isAdmin = getUserService().userHasPrivilege(token, PrivilegeType.LAYOUT_MANAGEMENT, layout.getModel().getProject()); if (layout.isPublicLayout() && !isAdmin) { throw new SecurityException("You cannot modify given overlay"); @@ -191,7 +184,7 @@ public class OverlayRestImpl extends BaseRestImpl { } } layoutDao.update(layout); - return layoutService.getLayoutById(Integer.valueOf(overlayId), authenticationToken); + return layoutService.getLayoutById(Integer.valueOf(overlayId), token); } catch (NumberFormatException e) { throw new ObjectNotFoundException("overlay doesn't exist"); } @@ -207,18 +200,17 @@ public class OverlayRestImpl extends BaseRestImpl { public Map<String, Object> removeOverlay(String token, String projectId, String overlayId) throws QueryException, SecurityException, IOException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new ObjectNotFoundException("Project with given id doesn't exist"); } try { Integer id = Integer.valueOf(overlayId); - LayoutView layout = layoutService.getLayoutById(id, authenticationToken); + LayoutView layout = layoutService.getLayoutById(id, token); if (layout == null) { throw new ObjectNotFoundException("Overlay doesn't exist"); } - if (layoutService.userCanRemoveLayout(layout, authenticationToken)) { + if (layoutService.userCanRemoveLayout(layout, token)) { layoutService.removeLayout(layout, null); return okStatus(); } else { @@ -248,12 +240,11 @@ public class OverlayRestImpl extends BaseRestImpl { public LayoutView addOverlay(String token, String projectId, String name, String description, String content, String fileId, String filename, String type) throws SecurityException, QueryException, IOException { - AuthenticationToken authenticationToken = getUserService().getToken(token); User user = getUserService().getUserByToken(token); if (Configuration.ANONYMOUS_LOGIN.equals(user.getLogin())) { throw new SecurityException("You have no privileges to add overlay"); } - Model model = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model model = getModelService().getLastModelByProjectId(projectId, token); if (model == null) { throw new QueryException("Project with given id doesn't exist"); } @@ -292,7 +283,7 @@ public class OverlayRestImpl extends BaseRestImpl { LayoutView layout = layoutService.createLayout(new CreateLayoutParams().async(false).colorInputStream(stream) .description(description).layoutFileName(filename).model(model).name(name).user(user) .colorSchemaType(colorSchemaType).directory(".")); - return layoutService.getLayoutById(Integer.valueOf(layout.getIdObject()), authenticationToken); + return layoutService.getLayoutById(Integer.valueOf(layout.getIdObject()), token); } catch (InvalidColorSchemaException e) { throw new QueryException(e.getMessage(), e); } @@ -301,9 +292,7 @@ public class OverlayRestImpl extends BaseRestImpl { public Map<String, Object> getOverlayElement(String token, String projectId, Integer modelId, Integer overlayId, Integer elementId, String elementType, String columns) throws QueryException, SecurityException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - - Model topModel = getModelService().getLastModelByProjectId(projectId, authenticationToken); + Model topModel = getModelService().getLastModelByProjectId(projectId, token); if (topModel == null) { throw new QueryException("Project with given id doesn't exist"); } @@ -311,14 +300,13 @@ public class OverlayRestImpl extends BaseRestImpl { Map<String, Object> result = new HashMap<>(); if (ElementIdentifierType.ALIAS.getJsName().equals(elementType)) { - FullLayoutAliasView layoutAliasView = layoutService.getFullAliasForLayout(model, elementId, overlayId, - authenticationToken); + FullLayoutAliasView layoutAliasView = layoutService.getFullAliasForLayout(model, elementId, overlayId, token); result.put("type", ElementIdentifierType.ALIAS); result.put("overlayContent", layoutAliasView); return result; } else if (ElementIdentifierType.REACTION.getJsName().equals(elementType)) { FullLayoutReactionView layoutAliasView = layoutService.getFullReactionForLayout(model, elementId, overlayId, - authenticationToken); + token); result.put("type", ElementIdentifierType.REACTION); result.put("overlayContent", layoutAliasView); return result; diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/users/UserController.java b/rest-api/src/main/java/lcsb/mapviewer/api/users/UserController.java index 508fa68941203ef756725bd3ee94aaad53328d9a..4312f60b41c64c6d0fb56574f46b35f43e9a38ca 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/users/UserController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/users/UserController.java @@ -15,6 +15,7 @@ import org.springframework.http.MediaType; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.web.authentication.WebAuthenticationDetails; @@ -37,7 +38,6 @@ import lcsb.mapviewer.api.QueryException; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.view.AuthenticationToken; @RestController public class UserController extends BaseController { @@ -56,9 +56,6 @@ public class UserController extends BaseController { @Autowired private AuthenticationProvider authenticationProvider; - @Autowired - private SessionRegistry sessionRegistry; - @RequestMapping(value = "/doLogin", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE }) public Map<String, Object> login(// @@ -67,20 +64,20 @@ public class UserController extends BaseController { HttpServletResponse response, // HttpServletRequest request// ) throws SecurityException, IOException { - AuthenticationToken token = userService.login(login, password, request.getSession().getId()); - if (token == null) { - throw new SecurityException("Invalid credentials"); - } else { + try { UsernamePasswordAuthenticationToken springToken = new UsernamePasswordAuthenticationToken(login, password); springToken.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = this.authenticationProvider.authenticate(springToken); SecurityContextHolder.getContext().setAuthentication(authentication); - sessionRegistry.registerNewSession(request.getSession().getId(), authentication.getPrincipal()); - + + userService.login(login, password, request.getSession().getId()); + Map<String, Object> result = new HashMap<>(); result.put("info", "Login successful. TOKEN returned as a cookie"); return result; + } catch (AuthenticationException e) { + throw new SecurityException("Invalid credentials"); } } diff --git a/rest-api/src/main/java/lcsb/mapviewer/api/users/UserRestImpl.java b/rest-api/src/main/java/lcsb/mapviewer/api/users/UserRestImpl.java index 4b60023f4fce4065c34ad9a81b954bfbda639f80..5044560529757522224586fa0e534709a195bfec 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/users/UserRestImpl.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/users/UserRestImpl.java @@ -30,7 +30,6 @@ import lcsb.mapviewer.model.user.UserClassValidAnnotations; import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.interfaces.IConfigurationService; import lcsb.mapviewer.services.interfaces.ILayoutService; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ConfigurationView; @Transactional(value = "txManager") @@ -137,25 +136,26 @@ public class UserRestImpl extends BaseRestImpl { result.put("annotators-parameters", prepareAnnotatorsParams(schema.getAnnotatorsParams())); return result; } - + /** - * Prepares annotator parameters in the form of a map having annotators - * class names as keys and map of name:value pairs of given annotator as values. + * Prepares annotator parameters in the form of a map having annotators class + * names as keys and map of name:value pairs of given annotator as values. + * * @param annotatorsParams * @return */ private Map<String, Object> prepareAnnotatorsParams(List<UserAnnotatorsParam> annotatorsParams) { - Map<String, Object> result = new HashMap<>(); - for (UserAnnotatorsParam param : annotatorsParams) { - String className = param.getAnnotatorClassName().getName(); - Map<String, String> annotatorParams = (Map<String, String>)result.get(className); - if (annotatorParams == null) { - annotatorParams = new HashMap<>(); - result.put(className, annotatorParams); - } - annotatorParams.put(param.getParamName(), param.getParamValue()); - } - return result; + Map<String, Object> result = new HashMap<>(); + for (UserAnnotatorsParam param : annotatorsParams) { + String className = param.getAnnotatorClassName().getName(); + Map<String, String> annotatorParams = (Map<String, String>) result.get(className); + if (annotatorParams == null) { + annotatorParams = new HashMap<>(); + result.put(className, annotatorParams); + } + annotatorParams.put(param.getParamName(), param.getParamValue()); + } + return result; } private Map<String, Object> prepareValidAnnotations(List<UserClassValidAnnotations> classValidAnnotators) { @@ -185,20 +185,20 @@ public class UserRestImpl extends BaseRestImpl { } } } - - private void updateAnnotatorsParams(UserAnnotationSchema schema, Map<String, Object> data) throws QueryException { - for (String annotatorClassname : data.keySet()) { - Map<String, Object> nameValueS = (Map<String, Object>)data.get(annotatorClassname); - for (String name: nameValueS.keySet()) { - String value = (String)nameValueS.get(name); - try { - UserAnnotatorsParam param = new UserAnnotatorsParam(Class.forName(annotatorClassname), name, value); - schema.addAnnotatorParam(param); - } catch (ClassNotFoundException e) { - throw new QueryException("Unknown annotator class name: " + annotatorClassname); - } - } - } + + private void updateAnnotatorsParams(UserAnnotationSchema schema, Map<String, Object> data) throws QueryException { + for (String annotatorClassname : data.keySet()) { + Map<String, Object> nameValueS = (Map<String, Object>) data.get(annotatorClassname); + for (String name : nameValueS.keySet()) { + String value = (String) nameValueS.get(name); + try { + UserAnnotatorsParam param = new UserAnnotatorsParam(Class.forName(annotatorClassname), name, value); + schema.addAnnotatorParam(param); + } catch (ClassNotFoundException e) { + throw new QueryException("Unknown annotator class name: " + annotatorClassname); + } + } + } } private Map<String, Object> prepareRequiredAnnotations(List<UserClassRequiredAnnotations> classRequiredAnnotators) { @@ -368,14 +368,13 @@ public class UserRestImpl extends BaseRestImpl { } public List<Map<String, Object>> getUsers(String token, String columns) throws SecurityException { - AuthenticationToken authenticationToken = getUserService().getToken(token); User ownUserData = getUserService().getUserByToken(token); boolean isAdmin = getUserService().userHasPrivilege(ownUserData, PrivilegeType.USER_MANAGEMENT); Set<String> columnSet = createUserColumnSet(columns); List<Map<String, Object>> result = new ArrayList<>(); - for (User user : getUserService().getUsers(authenticationToken)) { + for (User user : getUserService().getUsers(token)) { result.add(prepareUse(user, columnSet, isAdmin)); } return result; @@ -387,7 +386,6 @@ public class UserRestImpl extends BaseRestImpl { throw new QueryException("Privileges not defined"); } try { - AuthenticationToken authenticationToken = getUserService().getToken(token); User modifiedUser = getUserService().getUserByLogin(login); for (String key : privilegesData.keySet()) { @@ -396,7 +394,7 @@ public class UserRestImpl extends BaseRestImpl { PrivilegeType type = PrivilegeType.valueOf(key); if (type.getPrivilegeClassType().equals(BasicPrivilege.class)) { - getUserService().setUserPrivilege(modifiedUser, type, value, authenticationToken); + getUserService().setUserPrivilege(modifiedUser, type, value, token); } else if (type.getPrivilegeClassType().equals(ObjectPrivilege.class)) { if (value instanceof Map) { Map<?, ?> objects = (Map<?, ?>) value; @@ -405,8 +403,7 @@ public class UserRestImpl extends BaseRestImpl { if (!objectId.equals("null")) { objectIdAsInteger = Integer.valueOf((String) objectId); } - getUserService().setUserPrivilege(modifiedUser, type, objects.get(objectId), objectIdAsInteger, - authenticationToken); + getUserService().setUserPrivilege(modifiedUser, type, objects.get(objectId), objectIdAsInteger, token); } } else { throw new QueryException("Invalid value for privilege: " + key); @@ -428,7 +425,6 @@ public class UserRestImpl extends BaseRestImpl { throw new QueryException("Preferences not defined"); } try { - AuthenticationToken authenticationToken = getUserService().getToken(token); User modifiedUser = getUserService().getUserByLogin(login); if (modifiedUser == null) { throw new ObjectNotFoundException("User doesn't exist"); @@ -438,7 +434,7 @@ public class UserRestImpl extends BaseRestImpl { for (String key : preferencesData.keySet()) { Map<String, Object> value = (Map<String, Object>) preferencesData.get(key); - + if (key.equals("project-upload")) { updateUploadPreferences(schema, value); } else if (key.equals("element-annotators")) { @@ -447,14 +443,14 @@ public class UserRestImpl extends BaseRestImpl { updateRequiredAnnotations(schema, value); } else if (key.equals("element-valid-annotations")) { updateValidAnnotations(schema, value); - } else if (key.equals("annotators-parameters")) { - updateAnnotatorsParams(schema, value); + } else if (key.equals("annotators-parameters")) { + updateAnnotatorsParams(schema, value); } else { throw new QueryException("Unknown preferences field: " + key); } } modifiedUser.setAnnotationSchema(schema); - getUserService().updateUser(modifiedUser, authenticationToken); + getUserService().updateUser(modifiedUser, token); return getUser(token, login, ""); } catch (IllegalArgumentException e) { throw new QueryException("Invalid input", e); @@ -487,7 +483,6 @@ public class UserRestImpl extends BaseRestImpl { public Map<String, Object> updateUser(String token, String login, Map<String, Object> userData) throws QueryException, SecurityException { - AuthenticationToken authenticationToken = getUserService().getToken(token); if (userData == null) { throw new QueryException("user field cannot be undefined"); } @@ -495,7 +490,7 @@ public class UserRestImpl extends BaseRestImpl { if (user == null) { throw new ObjectNotFoundException("user doesn't exist"); } - boolean isAdmin = getUserService().userHasPrivilege(authenticationToken, PrivilegeType.USER_MANAGEMENT); + boolean isAdmin = getUserService().userHasPrivilege(token, PrivilegeType.USER_MANAGEMENT); if (!isAdmin && !login.equalsIgnoreCase(getUserService().getUserByToken(token).getLogin())) { throw new SecurityException("Access denied"); } @@ -529,8 +524,7 @@ public class UserRestImpl extends BaseRestImpl { public Map<String, Object> addProject(String token, String login, MultiValueMap<String, Object> userData) throws QueryException, SecurityException { - AuthenticationToken authenticationToken = getUserService().getToken(token); - if (!getUserService().userHasPrivilege(authenticationToken, PrivilegeType.USER_MANAGEMENT)) { + if (!getUserService().userHasPrivilege(token, PrivilegeType.USER_MANAGEMENT)) { throw new SecurityException("Access denied"); } @@ -565,9 +559,8 @@ public class UserRestImpl extends BaseRestImpl { } public Map<String, Object> removeUser(String token, String login) throws SecurityException, QueryException { - AuthenticationToken authenticationToken = getUserService().getToken(token); User user = getUserService().getUserByLogin(login); - if (!getUserService().userHasPrivilege(authenticationToken, PrivilegeType.USER_MANAGEMENT)) { + if (!getUserService().userHasPrivilege(token, PrivilegeType.USER_MANAGEMENT)) { throw new SecurityException("Access denied"); } if (user == null) { diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java b/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java index a8ff54bc1afba24c6823953e5d13fdccd88f1d6e..37c0ec02045d5b2fc12481aa2917a9c2c2acd91b 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/RestTestFunctions.java @@ -59,15 +59,15 @@ import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; import lcsb.mapviewer.model.map.model.SubmodelType; import lcsb.mapviewer.persist.DbUtils; import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.view.AuthenticationToken; @Transactional(value = "txManager") @Rollback(true) @ContextConfiguration(locations = { "/applicationContext-persist.xml", // - "/applicationContext-annotation.xml", // - "/applicationContext-service.xml", // - "/applicationContext-rest.xml", // - "/dataSource.xml", // + "/applicationContext-annotation.xml", // + "/applicationContext-service.xml", // + "/applicationContext-rest.xml", // + "/test-applicationContext.xml", // + "/dataSource.xml", // }) @RunWith(SpringJUnit4ClassRunner.class) public abstract class RestTestFunctions { @@ -84,15 +84,15 @@ public abstract class RestTestFunctions { @Autowired protected DbUtils dbUtils; - protected AuthenticationToken token; + protected String token; - protected AuthenticationToken adminToken; + protected String adminToken; @Before public void generalSetUp() { dbUtils.setAutoFlush(false); - token = userService.login(Configuration.ANONYMOUS_LOGIN, null); + token = userService.login(Configuration.ANONYMOUS_LOGIN, ""); // assume that we have admin account with all the privileges adminToken = userService.login("admin", "admin"); diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java index fe90900409938f0ecef9997959c126b825a84572..61a8f65f47bf0fd421af0af04528eb385eb7672f 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/configuration/ConfigurationRestImplTest.java @@ -22,98 +22,98 @@ import lcsb.mapviewer.services.view.ConfigurationView; public class ConfigurationRestImplTest extends RestTestFunctions { - @SuppressWarnings("unused") - private Logger logger = Logger.getLogger(ConfigurationRestImplTest.class); - - @Autowired - public ConfigurationRestImpl configurationRestImpl; - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetAllParams() throws Exception { - try { - List<ConfigurationView> list = configurationRestImpl.getAllValues(token.getId()); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testImageFormats() throws Exception { - try { - List<Map<String, Object>> list = configurationRestImpl.getImageFormats(token.getId()); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testModelFormats() throws Exception { - try { - List<Map<String, Object>> list = configurationRestImpl.getModelFormats(token.getId()); - assertTrue(list.size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetElementTypes() throws Exception { - try { - Set<Map<String, String>> list = configurationRestImpl.getElementTypes(token.getId()); - GenericProtein protein = new GenericProtein("id"); - boolean contains = false; - for (Map<String, String> object : list) { - contains |= (object.get("name").equals(protein.getStringType())); - } - assertTrue(contains); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetReactionTypes() throws Exception { - try { - Set<Map<String, String>> list = configurationRestImpl.getReactionTypes(token.getId()); - StateTransitionReaction reaction = new StateTransitionReaction(); - boolean contains = false; - for (Map<String, String> object : list) { - contains |= (object.get("name").equals(reaction.getStringType())); - } - assertTrue(contains); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetMiriamTypes() throws Exception { - try { - Map<?, ?> list = configurationRestImpl.getMiriamTypes(token.getId()); - assertNotNull(list.get(MiriamType.PUBMED.name())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @SuppressWarnings("unused") + private Logger logger = Logger.getLogger(ConfigurationRestImplTest.class); + + @Autowired + public ConfigurationRestImpl configurationRestImpl; + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetAllParams() throws Exception { + try { + List<ConfigurationView> list = configurationRestImpl.getAllValues(token); + assertTrue(list.size() > 0); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testImageFormats() throws Exception { + try { + List<Map<String, Object>> list = configurationRestImpl.getImageFormats(token); + assertTrue(list.size() > 0); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testModelFormats() throws Exception { + try { + List<Map<String, Object>> list = configurationRestImpl.getModelFormats(token); + assertTrue(list.size() > 0); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetElementTypes() throws Exception { + try { + Set<Map<String, String>> list = configurationRestImpl.getElementTypes(token); + GenericProtein protein = new GenericProtein("id"); + boolean contains = false; + for (Map<String, String> object : list) { + contains |= (object.get("name").equals(protein.getStringType())); + } + assertTrue(contains); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetReactionTypes() throws Exception { + try { + Set<Map<String, String>> list = configurationRestImpl.getReactionTypes(token); + StateTransitionReaction reaction = new StateTransitionReaction(); + boolean contains = false; + for (Map<String, String> object : list) { + contains |= (object.get("name").equals(reaction.getStringType())); + } + assertTrue(contains); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetMiriamTypes() throws Exception { + try { + Map<?, ?> list = configurationRestImpl.getMiriamTypes(token); + assertNotNull(list.get(MiriamType.PUBMED.name())); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/files/FileRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/files/FileRestImplTest.java index 69ef990fdfc1f6cef0698f94e0b37d4e38a48de1..28ad0cf7b0e155f53bd693234641bb23d2ddaca1 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/files/FileRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/files/FileRestImplTest.java @@ -24,12 +24,12 @@ public class FileRestImplTest extends RestTestFunctions { @Test(expected = lcsb.mapviewer.services.SecurityException.class) public void testCreateFileWithoutPrivilege() throws Exception { - fileRestImpl.createFile(token.getId(), "test.txt", "100"); + fileRestImpl.createFile(token, "test.txt", "100"); } @Test public void testCreateFile() throws Exception { - Map<String, Object> result = fileRestImpl.createFile(adminToken.getId(), "test.txt", "100"); + Map<String, Object> result = fileRestImpl.createFile(adminToken, "test.txt", "100"); assertNotNull(result); int id = (Integer) result.get("id"); UploadedFileEntry file = uploadedFileEntryDao.getById(id); @@ -44,16 +44,16 @@ public class FileRestImplTest extends RestTestFunctions { byte[] dataChunk = new byte[] { 105, 103 }; byte[] dataChunk2 = new byte[] { 32, 73 }; byte[] dataChunkMerged = ArrayUtils.addAll(dataChunk, dataChunk2); - Map<String, Object> result = fileRestImpl.createFile(adminToken.getId(), "test.txt", "100"); + Map<String, Object> result = fileRestImpl.createFile(adminToken, "test.txt", "100"); int id = (Integer) result.get("id"); - fileRestImpl.uploadContent(adminToken.getId(), id + "", dataChunk); + fileRestImpl.uploadContent(adminToken, id + "", dataChunk); UploadedFileEntry file = uploadedFileEntryDao.getById(id); assertEquals(100, file.getLength()); assertEquals(2, file.getFileContent().length); assertArrayEquals(dataChunk, file.getFileContent()); - fileRestImpl.uploadContent(adminToken.getId(), id + "", dataChunk2); + fileRestImpl.uploadContent(adminToken, id + "", dataChunk2); assertEquals(100, file.getLength()); assertEquals(4, file.getFileContent().length); @@ -65,11 +65,11 @@ public class FileRestImplTest extends RestTestFunctions { @Test public void testUploadInvalidContent() throws Exception { byte[] dataChunk = new byte[100]; - Map<String, Object> result = fileRestImpl.createFile(adminToken.getId(), "test.txt", "100"); + Map<String, Object> result = fileRestImpl.createFile(adminToken, "test.txt", "100"); int id = (Integer) result.get("id"); try { - fileRestImpl.uploadContent(adminToken.getId(), id + "", dataChunk); + fileRestImpl.uploadContent(adminToken, id + "", dataChunk); } finally { uploadedFileEntryDao.getById(id); UploadedFileEntry file = uploadedFileEntryDao.getById(id); diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java index b1a2c84e9b467b750f25e6bcb8390f72e4d38d41..cc820e078009074692d9783239bfe63a569af60a 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/genomics/ReferenceGenomeControllerTest.java @@ -14,47 +14,47 @@ import lcsb.mapviewer.api.QueryException; import lcsb.mapviewer.api.RestTestFunctions; public class ReferenceGenomeControllerTest extends RestTestFunctions { - Logger logger = Logger.getLogger(ReferenceGenomeControllerTest.class); - - @Autowired - public ReferenceGenomeRestImpl referenceGenomeRestImpl; - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetForNonExistingType() throws Exception { - try { - referenceGenomeRestImpl.getReferenceGenome(token.getId(), "9606", "type", "ver"); - fail("Exception expected"); - } catch (QueryException e2) { - assertTrue(e2.getMessage().contains("Cannot find type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetForNonExistingOrganism() throws Exception { - try { - referenceGenomeRestImpl.getReferenceGenome(token.getId(), "960000", "UCSC", "ver"); - fail("Exception expected"); - } catch (QueryException e2) { - assertTrue(e2.getMessage().contains("Cannot find requested reference genome")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + Logger logger = Logger.getLogger(ReferenceGenomeControllerTest.class); + + @Autowired + public ReferenceGenomeRestImpl referenceGenomeRestImpl; + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetForNonExistingType() throws Exception { + try { + referenceGenomeRestImpl.getReferenceGenome(token, "9606", "type", "ver"); + fail("Exception expected"); + } catch (QueryException e2) { + assertTrue(e2.getMessage().contains("Cannot find type")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetForNonExistingOrganism() throws Exception { + try { + referenceGenomeRestImpl.getReferenceGenome(token, "960000", "UCSC", "ver"); + fail("Exception expected"); + } catch (QueryException e2) { + assertTrue(e2.getMessage().contains("Cannot find requested reference genome")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/mesh/MeshRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/mesh/MeshRestImplTest.java index 93e6211849e467387830251cf12dac5e0343ed25..dcc0aabb4cac149edc49e3e4fd714c939331b008 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/mesh/MeshRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/mesh/MeshRestImplTest.java @@ -1,6 +1,7 @@ package lcsb.mapviewer.api.mesh; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.Map; @@ -20,9 +21,9 @@ public class MeshRestImplTest extends RestTestFunctions { @Test public void test() throws ObjectNotFoundException, AnnotatorException { - Map<String, Object> result = meshRestImpl.getMesh(token.getId(), "D010300"); + Map<String, Object> result = meshRestImpl.getMesh(token, "D010300"); assertNotNull(result); - String name =(String) result.get("name"); + String name = (String) result.get("name"); assertTrue(name.toLowerCase().contains("parkinson")); } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java index 074b22ed0a0e2d07e93c18b83aa4e126be46b14f..872eec22049face74dd5dd2d78263a4b79e73144 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/ProjectRestImplTest.java @@ -75,7 +75,7 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetModelAsImageForInvalidConverter() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - projectRest.getModelAsImage(token.getId(), "sample", "0", "", "", "", "", ""); + projectRest.getModelAsImage(token, "sample", "0", "", "", "", "", ""); fail("Exception expected"); } catch (InvalidArgumentException e) { } catch (Exception e) { @@ -88,8 +88,8 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetModelAsImage() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - FileEntry result = projectRest.getModelAsImage(token.getId(), "sample", "0", - PdfImageGenerator.class.getCanonicalName(), "", "", "", ""); + FileEntry result = projectRest.getModelAsImage(token, "sample", "0", PdfImageGenerator.class.getCanonicalName(), + "", "", "", ""); assertNotNull(result); } catch (Exception e) { e.printStackTrace(); @@ -101,7 +101,7 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetModelDataDependencies() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - ProjectMetaData result = projectRest.getProject("sample", token.getId()); + ProjectMetaData result = projectRest.getProject("sample", token); Gson gson = new Gson(); assertNotNull(gson.toJson(result)); Mockito.verify(projectRest.getModelService(), times(0)).getLastModelByProjectId(anyString(), any()); @@ -114,15 +114,14 @@ public class ProjectRestImplTest extends RestTestFunctions { @Test(expected = ObjectNotFoundException.class) public void testGetInvalidMetaData() throws Exception { ProjectRestImpl projectRest = createMockProjectRest(null); - projectRest.getProject("unknown_model_id", token.getId()); + projectRest.getProject("unknown_model_id", token); } @Test public void testGetModelAsImage2() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - projectRest.getModelAsImage(token.getId(), "sample", "0", PdfImageGenerator.class.getCanonicalName(), "", "", "", - ""); + projectRest.getModelAsImage(token, "sample", "0", PdfImageGenerator.class.getCanonicalName(), "", "", "", ""); } catch (Exception e) { e.printStackTrace(); throw e; @@ -133,7 +132,7 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetModelAsFileModel() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - projectRest.getModelAsModelFile(token.getId(), "sample", "0", "", "", "", "", ""); + projectRest.getModelAsModelFile(token, "sample", "0", "", "", "", "", ""); fail("Exception expected"); } catch (QueryException e) { } catch (Exception e) { @@ -146,8 +145,8 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetModelAsFileModel2() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - projectRest.getModelAsModelFile(token.getId(), "sample", "0", CellDesignerXmlParser.class.getCanonicalName(), "", - "", "", "0,0;90,0;90,90;90,0"); + projectRest.getModelAsModelFile(token, "sample", "0", CellDesignerXmlParser.class.getCanonicalName(), "", "", "", + "0,0;90,0;90,90;90,0"); } catch (Exception e) { e.printStackTrace(); throw e; @@ -158,7 +157,7 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetModelAsFileModel3() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - projectRest.getModelAsModelFile(token.getId(), "sample", "0", "", "", "", "", "0,0;90,0;90,90;90,0"); + projectRest.getModelAsModelFile(token, "sample", "0", "", "", "", "", "0,0;90,0;90,90;90,0"); fail("Exception expected"); } catch (QueryException e) { } catch (Exception e) { @@ -171,7 +170,7 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetProject() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - ProjectMetaData result = projectRest.getProject("sample", token.getId()); + ProjectMetaData result = projectRest.getProject("sample", token); Gson gson = new Gson(); assertNotNull(gson.toJson(result)); } catch (Exception e) { @@ -194,7 +193,7 @@ public class ProjectRestImplTest extends RestTestFunctions { data.put("disease", disease); data.put("projectId", "sample"); data.put("id", "0"); - projectRest.updateProject(adminToken.getId(), "sample", data); + projectRest.updateProject(adminToken, "sample", data); } catch (Exception e) { e.printStackTrace(); throw e; @@ -224,7 +223,7 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetProjects() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - List<ProjectMetaData> result = projectRest.getProjects(token.getId()); + List<ProjectMetaData> result = projectRest.getProjects(token); Gson gson = new Gson(); assertNotNull(gson.toJson(result)); } catch (Exception e) { @@ -237,7 +236,7 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetStatistics() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getStatistics("sample", token.getId()); + Map<String, Object> result = projectRest.getStatistics("sample", token); Gson gson = new Gson(); assertNotNull(gson.toJson(result)); @@ -259,7 +258,7 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetMetaDataForComplexWithImages() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/complex_model_with_submaps.zip"); - ProjectMetaData result = projectRest.getProject("sample", token.getId()); + ProjectMetaData result = projectRest.getProject("sample", token); Gson gson = new Gson(); assertNotNull(gson.toJson(result)); } catch (Exception e) { @@ -331,7 +330,7 @@ public class ProjectRestImplTest extends RestTestFunctions { public void testGetLogs() throws Exception { try { ProjectRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getLogs("sample", "", token.getId(), "0", 10, "id", "asc", ""); + Map<String, Object> result = projectRest.getLogs("sample", "", token, "0", 10, "id", "asc", ""); assertNotNull(result); Gson gson = new Gson(); assertNotNull(gson.toJson(result)); diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java index 58213ce5c9cff44adc2e93f05a1952bd0fabf389..75b9c48eb49fac8bf7e0760b3af5b8996c97add2 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/comments/CommentRestImplTest.java @@ -26,68 +26,68 @@ import lcsb.mapviewer.services.interfaces.IProjectService; public class CommentRestImplTest extends RestTestFunctions { - @Autowired - public CommentRestImpl _commentRestImpl; + @Autowired + public CommentRestImpl _commentRestImpl; - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testGetForNonExisting() throws Exception { - try { - _commentRestImpl.getCommentList(token.getId(), "unk", "", "", "", ""); - fail("Exception expected"); - } catch (QueryException e2) { - assertTrue(e2.getMessage().contains("Project with given id doesn't exist")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testGetForNonExisting() throws Exception { + try { + _commentRestImpl.getCommentList(token, "unk", "", "", "", ""); + fail("Exception expected"); + } catch (QueryException e2) { + assertTrue(e2.getMessage().contains("Project with given id doesn't exist")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } - @Test - public void testGetCommentsDependencies() throws Exception { - try { - CommentRestImpl commentRestImpl = createMockProjectRest("testFiles/model/sample.xml"); - commentRestImpl.getCommentList(adminToken.getId(), "sample", "", "", "", ""); - Mockito.verify(commentRestImpl.getModelService(), times(0)).getLastModelByProjectId(anyString(), any()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testGetCommentsDependencies() throws Exception { + try { + CommentRestImpl commentRestImpl = createMockProjectRest("testFiles/model/sample.xml"); + commentRestImpl.getCommentList(adminToken, "sample", "", "", "", ""); + Mockito.verify(commentRestImpl.getModelService(), times(0)).getLastModelByProjectId(anyString(), any()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } - private CommentRestImpl createMockProjectRest(String string) throws Exception { - Model model = null; - Project project = null; - String modelName = ""; - if (string != null) { - project = new Project(); - model = super.getModelForFile(string, true); - project.addModel(model); - modelName = model.getName(); - } - IModelService mockModelService = Mockito.mock(IModelService.class); - Mockito.when(mockModelService.getLastModelByProjectId(eq(modelName), any())).thenReturn(model); - _commentRestImpl.setModelService(mockModelService); + private CommentRestImpl createMockProjectRest(String string) throws Exception { + Model model = null; + Project project = null; + String modelName = ""; + if (string != null) { + project = new Project(); + model = super.getModelForFile(string, true); + project.addModel(model); + modelName = model.getName(); + } + IModelService mockModelService = Mockito.mock(IModelService.class); + Mockito.when(mockModelService.getLastModelByProjectId(eq(modelName), any())).thenReturn(model); + _commentRestImpl.setModelService(mockModelService); - IProjectService projectServiceMock = Mockito.mock(IProjectService.class); - Mockito.when(projectServiceMock.getProjectByProjectId(eq(modelName), any())).thenReturn(project); - List<Project> projects = new ArrayList<>(); - projects.add(project); - Mockito.when(projectServiceMock.getAllProjects(any())).thenReturn(projects); - _commentRestImpl.setProjectService(projectServiceMock); + IProjectService projectServiceMock = Mockito.mock(IProjectService.class); + Mockito.when(projectServiceMock.getProjectByProjectId(eq(modelName), any())).thenReturn(project); + List<Project> projects = new ArrayList<>(); + projects.add(project); + Mockito.when(projectServiceMock.getAllProjects(any())).thenReturn(projects); + _commentRestImpl.setProjectService(projectServiceMock); - return _commentRestImpl; - } + return _commentRestImpl; + } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java index 880479f85b67aba56a6e8497d0967e9453089d1d..89e6026906bae288de75b8592cb26850ce9b6a03 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/drugs/DrugRestImplTest.java @@ -20,46 +20,46 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.services.interfaces.IModelService; public class DrugRestImplTest extends RestTestFunctions { - Logger logger = Logger.getLogger(DrugRestImplTest.class); + Logger logger = Logger.getLogger(DrugRestImplTest.class); - @Autowired + @Autowired - private DrugRestImpl _drugRestImpl; + private DrugRestImpl _drugRestImpl; - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - @SuppressWarnings("unchecked") - public void testGetDrugsByQuery() throws Exception { - try { - DrugRestImpl drugRestImpl = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = drugRestImpl.getDrugsByQuery(token.getId(), "sample", "", "nadh").get(0); - List<Map<String, Object>> references = (List<Map<String, Object>>) result.get("references"); - Map<String, Object> reference = references.get(0); - assertNotNull(reference.get("type")); + @Test + @SuppressWarnings("unchecked") + public void testGetDrugsByQuery() throws Exception { + try { + DrugRestImpl drugRestImpl = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = drugRestImpl.getDrugsByQuery(token, "sample", "", "nadh").get(0); + List<Map<String, Object>> references = (List<Map<String, Object>>) result.get("references"); + Map<String, Object> reference = references.get(0); + assertNotNull(reference.get("type")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } - private DrugRestImpl createMockProjectRest(String string) throws Exception { - Model model = super.getModelForFile(string, true); - IModelService mockModelService = Mockito.mock(IModelService.class); - Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); - _drugRestImpl.setModelService(mockModelService); - return _drugRestImpl; - } + private DrugRestImpl createMockProjectRest(String string) throws Exception { + Model model = super.getModelForFile(string, true); + IModelService mockModelService = Mockito.mock(IModelService.class); + Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); + _drugRestImpl.setModelService(mockModelService); + return _drugRestImpl; + } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java index fb9da16bb839051db9619b5f3242fe6f008a78d7..25456e10a7a726ce6e63d246472cce55feb8eb41 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/mirnas/MiRnaRestImplTest.java @@ -22,46 +22,47 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.services.interfaces.IModelService; public class MiRnaRestImplTest extends RestTestFunctions { - Logger logger = Logger.getLogger(MiRnaRestImplTest.class); + Logger logger = Logger.getLogger(MiRnaRestImplTest.class); - @Autowired - MiRnaRestImpl _miRnaRestImpl; + @Autowired + MiRnaRestImpl _miRnaRestImpl; - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testGetMiRnasByTarget() throws Exception { - try { - MiRnaRestImpl miRnaRestImpl = createMockProjectRest("testFiles/model/mi_rna_target.xml"); - List<Map<String, Object>> result = miRnaRestImpl.getMiRnasByTarget(token.getId(), "mi_rna_target", "ALIAS", "0", ""); - Set<String> names = new HashSet<>(); - for (Map<String, Object> miRna : result) { - assertFalse("Duplicate miRna found: " + miRna.get("name"), names.contains(miRna.get("name"))); - names.add((String)miRna.get("name")); - } + @Test + public void testGetMiRnasByTarget() throws Exception { + try { + MiRnaRestImpl miRnaRestImpl = createMockProjectRest("testFiles/model/mi_rna_target.xml"); + List<Map<String, Object>> result = miRnaRestImpl.getMiRnasByTarget(token, "mi_rna_target", "ALIAS", "0", + ""); + Set<String> names = new HashSet<>(); + for (Map<String, Object> miRna : result) { + assertFalse("Duplicate miRna found: " + miRna.get("name"), names.contains(miRna.get("name"))); + names.add((String) miRna.get("name")); + } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } - private MiRnaRestImpl createMockProjectRest(String string) throws Exception { - Model model = super.getModelForFile(string, true); - IModelService mockModelService = Mockito.mock(IModelService.class); - Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); - _miRnaRestImpl.setModelService(mockModelService); - return _miRnaRestImpl; - } + private MiRnaRestImpl createMockProjectRest(String string) throws Exception { + Model model = super.getModelForFile(string, true); + IModelService mockModelService = Mockito.mock(IModelService.class); + Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); + _miRnaRestImpl.setModelService(mockModelService); + return _miRnaRestImpl; + } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java index 658733631c3cc430d40f9f1f0e4b43ba0539c3ab..0b7b40b3abb5c454973195b69f647d73fab0bcde 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/ModelRestImplTest.java @@ -8,27 +8,33 @@ import static org.mockito.Matchers.refEq; import java.util.List; import org.junit.After; -import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.api.RestTestFunctions; +import lcsb.mapviewer.common.exception.InvalidArgumentException; +import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.services.interfaces.IModelService; +import lcsb.mapviewer.services.interfaces.IProjectService; public class ModelRestImplTest extends RestTestFunctions { @Autowired - ModelRestImpl _projectRestImpl; + ModelRestImpl _modelRestImpl; - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @Autowired + IModelService modelService; + + @Autowired + IProjectService projectService; @Before public void setUp() throws Exception { + _modelRestImpl.setModelService(modelService); + _modelRestImpl.setProjectService(projectService); } @After @@ -39,19 +45,19 @@ public class ModelRestImplTest extends RestTestFunctions { public void testModels() throws Exception { try { ModelRestImpl modelRest = createMockProjectRest("testFiles/model/sample.xml"); - List<ModelMetaData> result = modelRest.getModels("sample", token.getId()); + List<ModelMetaData> result = modelRest.getModels("sample", token); assertEquals(1, result.size()); } catch (Exception e) { e.printStackTrace(); throw e; } } - + @Test public void testGetEmptyModels() throws Exception { try { ModelRestImpl modelRest = createEmptyProjectRest("test"); - List<ModelMetaData> result = modelRest.getModels("test", token.getId()); + List<ModelMetaData> result = modelRest.getModels("test", token); assertEquals(0, result.size()); } catch (Exception e) { e.printStackTrace(); @@ -59,19 +65,24 @@ public class ModelRestImplTest extends RestTestFunctions { } } - private ModelRestImpl createEmptyProjectRest(String string) { + private ModelRestImpl createEmptyProjectRest(String string) throws Exception { IModelService mockModelService = Mockito.mock(IModelService.class); Mockito.when(mockModelService.getLastModelByProjectId(refEq(string), any())).thenReturn(null); - _projectRestImpl.setModelService(mockModelService); - return _projectRestImpl; + + IProjectService mockProjectService = Mockito.mock(IProjectService.class); + Mockito.when(mockProjectService.getProjectByProjectId(refEq(string), any())).thenReturn(new Project()); + + _modelRestImpl.setModelService(mockModelService); + _modelRestImpl.setProjectService(mockProjectService); + return _modelRestImpl; } private ModelRestImpl createMockProjectRest(String string) throws Exception { Model model = super.getModelForFile(string, true); IModelService mockModelService = Mockito.mock(IModelService.class); Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); - _projectRestImpl.setModelService(mockModelService); - return _projectRestImpl; + _modelRestImpl.setModelService(mockModelService); + return _modelRestImpl; } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java index 50bec236b39243a7a2ca3bfcad34e76447051193..04822ae7148dd5342655ce8bc49f88443a64fa0f 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/BioEntitiesControllerTest.java @@ -24,47 +24,48 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.services.interfaces.IModelService; public class BioEntitiesControllerTest extends RestTestFunctions { - Logger logger = Logger.getLogger(BioEntitiesControllerTest.class); + Logger logger = Logger.getLogger(BioEntitiesControllerTest.class); - @Autowired - BioEntitiesRestImpl _bioEntitiesRestImpl; + @Autowired + BioEntitiesRestImpl _bioEntitiesRestImpl; - ObjectMapper mapper = new ObjectMapper(); + ObjectMapper mapper = new ObjectMapper(); - @AfterClass - public static void tearDownAfterClass() throws Exception { - } + @AfterClass + public static void tearDownAfterClass() throws Exception { + } - @Before - public void setUp() throws Exception { - } + @Before + public void setUp() throws Exception { + } - @After - public void tearDown() throws Exception { - } + @After + public void tearDown() throws Exception { + } - @Test - public void testGetClosestElementsByCoordinates() throws Exception { - try { - BioEntitiesRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - int count = 3; - List<Map<String, Object>> result = projectRest.getClosestElementsByCoordinates("sample", "0", token.getId(), new Point2D.Double(1, 2), count, "false"); - assertEquals(count, result.size()); - - String json = mapper.writeValueAsString(result); - assertNotNull(json); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + @Test + public void testGetClosestElementsByCoordinates() throws Exception { + try { + BioEntitiesRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + int count = 3; + List<Map<String, Object>> result = projectRest.getClosestElementsByCoordinates("sample", "0", token, + new Point2D.Double(1, 2), count, "false"); + assertEquals(count, result.size()); - private BioEntitiesRestImpl createMockProjectRest(String string) throws Exception { - Model model = super.getModelForFile(string, true); - IModelService mockModelService = Mockito.mock(IModelService.class); - Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); - _bioEntitiesRestImpl.setModelService(mockModelService); - return _bioEntitiesRestImpl; - } + String json = mapper.writeValueAsString(result); + assertNotNull(json); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + private BioEntitiesRestImpl createMockProjectRest(String string) throws Exception { + Model model = super.getModelForFile(string, true); + IModelService mockModelService = Mockito.mock(IModelService.class); + Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); + _bioEntitiesRestImpl.setModelService(mockModelService); + return _bioEntitiesRestImpl; + } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java index 5e9ac8b9f8f0e4e1e4a24acb50d8d0e0ba538c7d..a5a06edbcebc117f303da8876033620b17043439 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/bioEntities/elements/ElementRestImplTest.java @@ -34,165 +34,165 @@ import lcsb.mapviewer.model.map.species.field.RnaRegion; import lcsb.mapviewer.services.interfaces.IModelService; public class ElementRestImplTest extends RestTestFunctions { - Logger logger = Logger.getLogger(RestTestFunctions.class); - - @Autowired - ElementsRestImpl _elementsRestImpl; - - @Autowired - PdbAnnotator pdbAnnotator; - - ObjectMapper mapper = new ObjectMapper(); - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetElementsProcessAllColumns() throws Exception { - try { - ElementsRestImpl projectRest = createMockElementRest("testFiles/model/sample.xml", true); - List<Map<String, Object>> result = projectRest.getElements("sample", "", "", "*", token.getId(), "", "", ""); - for (Map<String, Object> element : result) { - for (String paramName : element.keySet()) { - Object val = element.get(paramName); - String paramValue = ""; - if (val != null) { - paramValue = val.toString(); - } - assertFalse("Improper handler for column name: " + paramName, paramValue.contains("Unknown column")); - } - } - String json = mapper.writeValueAsString(result); - assertNotNull(json); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetElementsByType() throws Exception { - try { - String proteinType = new GenericProtein("1").getStringType(); - ElementsRestImpl projectRest = createMockElementRest("testFiles/model/sample.xml", false); - List<Map<String, Object>> result = projectRest.getElements("sample", "", "", "*", token.getId(), proteinType, "", ""); - assertEquals(12, result.size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetElementsVisibility() throws Exception { - try { - ElementsRestImpl elementRest = createMockElementRest("testFiles/model/sample.xml"); - List<Map<String, Object>> result = elementRest.getElements("sample", "", "", "*", token.getId(), "", "", ""); - for (Map<String, Object> map : result) { - assertTrue(map.get("hierarchyVisibilityLevel") instanceof String); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @SuppressWarnings("unchecked") - @Test - public void testGetModificationsForProtein() throws Exception { - try { - String state = "asd"; - GenericProtein protein = new GenericProtein("s1"); - ModificationResidue mr = new ModificationResidue(); - mr.setState(ModificationState.ACETYLATED); - mr.setName("S250"); - protein.addModificationResidue(mr); - protein.setStructuralState(state); - Map<String, Object> result = _elementsRestImpl.getOthersForElement(protein); - assertNotNull(result.get("modifications")); - assertEquals(state, result.get("structuralState")); - List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); - assertEquals(1, modifications.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @SuppressWarnings("unchecked") - @Test - public void testGetModificationsForRna() throws Exception { - try { - String state = "asd"; - Rna rna = new Rna("s1"); - RnaRegion mr = new RnaRegion(); - mr.setState(ModificationState.ACETYLATED); - mr.setName("S250"); - rna.addRegion(mr); - rna.setState(state); - Map<String, Object> result = _elementsRestImpl.getOthersForElement(rna); - assertNotNull(result.get("modifications")); - assertEquals(state, result.get("structuralState")); - List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); - assertEquals(1, modifications.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @SuppressWarnings("unchecked") - @Test - public void testGetModificationsForAntisenseRna() throws Exception { - try { - String state = "asd"; - AntisenseRna antisenseRna = new AntisenseRna("s1"); - AntisenseRnaRegion mr = new AntisenseRnaRegion(); - mr.setState(ModificationState.ACETYLATED); - mr.setName("S250"); - antisenseRna.addRegion(mr); - antisenseRna.setState(state); - Map<String, Object> result = _elementsRestImpl.getOthersForElement(antisenseRna); - assertNotNull(result.get("modifications")); - assertEquals(state, result.get("structuralState")); - List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); - assertEquals(1, modifications.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - private ElementsRestImpl createMockElementRest(String string) throws Exception { - return createMockElementRest(string, false); - } - - private ElementsRestImpl createMockElementRest(String string, Boolean annotate) throws Exception { - Model model = super.getModelForFile(string, true); - if (annotate) { - try { - Protein protein = new GenericProtein("SNCA"); - protein.setElementId("SNCA"); - pdbAnnotator.annotateElement(protein); - model.addElement(protein); - } catch (Exception e) { - } - } - IModelService mockModelService = Mockito.mock(IModelService.class); - Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); - _elementsRestImpl.setModelService(mockModelService); - return _elementsRestImpl; - } + Logger logger = Logger.getLogger(RestTestFunctions.class); + + @Autowired + ElementsRestImpl _elementsRestImpl; + + @Autowired + PdbAnnotator pdbAnnotator; + + ObjectMapper mapper = new ObjectMapper(); + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetElementsProcessAllColumns() throws Exception { + try { + ElementsRestImpl projectRest = createMockElementRest("testFiles/model/sample.xml", true); + List<Map<String, Object>> result = projectRest.getElements("sample", "", "", "*", token, "", "", ""); + for (Map<String, Object> element : result) { + for (String paramName : element.keySet()) { + Object val = element.get(paramName); + String paramValue = ""; + if (val != null) { + paramValue = val.toString(); + } + assertFalse("Improper handler for column name: " + paramName, paramValue.contains("Unknown column")); + } + } + String json = mapper.writeValueAsString(result); + assertNotNull(json); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetElementsByType() throws Exception { + try { + String proteinType = new GenericProtein("1").getStringType(); + ElementsRestImpl projectRest = createMockElementRest("testFiles/model/sample.xml", false); + List<Map<String, Object>> result = projectRest.getElements("sample", "", "", "*", token, proteinType, "", ""); + assertEquals(12, result.size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetElementsVisibility() throws Exception { + try { + ElementsRestImpl elementRest = createMockElementRest("testFiles/model/sample.xml"); + List<Map<String, Object>> result = elementRest.getElements("sample", "", "", "*", token, "", "", ""); + for (Map<String, Object> map : result) { + assertTrue(map.get("hierarchyVisibilityLevel") instanceof String); + } + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @SuppressWarnings("unchecked") + @Test + public void testGetModificationsForProtein() throws Exception { + try { + String state = "asd"; + GenericProtein protein = new GenericProtein("s1"); + ModificationResidue mr = new ModificationResidue(); + mr.setState(ModificationState.ACETYLATED); + mr.setName("S250"); + protein.addModificationResidue(mr); + protein.setStructuralState(state); + Map<String, Object> result = _elementsRestImpl.getOthersForElement(protein); + assertNotNull(result.get("modifications")); + assertEquals(state, result.get("structuralState")); + List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); + assertEquals(1, modifications.size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @SuppressWarnings("unchecked") + @Test + public void testGetModificationsForRna() throws Exception { + try { + String state = "asd"; + Rna rna = new Rna("s1"); + RnaRegion mr = new RnaRegion(); + mr.setState(ModificationState.ACETYLATED); + mr.setName("S250"); + rna.addRegion(mr); + rna.setState(state); + Map<String, Object> result = _elementsRestImpl.getOthersForElement(rna); + assertNotNull(result.get("modifications")); + assertEquals(state, result.get("structuralState")); + List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); + assertEquals(1, modifications.size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @SuppressWarnings("unchecked") + @Test + public void testGetModificationsForAntisenseRna() throws Exception { + try { + String state = "asd"; + AntisenseRna antisenseRna = new AntisenseRna("s1"); + AntisenseRnaRegion mr = new AntisenseRnaRegion(); + mr.setState(ModificationState.ACETYLATED); + mr.setName("S250"); + antisenseRna.addRegion(mr); + antisenseRna.setState(state); + Map<String, Object> result = _elementsRestImpl.getOthersForElement(antisenseRna); + assertNotNull(result.get("modifications")); + assertEquals(state, result.get("structuralState")); + List<Map<String, Object>> modifications = (List<Map<String, Object>>) result.get("modifications"); + assertEquals(1, modifications.size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + private ElementsRestImpl createMockElementRest(String string) throws Exception { + return createMockElementRest(string, false); + } + + private ElementsRestImpl createMockElementRest(String string, Boolean annotate) throws Exception { + Model model = super.getModelForFile(string, true); + if (annotate) { + try { + Protein protein = new GenericProtein("SNCA"); + protein.setElementId("SNCA"); + pdbAnnotator.annotateElement(protein); + model.addElement(protein); + } catch (Exception e) { + } + } + IModelService mockModelService = Mockito.mock(IModelService.class); + Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); + _elementsRestImpl.setModelService(mockModelService); + return _elementsRestImpl; + } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java index 551214008055f3656e88524ddf4c7bf85eb18914..3aee7fc3105936353401d1d021d8e9ae44d8616c 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/projects/models/publications/PublicationsRestImplTest.java @@ -22,85 +22,85 @@ import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.services.interfaces.IModelService; public class PublicationsRestImplTest extends RestTestFunctions { - Logger logger = Logger.getLogger(PublicationsRestImplTest.class); - - @Autowired - PublicationsRestImpl _projectRestImpl; - - @AfterClass - public static void tearDownAfterClass() throws Exception { - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testPublications() throws Exception { - try { - PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getPublications("sample", "*", token.getId(), "0", 20, "", "", ""); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertEquals(1, ((List<?>) result.get("data")).size()); - - result = projectRest.getPublications("sample", "*", token.getId(), "1", 20, "", "", ""); - assertEquals(1, result.get("totalSize")); - assertEquals(1, result.get("start")); - assertEquals(0, ((List<?>) result.get("data")).size()); - - result = projectRest.getPublications("sample", "*", token.getId(), "0", 00, "", "", ""); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertEquals(0, ((List<?>) result.get("data")).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testPublicationsFiltering() throws Exception { - try { - PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - Map<String, Object> result = projectRest.getPublications("sample", "*", token.getId(), "0", 20, "pubmedId", "asc", "123"); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertEquals(1, ((List<?>) result.get("data")).size()); - - result = projectRest.getPublications("sample", "*", token.getId(), "0", 20, "pubmedId", "asc", "1234"); - assertEquals(1, result.get("totalSize")); - assertEquals(0, result.get("start")); - assertEquals(0, ((List<?>) result.get("data")).size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testPublicationsInvalidSortingFiltering() throws Exception { - try { - PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); - projectRest.getPublications("sample", "*", token.getId(), "0", 20, "xxx", "asc", "123"); - fail("Exception expected"); - } catch (QueryException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - private PublicationsRestImpl createMockProjectRest(String string) throws Exception { - Model model = super.getModelForFile(string, true); - IModelService mockModelService = Mockito.mock(IModelService.class); - Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); - _projectRestImpl.setModelService(mockModelService); - return _projectRestImpl; - } + Logger logger = Logger.getLogger(PublicationsRestImplTest.class); + + @Autowired + PublicationsRestImpl _projectRestImpl; + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testPublications() throws Exception { + try { + PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = projectRest.getPublications("sample", "*", token, "0", 20, "", "", ""); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertEquals(1, ((List<?>) result.get("data")).size()); + + result = projectRest.getPublications("sample", "*", token, "1", 20, "", "", ""); + assertEquals(1, result.get("totalSize")); + assertEquals(1, result.get("start")); + assertEquals(0, ((List<?>) result.get("data")).size()); + + result = projectRest.getPublications("sample", "*", token, "0", 00, "", "", ""); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertEquals(0, ((List<?>) result.get("data")).size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testPublicationsFiltering() throws Exception { + try { + PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + Map<String, Object> result = projectRest.getPublications("sample", "*", token, "0", 20, "pubmedId", "asc", "123"); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertEquals(1, ((List<?>) result.get("data")).size()); + + result = projectRest.getPublications("sample", "*", token, "0", 20, "pubmedId", "asc", "1234"); + assertEquals(1, result.get("totalSize")); + assertEquals(0, result.get("start")); + assertEquals(0, ((List<?>) result.get("data")).size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testPublicationsInvalidSortingFiltering() throws Exception { + try { + PublicationsRestImpl projectRest = createMockProjectRest("testFiles/model/sample.xml"); + projectRest.getPublications("sample", "*", token, "0", 20, "xxx", "asc", "123"); + fail("Exception expected"); + } catch (QueryException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + private PublicationsRestImpl createMockProjectRest(String string) throws Exception { + Model model = super.getModelForFile(string, true); + IModelService mockModelService = Mockito.mock(IModelService.class); + Mockito.when(mockModelService.getLastModelByProjectId(anyString(), any())).thenReturn(model); + _projectRestImpl.setModelService(mockModelService); + return _projectRestImpl; + } } diff --git a/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java b/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java index 07d064945bcb49597c5b02b0f4e7bb11546163e7..dff753719ffc90d4760a1e1b7a5c1a5e31b9fd0d 100644 --- a/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java +++ b/rest-api/src/test/java/lcsb/mapviewer/api/users/UserRestImplTest.java @@ -46,7 +46,7 @@ public class UserRestImplTest extends RestTestFunctions { @Test public void testGetUser() throws Exception { try { - Object response = userRestImpl.getUser(token.getId(), Configuration.ANONYMOUS_LOGIN, ""); + Object response = userRestImpl.getUser(token, Configuration.ANONYMOUS_LOGIN, ""); assertNotNull(response); } catch (Exception e) { e.printStackTrace(); @@ -59,12 +59,12 @@ public class UserRestImplTest extends RestTestFunctions { try { Map<String, Object> data = new HashMap<>(); data.put(PrivilegeType.ADD_MAP.name(), 1); - userRestImpl.updatePrivileges(adminToken.getId(), Configuration.ANONYMOUS_LOGIN, data); + userRestImpl.updatePrivileges(adminToken, Configuration.ANONYMOUS_LOGIN, data); assertTrue(userService.userHasPrivilege(userService.getUserByLogin(Configuration.ANONYMOUS_LOGIN), PrivilegeType.ADD_MAP)); data.put(PrivilegeType.ADD_MAP.name(), 0); - userRestImpl.updatePrivileges(adminToken.getId(), Configuration.ANONYMOUS_LOGIN, data); + userRestImpl.updatePrivileges(adminToken, Configuration.ANONYMOUS_LOGIN, data); assertFalse(userService.userHasPrivilege(userService.getUserByLogin(Configuration.ANONYMOUS_LOGIN), PrivilegeType.ADD_MAP)); @@ -77,9 +77,8 @@ public class UserRestImplTest extends RestTestFunctions { @Test public void testUpdatePreferences() throws Exception { try { - Map<String, Object> data = deserialize( - userRestImpl.getUser(adminToken.getId(), Configuration.ANONYMOUS_LOGIN, "")); - userRestImpl.updatePreferences(adminToken.getId(), Configuration.ANONYMOUS_LOGIN, + Map<String, Object> data = deserialize(userRestImpl.getUser(adminToken, Configuration.ANONYMOUS_LOGIN, "")); + userRestImpl.updatePreferences(adminToken, Configuration.ANONYMOUS_LOGIN, (Map<String, Object>) data.get("preferences")); } catch (Exception e) { @@ -99,7 +98,7 @@ public class UserRestImplTest extends RestTestFunctions { @Test public void testGetUsers() throws Exception { try { - Object response = userRestImpl.getUsers(adminToken.getId(), ""); + Object response = userRestImpl.getUsers(adminToken, ""); assertNotNull(response); } catch (Exception e) { e.printStackTrace(); diff --git a/rest-api/src/test/resources/test-applicationContext.xml b/rest-api/src/test/resources/test-applicationContext.xml new file mode 100644 index 0000000000000000000000000000000000000000..9bd238746219dfb4bf7a443451209c5d8ecb9116 --- /dev/null +++ b/rest-api/src/test/resources/test-applicationContext.xml @@ -0,0 +1,14 @@ +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:context="http://www.springframework.org/schema/context" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans-4.0.xsd + http://www.springframework.org/schema/tx + http://www.springframework.org/schema/tx/spring-tx-4.0.xsd + http://www.springframework.org/schema/context + http://www.springframework.org/schema/context/spring-context-4.0.xsd"> + + <bean id="SessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/> + +</beans> diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java b/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java index faf8f766ae94a39b5accd4f67f10098b8d555708..1e928dd14e09bad74c4f6dc8786f13c9256af80c 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java @@ -25,6 +25,7 @@ import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.user.PrivilegeType; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.dao.map.CommentDao; +import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.UserAccessException; import lcsb.mapviewer.services.interfaces.ICommentService; import lcsb.mapviewer.services.interfaces.IConfigurationService; @@ -37,7 +38,6 @@ import lcsb.mapviewer.services.search.comment.FullCommentViewFactory; import lcsb.mapviewer.services.search.data.ElementIdentifier; import lcsb.mapviewer.services.search.data.ElementIdentifier.ElementIdentifierType; import lcsb.mapviewer.services.utils.EmailSender; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.CommentView; import lcsb.mapviewer.services.view.CommentViewFactory; @@ -54,7 +54,7 @@ public class CommentService implements ICommentService { /** * Max distance between two points on map for which two comments should be - * considered as refereing to the same point. + * considered as referring to the same point. */ private static final double COMMENT_POINT_DISTANCE_EPSILON = 0.02; @@ -189,7 +189,7 @@ public class CommentService implements ICommentService { } @Override - public List<CommentView> getCommentsByMap(Model model, AuthenticationToken token) throws UserAccessException { + public List<CommentView> getCommentsByMap(Model model, String token) throws SecurityException { boolean editComments = userService.userHasPrivilege(token, PrivilegeType.EDIT_COMMENTS_PROJECT, model.getProject()); boolean viewProject = userService.userHasPrivilege(token, PrivilegeType.VIEW_PROJECT, model.getProject()); if (!editComments && !viewProject) { @@ -409,7 +409,7 @@ public class CommentService implements ICommentService { } @Override - public List<Comment> getCommentsByProject(Project project, AuthenticationToken token) throws UserAccessException { + public List<Comment> getCommentsByProject(Project project, String token) throws SecurityException { boolean editComments = userService.userHasPrivilege(token, PrivilegeType.EDIT_COMMENTS_PROJECT, project); boolean viewProject = userService.userHasPrivilege(token, PrivilegeType.VIEW_PROJECT, project); boolean manageProjects = userService.userHasPrivilege(token, PrivilegeType.PROJECT_MANAGEMENT); @@ -426,10 +426,11 @@ public class CommentService implements ICommentService { } @Override - public void deleteComment(Comment comment, AuthenticationToken token, String reason) throws UserAccessException { + public void deleteComment(Comment comment, String token, String reason) throws SecurityException { Project project = comment.getModelData().getProject(); boolean editComments = userService.userHasPrivilege(token, PrivilegeType.EDIT_COMMENTS_PROJECT, project); - if (editComments || userService.getUserByToken(token).equals(comment.getUser())) { + User user = userService.getUserByToken(token); + if (editComments || user.equals(comment.getUser())) { comment.setDeleted(true); comment.setRemoveReason(reason); commentDao.update(comment); diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/LayoutService.java b/service/src/main/java/lcsb/mapviewer/services/impl/LayoutService.java index 753d7999db145c31b109185974aa7ce94fd95533..85f04b62e41bdb7de6b929aab92502a586d929d2 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/LayoutService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/LayoutService.java @@ -68,7 +68,6 @@ import lcsb.mapviewer.services.search.layout.LightLayoutReactionViewFactory; import lcsb.mapviewer.services.utils.ColorSchemaReader; import lcsb.mapviewer.services.utils.EmailSender; import lcsb.mapviewer.services.utils.data.ColorSchemaColumn; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.LayoutView; import lcsb.mapviewer.services.view.LayoutViewFactory; @@ -897,7 +896,7 @@ public class LayoutService implements ILayoutService { } @Override - public byte[] getInputDataForLayout(LayoutView layoutView, AuthenticationToken token) throws SecurityException { + public byte[] getInputDataForLayout(LayoutView layoutView, String token) throws SecurityException { return getInputDataForLayout(layoutView.getIdObject(), token); } @@ -912,7 +911,7 @@ public class LayoutService implements ILayoutService { * database (compatibility reasons) then null is returned * @throws SecurityException */ - private byte[] getInputDataForLayout(int layoutId, AuthenticationToken token) throws SecurityException { + private byte[] getInputDataForLayout(int layoutId, String token) throws SecurityException { Layout layout = getLayoutDataById(layoutId, token); if (layout == null) { return null; @@ -926,7 +925,7 @@ public class LayoutService implements ILayoutService { } @Override - public List<LightLayoutAliasView> getAliasesForLayout(Model model, int layoutId, AuthenticationToken token) + public List<LightLayoutAliasView> getAliasesForLayout(Model model, int layoutId, String token) throws SecurityException { try { ColorSchemaReader reader = new ColorSchemaReader(); @@ -950,7 +949,7 @@ public class LayoutService implements ILayoutService { } @Override - public List<LightLayoutReactionView> getReactionsForLayout(Model model, int layoutId, AuthenticationToken token) + public List<LightLayoutReactionView> getReactionsForLayout(Model model, int layoutId, String token) throws SecurityException { try { ColorSchemaReader reader = new ColorSchemaReader(); @@ -974,7 +973,7 @@ public class LayoutService implements ILayoutService { } @Override - public Map<Object, ColorSchema> getElementsForLayout(Model model, Integer layoutId, AuthenticationToken token) + public Map<Object, ColorSchema> getElementsForLayout(Model model, Integer layoutId, String token) throws SecurityException { try { ColorSchemaReader reader = new ColorSchemaReader(); @@ -993,7 +992,7 @@ public class LayoutService implements ILayoutService { @Override public List<FullLayoutAliasView> getFullAliasesForLayoutByIds(Model model, List<Pair<Integer, Integer>> identifiers, - int layoutId, AuthenticationToken token) throws SecurityException { + int layoutId, String token) throws SecurityException { try { Set<Integer> ids = new HashSet<>(); for (Pair<Integer, Integer> pair : identifiers) { @@ -1043,7 +1042,7 @@ public class LayoutService implements ILayoutService { } @Override - public LayoutView getLayoutById(int overlayId, AuthenticationToken token) throws SecurityException { + public LayoutView getLayoutById(int overlayId, String token) throws SecurityException { Layout layout = getLayoutDataById(overlayId, token); if (layout == null) { return null; @@ -1052,7 +1051,7 @@ public class LayoutService implements ILayoutService { } @Override - public Layout getLayoutDataById(int overlayId, AuthenticationToken token) throws SecurityException { + public Layout getLayoutDataById(int overlayId, String token) throws SecurityException { Layout layout = layoutDao.getById(overlayId); if (layout == null) { return null; @@ -1065,7 +1064,7 @@ public class LayoutService implements ILayoutService { } @Override - public FullLayoutAliasView getFullAliasForLayout(Model model, Integer id, int layoutId, AuthenticationToken token) + public FullLayoutAliasView getFullAliasForLayout(Model model, Integer id, int layoutId, String token) throws SecurityException { try { ColorSchemaReader reader = new ColorSchemaReader(); @@ -1093,8 +1092,8 @@ public class LayoutService implements ILayoutService { } @Override - public FullLayoutReactionView getFullReactionForLayout(Model model, Integer id, int layoutId, - AuthenticationToken token) throws SecurityException { + public FullLayoutReactionView getFullReactionForLayout(Model model, Integer id, int layoutId, String token) + throws SecurityException { try { ColorSchemaReader reader = new ColorSchemaReader(); Collection<ColorSchema> schemas; @@ -1121,7 +1120,7 @@ public class LayoutService implements ILayoutService { } @Override - public boolean userCanRemoveLayout(LayoutView layout, AuthenticationToken authenticationToken) { + public boolean userCanRemoveLayout(LayoutView layout, String authenticationToken) throws SecurityException { User user = userService.getUserByToken(authenticationToken); return userCanRemoveLayout(layout, user); } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java b/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java index d3634f6b8db02c1ef0494eb7d8ee3187ed9d9e1c..9f8111197fd2cd33ea13978d6f9c2592cb258bd4 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java @@ -41,7 +41,6 @@ import lcsb.mapviewer.services.interfaces.IUserService; import lcsb.mapviewer.services.search.data.LightAliasView; import lcsb.mapviewer.services.search.data.LightAliasViewFactory; import lcsb.mapviewer.services.search.data.LightReactionView; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.LayoutView; import lcsb.mapviewer.services.view.ModelView; import lcsb.mapviewer.services.view.ModelViewFactory; @@ -123,7 +122,7 @@ public class ModelService implements IModelService { private TaxonomyBackend taxonomyBackend; @Override - public Model getLastModelByProjectId(String projectName, AuthenticationToken token) { + public Model getLastModelByProjectId(String projectName, String token) throws lcsb.mapviewer.services.SecurityException { if (projectName == null) { return null; } @@ -561,7 +560,7 @@ public class ModelService implements IModelService { } @Override - public void updateModel(ModelData model, AuthenticationToken token) { + public void updateModel(ModelData model, String token) throws lcsb.mapviewer.services.SecurityException { Model topCachedData = getLastModelByProjectId(model.getProject().getProjectId(), token); Model cachedData = topCachedData.getSubmodelById(model.getId()); cachedData.setDefaultCenterX(model.getDefaultCenterX()); diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java b/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java index 4e1cb28e8895f1d23f26ea4d39cace0a6aace908..a6713e8be40dbf351ce845634fe18fc958ca44f8 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java @@ -106,7 +106,6 @@ import lcsb.mapviewer.services.utils.CreateProjectParams; import lcsb.mapviewer.services.utils.EmailSender; import lcsb.mapviewer.services.utils.InvalidDataMiningInputFile; import lcsb.mapviewer.services.utils.data.BuildInLayout; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ProjectView; import lcsb.mapviewer.services.view.ProjectViewFactory; @@ -265,7 +264,7 @@ public class ProjectService implements IProjectService { private MapGenerator generator = new MapGenerator(); @Override - public Project getProjectByProjectId(String name, AuthenticationToken token) throws UserAccessException { + public Project getProjectByProjectId(String name, String token) throws SecurityException { Project result = projectDao.getProjectByProjectId(name); if (result == null) { return result; @@ -287,7 +286,7 @@ public class ProjectService implements IProjectService { } @Override - public List<Project> getAllProjects(AuthenticationToken token) { + public List<Project> getAllProjects(String token) throws SecurityException { List<Project> projects = projectDao.getAll(); if (userService.userHasPrivilege(token, PrivilegeType.ADD_MAP)) { return projects; @@ -302,7 +301,7 @@ public class ProjectService implements IProjectService { } @Override - public List<ProjectView> getAllProjectViews(AuthenticationToken token) { + public List<ProjectView> getAllProjectViews(String token) throws SecurityException { List<ProjectView> result = new ArrayList<>(); List<Project> projects = getAllProjects(token); for (Project project : projects) { @@ -359,8 +358,8 @@ public class ProjectService implements IProjectService { } @Override - public void removeProject(ProjectView selectedProject, String homeDir, boolean async, AuthenticationToken token) - throws UserAccessException { + public void removeProject(ProjectView selectedProject, String homeDir, boolean async, String token) + throws SecurityException { Project project = projectDao.getById(selectedProject.getIdObject()); removeProject(project, homeDir, async, token); } @@ -381,14 +380,14 @@ public class ProjectService implements IProjectService { } @Override - public ProjectView getProjectViewByProjectId(String name, AuthenticationToken token) throws UserAccessException { + public ProjectView getProjectViewByProjectId(String name, String token) throws SecurityException { Project project = getProjectByProjectId(name, token); return projectViewFactory.create(project); } @Override - public void removeProject(final Project p, final String dir, final boolean async, AuthenticationToken token) - throws UserAccessException { + public void removeProject(final Project p, final String dir, final boolean async, String token) + throws SecurityException { if (!userService.userHasPrivilege(userService.getUserByToken(token), PrivilegeType.PROJECT_MANAGEMENT)) { throw new UserAccessException("User cannot remove project"); } @@ -497,17 +496,17 @@ public class ProjectService implements IProjectService { /** * When we encountered hibernate exception we need to handle error reporting * differently (hibernate session is broken). This method handles such case when - * hibernate excedption occured when removing project. + * hibernate exception occurred when removing project. * * @param originalProject - * project that was beining removed + * project that was being removed * @param exception * hibernate exception that caused problems */ protected void handleHibernateExceptionRemovingReporting(Project originalProject, HibernateException exception, - AuthenticationToken token) { + String token) { // we need to open separate thread because current one thrown db exception - // and transaction is corrupetd and will be rolledback + // and transaction is corrupted and will be rolledback Thread reportInSeparateThread = new Thread(new Runnable() { @Override @@ -522,7 +521,7 @@ public class ProjectService implements IProjectService { project.setErrors(errorMessage + "\n" + project.getErrors()); project.setStatus(ProjectStatus.FAIL); projectDao.update(project); - } catch (UserAccessException e) { + } catch (SecurityException e) { logger.error(e, e); } finally { dbUtils.closeSessionForCurrentThread(); @@ -540,7 +539,7 @@ public class ProjectService implements IProjectService { } @Override - public ProjectView getProjectViewById(Integer id, AuthenticationToken token) throws UserAccessException { + public ProjectView getProjectViewById(Integer id, String token) throws SecurityException { Project project = projectDao.getById(id); if (userService.userHasPrivilege(token, PrivilegeType.VIEW_PROJECT, project)) { return projectViewFactory.create(project); @@ -1529,11 +1528,11 @@ public class ProjectService implements IProjectService { * @param params * parameters used to create project * @param e - * exception that occured during uploading of the project + * exception that occurred during uploading of the project */ private void handleHibernateExceptionReporting(CreateProjectParams params, HibernateException e) { // we need to open separate thread because current one thrown db exception - // and transaction is corrupetd and will be rolledback + // and transaction is corrupted and will be rolledback Thread reportInSeparateThread = new Thread(new Runnable() { @Override diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/ReferenceGenomeService.java b/service/src/main/java/lcsb/mapviewer/services/impl/ReferenceGenomeService.java index 13fd8dc9e217d4ae68f0955a58cec0e3700af48b..07fc7be059671037a6e84c5f560d07f9e1fe8bf7 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ReferenceGenomeService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/ReferenceGenomeService.java @@ -21,7 +21,6 @@ import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; import lcsb.mapviewer.persist.dao.map.layout.ReferenceGenomeDao; import lcsb.mapviewer.services.interfaces.IReferenceGenomeService; import lcsb.mapviewer.services.utils.ReferenceGenomeExistsException; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ReferenceGenomeView; import lcsb.mapviewer.services.view.ReferenceGenomeViewFactory; @@ -34,123 +33,128 @@ import lcsb.mapviewer.services.view.ReferenceGenomeViewFactory; @Transactional(value = "txManager") public class ReferenceGenomeService implements IReferenceGenomeService { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private Logger logger = Logger.getLogger(ReferenceGenomeService.class); - - /** - * Class responsible for connection to {@link ReferenceGenomeType#UCSC} - * database. - */ - @Autowired - private UcscReferenceGenomeConnector ucscReferenceGenomeConnector; - - /** - * Data access object for {@link ReferenceGenome} objects. - */ - @Autowired - private ReferenceGenomeDao referenceGenomeDao; - - /** - * Factory that creates {@link ReferenceGenomeView}. - */ - @Autowired - private ReferenceGenomeViewFactory factory; - - @Override - public void addReferenceGenome(ReferenceGenomeType type, MiriamData organism, String version, String customUrl) - throws IOException, URISyntaxException, ReferenceGenomeConnectorException { - for (ReferenceGenome genome : getDownloadedGenomes()) { - if (genome.getType().equals(type) && genome.getOrganism().equals(organism) && genome.getVersion().equals(version)) { - throw new ReferenceGenomeExistsException("Selected reference genome already downloaded"); - } - } - getReferenceGenomeConnector(type).downloadGenomeVersion(organism, version, new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }, true, customUrl); - } - - /** - * Return {@link ReferenceGenomeConnector} implementation for given reference - * genome type. - * - * @param type - * type of reference genome - * @return {@link ReferenceGenomeConnector} implementation for given reference - * genome type - */ - private ReferenceGenomeConnector getReferenceGenomeConnector(ReferenceGenomeType type) { - if (type == ReferenceGenomeType.UCSC) { - return ucscReferenceGenomeConnector; - } else { - throw new InvalidArgumentException("Unknown reference genome type: " + type); - } - } - - @Override - public List<MiriamData> getOrganismsByReferenceGenomeType(ReferenceGenomeType type) throws ReferenceGenomeConnectorException { - return getReferenceGenomeConnector(type).getAvailableOrganisms(); - } - - @Override - public List<String> getAvailableGenomeVersions(ReferenceGenomeType type, MiriamData organism) throws ReferenceGenomeConnectorException { - return getReferenceGenomeConnector(type).getAvailableGenomeVersion(organism); - } - - @Override - public String getUrlForGenomeVersion(ReferenceGenomeType type, MiriamData organism, String version) { - try { - return getReferenceGenomeConnector(type).getGenomeVersionFile(organism, version); - } catch (FileNotAvailableException e) { - return null; - } - } - - @Override - public List<ReferenceGenome> getDownloadedGenomes() { - return referenceGenomeDao.getAll(); - } - - @Override - public void removeGenome(ReferenceGenome genome) throws IOException { - getReferenceGenomeConnector(genome.getType()).removeGenomeVersion(genome.getOrganism(), genome.getVersion()); - } - - @Override - public void addReferenceGenomeGeneMapping(ReferenceGenome referenceGenome, String name, String url) - throws IOException, URISyntaxException, ReferenceGenomeConnectorException { - getReferenceGenomeConnector(referenceGenome.getType()).downloadGeneMappingGenomeVersion(referenceGenome, name, new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }, true, url); - - } - - @Override - public void removeReferenceGenomeGeneMapping(ReferenceGenomeGeneMapping genome) throws IOException { - getReferenceGenomeConnector(genome.getReferenceGenome().getType()).removeGeneMapping(genome); - } - - @Override - public ReferenceGenomeView getReferenceGenomeViewByParams(MiriamData miriamData, ReferenceGenomeType genomeType, String version) { - List<ReferenceGenome> list = referenceGenomeDao.getByType(genomeType); - for (ReferenceGenome referenceGenome : list) { - if (referenceGenome.getOrganism().equals(miriamData) && referenceGenome.getVersion().equals(version)) { - return factory.create(referenceGenome); - } - } - return null; - } - - @Override - public ReferenceGenomeView getReferenceGenomeViewByParams(MiriamData organism, ReferenceGenomeType genomeType, String version, - AuthenticationToken authenticationToken) { - return this.getReferenceGenomeViewByParams(organism, genomeType, version); - } + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private Logger logger = Logger.getLogger(ReferenceGenomeService.class); + + /** + * Class responsible for connection to {@link ReferenceGenomeType#UCSC} + * database. + */ + @Autowired + private UcscReferenceGenomeConnector ucscReferenceGenomeConnector; + + /** + * Data access object for {@link ReferenceGenome} objects. + */ + @Autowired + private ReferenceGenomeDao referenceGenomeDao; + + /** + * Factory that creates {@link ReferenceGenomeView}. + */ + @Autowired + private ReferenceGenomeViewFactory factory; + + @Override + public void addReferenceGenome(ReferenceGenomeType type, MiriamData organism, String version, String customUrl) + throws IOException, URISyntaxException, ReferenceGenomeConnectorException { + for (ReferenceGenome genome : getDownloadedGenomes()) { + if (genome.getType().equals(type) && genome.getOrganism().equals(organism) + && genome.getVersion().equals(version)) { + throw new ReferenceGenomeExistsException("Selected reference genome already downloaded"); + } + } + getReferenceGenomeConnector(type).downloadGenomeVersion(organism, version, new IProgressUpdater() { + @Override + public void setProgress(double progress) { + } + }, true, customUrl); + } + + /** + * Return {@link ReferenceGenomeConnector} implementation for given reference + * genome type. + * + * @param type + * type of reference genome + * @return {@link ReferenceGenomeConnector} implementation for given reference + * genome type + */ + private ReferenceGenomeConnector getReferenceGenomeConnector(ReferenceGenomeType type) { + if (type == ReferenceGenomeType.UCSC) { + return ucscReferenceGenomeConnector; + } else { + throw new InvalidArgumentException("Unknown reference genome type: " + type); + } + } + + @Override + public List<MiriamData> getOrganismsByReferenceGenomeType(ReferenceGenomeType type) + throws ReferenceGenomeConnectorException { + return getReferenceGenomeConnector(type).getAvailableOrganisms(); + } + + @Override + public List<String> getAvailableGenomeVersions(ReferenceGenomeType type, MiriamData organism) + throws ReferenceGenomeConnectorException { + return getReferenceGenomeConnector(type).getAvailableGenomeVersion(organism); + } + + @Override + public String getUrlForGenomeVersion(ReferenceGenomeType type, MiriamData organism, String version) { + try { + return getReferenceGenomeConnector(type).getGenomeVersionFile(organism, version); + } catch (FileNotAvailableException e) { + return null; + } + } + + @Override + public List<ReferenceGenome> getDownloadedGenomes() { + return referenceGenomeDao.getAll(); + } + + @Override + public void removeGenome(ReferenceGenome genome) throws IOException { + getReferenceGenomeConnector(genome.getType()).removeGenomeVersion(genome.getOrganism(), genome.getVersion()); + } + + @Override + public void addReferenceGenomeGeneMapping(ReferenceGenome referenceGenome, String name, String url) + throws IOException, URISyntaxException, ReferenceGenomeConnectorException { + getReferenceGenomeConnector(referenceGenome.getType()).downloadGeneMappingGenomeVersion(referenceGenome, name, + new IProgressUpdater() { + @Override + public void setProgress(double progress) { + } + }, true, url); + + } + + @Override + public void removeReferenceGenomeGeneMapping(ReferenceGenomeGeneMapping genome) throws IOException { + getReferenceGenomeConnector(genome.getReferenceGenome().getType()).removeGeneMapping(genome); + } + + @Override + public ReferenceGenomeView getReferenceGenomeViewByParams(MiriamData miriamData, ReferenceGenomeType genomeType, + String version) { + List<ReferenceGenome> list = referenceGenomeDao.getByType(genomeType); + for (ReferenceGenome referenceGenome : list) { + if (referenceGenome.getOrganism().equals(miriamData) && referenceGenome.getVersion().equals(version)) { + return factory.create(referenceGenome); + } + } + return null; + } + + @Override + public ReferenceGenomeView getReferenceGenomeViewByParams(MiriamData organism, ReferenceGenomeType genomeType, + String version, String authenticationToken) { + return this.getReferenceGenomeViewByParams(organism, genomeType, version); + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java b/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java index 5a72274aa34818ccc17610d7d171d4d5a4aa8085..bac9ff234a7609bc95bcea60948f7bbac381db5a 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java @@ -5,14 +5,12 @@ import java.math.BigInteger; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Collection; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Random; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.session.SessionInformation; import org.springframework.security.core.session.SessionRegistry; import org.springframework.security.crypto.password.PasswordEncoder; @@ -34,14 +32,11 @@ import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.dao.ProjectDao; import lcsb.mapviewer.persist.dao.user.PrivilegeDao; import lcsb.mapviewer.persist.dao.user.UserDao; -import lcsb.mapviewer.services.AuthenticationTokenExpireException; -import lcsb.mapviewer.services.InvalidTokenException; import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.interfaces.IConfigurationService; import lcsb.mapviewer.services.interfaces.ILogService; import lcsb.mapviewer.services.interfaces.ILogService.LogParams; import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.PrivilegeView; import lcsb.mapviewer.services.view.UserView; import lcsb.mapviewer.services.view.UserView.UserProjectPrivilegeView; @@ -56,10 +51,6 @@ import lcsb.mapviewer.services.view.UserViewFactory; @Transactional(value = "txManager") public class UserService implements IUserService { - private static Map<String, AuthenticationToken> authenticationTokens = new HashMap<>(); - - private static Map<AuthenticationToken, User> authenticatedUsers = new HashMap<>(); - /** * Default class logger. */ @@ -111,23 +102,12 @@ public class UserService implements IUserService { private IConfigurationService configurationService; @Override - public AuthenticationToken login(String login, String password) { + public String login(String login, String password) { Random random = new SecureRandom(); String id = new BigInteger(130, random).toString(32); return this.login(login, password, id); } - private void clearAuthenticationTokens() { - synchronized (authenticationTokens) { - List<String> toRemove = new ArrayList<>(); - for (AuthenticationToken token : authenticationTokens.values()) { - if (isSessionExpired(token)) { - toRemove.add(token.getId()); - } - } - } - } - @Override public boolean userHasPrivilege(User user, PrivilegeType type) { return getUserPrivilegeLevel(user, type) > 0; @@ -509,72 +489,39 @@ public class UserService implements IUserService { } @Override - public User getUserByToken(AuthenticationToken token) { - User result = null; + public User getUserByToken(String token) throws SecurityException { if (!isSessionExpired(token)) { - synchronized (authenticationTokens) { - result = authenticatedUsers.get(token); - } - } - return result; - } - - @Override - public User getUserByToken(String tokenString) throws SecurityException { - return getUserByToken(getToken(tokenString)); - } - - @Override - public AuthenticationToken getToken(String tokenString) throws SecurityException { - AuthenticationToken result = null; - synchronized (authenticationTokens) { - result = authenticationTokens.get(tokenString); - } - if (result == null) { - throw new InvalidTokenException("Token string is invalid"); - } - if (isSessionExpired(result)) { - logout(result); - throw new AuthenticationTokenExpireException("Token validity expired"); + String login = ((org.springframework.security.core.userdetails.User) (sessionRegistry.getSessionInformation(token) + .getPrincipal())).getUsername(); + return userDao.getUserByLogin(login); + } else { + throw new SecurityException("Invalid token"); } - return result; } - private boolean isSessionExpired(AuthenticationToken result) { - SessionInformation sessionData = sessionRegistry.getSessionInformation(result.getId()); + private boolean isSessionExpired(String token) { + SessionInformation sessionData = sessionRegistry.getSessionInformation(token); if (sessionData == null) { - logger.debug("No session data for token id: " + result.getId()); + logger.debug("No session data for token id: " + token); return true; } return sessionData.isExpired(); } @Override - public void logout(AuthenticationToken token) { - synchronized (authenticationTokens) { - authenticationTokens.remove(token.getId()); - authenticatedUsers.remove(token); - } - } - - @Override - public boolean userHasPrivilege(AuthenticationToken token, PrivilegeType type, Object object) { + public boolean userHasPrivilege(String token, PrivilegeType type, Object object) throws SecurityException { return userHasPrivilege(getUserByToken(token), type, object); } @Override - public void logout(String tokenString) throws SecurityException { - AuthenticationToken token = getToken(tokenString); - logout(token); - } - - @Override - public boolean userHasPrivilege(AuthenticationToken token, PrivilegeType type) { - return userHasPrivilege(getUserByToken(token), type); + public void logout(String tokenString) { + if (!isSessionExpired(tokenString)) { + sessionRegistry.removeSessionInformation(tokenString); + } } @Override - public User getUserById(String creatorId, AuthenticationToken authenticationToken) throws SecurityException { + public User getUserById(String creatorId, String authenticationToken) throws SecurityException { User user = getUserByToken(authenticationToken); Integer id = Integer.parseInt(creatorId); if (user.getId().equals(id)) { @@ -587,7 +534,7 @@ public class UserService implements IUserService { } @Override - public List<User> getUsers(AuthenticationToken token) throws SecurityException { + public List<User> getUsers(String token) throws SecurityException { if (userHasPrivilege(token, PrivilegeType.USER_MANAGEMENT)) { return userDao.getAll(); } else { @@ -596,8 +543,7 @@ public class UserService implements IUserService { } @Override - public void setUserPrivilege(User user, PrivilegeType type, Object value, AuthenticationToken token) - throws SecurityException { + public void setUserPrivilege(User user, PrivilegeType type, Object value, String token) throws SecurityException { if (!userHasPrivilege(token, PrivilegeType.USER_MANAGEMENT)) { throw new SecurityException("You cannot modify user privileges"); } @@ -615,7 +561,7 @@ public class UserService implements IUserService { } @Override - public void setUserPrivilege(User user, PrivilegeType type, Object value, Integer objectId, AuthenticationToken token) + public void setUserPrivilege(User user, PrivilegeType type, Object value, Integer objectId, String token) throws SecurityException { boolean canModify = userHasPrivilege(token, PrivilegeType.USER_MANAGEMENT); if (!canModify) { @@ -647,7 +593,7 @@ public class UserService implements IUserService { } @Override - public void updateUser(User modifiedUser, AuthenticationToken token) throws SecurityException { + public void updateUser(User modifiedUser, String token) throws SecurityException { User user = getUserByToken(token); if (user.getLogin().equals(modifiedUser.getLogin()) || userHasPrivilege(token, PrivilegeType.USER_MANAGEMENT)) { updateUser(modifiedUser); @@ -663,26 +609,15 @@ public class UserService implements IUserService { } @Override - public AuthenticationToken login(String login, String password, String id) { + public String login(String login, String password, String token) { User user = userDao.getUserByLoginAndPassword(login, password); if (user == null && Configuration.ANONYMOUS_LOGIN.equals(login) && "".equals(password)) { user = getUserByLogin(Configuration.ANONYMOUS_LOGIN); } if (user != null) { - int count = 0; - synchronized (authenticationTokens) { - count = authenticationTokens.size(); - } - - if (count > 1000) { - clearAuthenticationTokens(); - } - AuthenticationToken authenticationToken = new AuthenticationToken(id); - synchronized (authenticationTokens) { - authenticationTokens.put(authenticationToken.getId(), authenticationToken); - authenticatedUsers.put(authenticationToken, user); - } - return authenticationToken; + sessionRegistry.registerNewSession(token, new org.springframework.security.core.userdetails.User(login, + passwordEncoder.encode(password), AuthorityUtils.commaSeparatedStringToAuthorityList(""))); + return token; } else { return null; } diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/ICommentService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/ICommentService.java index dd3db2c6beb22011de2f1a352a919a8893a903f5..048f9249b28823e55e698b2c9d61fcdd6a770506 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/ICommentService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/ICommentService.java @@ -8,11 +8,11 @@ import lcsb.mapviewer.model.map.Comment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelData; import lcsb.mapviewer.model.user.User; +import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.UserAccessException; import lcsb.mapviewer.services.search.ElementIdentifierDetails; import lcsb.mapviewer.services.search.comment.FullCommentView; import lcsb.mapviewer.services.search.data.ElementIdentifier; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.CommentView; /** @@ -22,101 +22,103 @@ import lcsb.mapviewer.services.view.CommentView; * */ public interface ICommentService { - /** - * Adds comment to the map. - * - * @param pinned - * parameter that defines if comment should be visible on the map. - * @param object - * determines which object is commented - it could be null; in this - * case it means that a comment is general one. - * @param name - * name of person that comments - * @param email - * email of the person that comments - * @param content - * content of the comment - * @param model - * which map we comment on - * @param submodel - * on which submodel we comment on - * @param coordinates - * where exactly the comment should be placed on - * - * @return comment object created based on the data provided as parameters - */ - Comment addComment(String name, String email, String content, Model model, Point2D coordinates, Object object, boolean pinned, Model submodel); + /** + * Adds comment to the map. + * + * @param pinned + * parameter that defines if comment should be visible on the map. + * @param object + * determines which object is commented - it could be null; in this + * case it means that a comment is general one. + * @param name + * name of person that comments + * @param email + * email of the person that comments + * @param content + * content of the comment + * @param model + * which map we comment on + * @param submodel + * on which submodel we comment on + * @param coordinates + * where exactly the comment should be placed on + * + * @return comment object created based on the data provided as parameters + */ + Comment addComment(String name, String email, String content, Model model, Point2D coordinates, Object object, + boolean pinned, Model submodel); - /** - * This method remove comment. Comment is not removed from the system, only - * 'deleted' flag is set. - * - * @param loggedUser - * user that wants to remove the comment - * @param commentId - * identifier of the comment that user wants to remove - * @param reason - * why user wants to remove the comment - */ - void deleteComment(User loggedUser, String commentId, String reason); - - void deleteComment(Comment comment, AuthenticationToken token, String reason) throws UserAccessException; + /** + * This method remove comment. Comment is not removed from the system, only + * 'deleted' flag is set. + * + * @param loggedUser + * user that wants to remove the comment + * @param commentId + * identifier of the comment that user wants to remove + * @param reason + * why user wants to remove the comment + */ + void deleteComment(User loggedUser, String commentId, String reason); - /** - * Method returns all comments for a given map. - * - * @param model - * given map - * @return list of the comments to the map - * @throws UserAccessException - */ - List<CommentView> getCommentsByMap(Model model, AuthenticationToken token) throws UserAccessException; - - List<Comment> getCommentsByProject(Project project, AuthenticationToken token) throws UserAccessException; + void deleteComment(Comment comment, String token, String reason) throws UserAccessException, SecurityException; - /** - * Returns number of comments in the system. - * - * @return number of comments in the system - */ - long getCommentCount(); + /** + * Method returns all comments for a given map. + * + * @param model + * given map + * @return list of the comments to the map + * @throws UserAccessException + * @throws SecurityException + */ + List<CommentView> getCommentsByMap(Model model, String token) throws UserAccessException, SecurityException; - /** - * Removes comments from the model. - * - * @param model - * from which model we want to remove comments - */ - void removeCommentsForModel(Model model); + List<Comment> getCommentsByProject(Project project, String token) throws UserAccessException, SecurityException; - /** - * This method returns marker for all comments in a model. - * - * @param model - * object to which we are looking for comments - * @return list of markers for comments - */ - List<FullCommentView> getCommentMarkers(Model model); + /** + * Returns number of comments in the system. + * + * @return number of comments in the system + */ + long getCommentCount(); - /** - * Removes comments from the model. - * - * @param model - * from which model we want to remove comments - */ - void removeCommentsForModel(ModelData model); + /** + * Removes comments from the model. + * + * @param model + * from which model we want to remove comments + */ + void removeCommentsForModel(Model model); - /** - * Returns detailed comment information about element. - * - * @param element - * element for which we are looking for comments - * @param model - * model where we are looking for comments - * @return detailed comment information about element - */ - List<ElementIdentifierDetails> getElementInformationForResult(ElementIdentifier element, Model model); + /** + * This method returns marker for all comments in a model. + * + * @param model + * object to which we are looking for comments + * @return list of markers for comments + */ + List<FullCommentView> getCommentMarkers(Model model); - Comment getCommentById(String commentId); + /** + * Removes comments from the model. + * + * @param model + * from which model we want to remove comments + */ + void removeCommentsForModel(ModelData model); + + /** + * Returns detailed comment information about element. + * + * @param element + * element for which we are looking for comments + * @param model + * model where we are looking for comments + * @return detailed comment information about element + */ + List<ElementIdentifierDetails> getElementInformationForResult(ElementIdentifier element, Model model); + + Comment getCommentById(String commentId); } diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/ILayoutService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/ILayoutService.java index a95d2623c9c82080e0887c71356fd143e28edae5..4b2c24e810b38875a9664fb7ab77e940bb73f53b 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/ILayoutService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/ILayoutService.java @@ -21,7 +21,6 @@ import lcsb.mapviewer.services.search.layout.LightLayoutAliasView; import lcsb.mapviewer.services.search.layout.LightLayoutReactionView; import lcsb.mapviewer.services.utils.EmailSender; import lcsb.mapviewer.services.utils.data.ColorSchemaType; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.LayoutView; /** @@ -32,501 +31,502 @@ import lcsb.mapviewer.services.view.LayoutView; */ public interface ILayoutService { - /** - * Parameters used for creation of the layout. - * - * @author Piotr Gawron - * - */ - class CreateLayoutParams { - - /** - * Size of the buffer used to copy stream data. - */ - private static final int BUFFER_SIZE = 1024; - - /** - * Name of the layout. - * - */ - private String name; - - /** - * Description of the layout. - * - */ - private String description; - - /** - * Where the graphic files should be saved. - * - */ - private String directory; - - /** - * - * {@link Model} for which the layout is created. - */ - private Model model; - - /** - * Who creates the layout. - * - */ - private User user; - - /** - * - * Input stream with coloring information data in the stream should - * correspond to a file that can be parsed by - * {@link lcsb.mapviewer.services.utils.ColorSchemaXlsxReader - * ColorSchemaReader} . This is a copy of original input stream, so we can - * read this input stream multiple times. - */ - private ByteArrayOutputStream colorInputStreamCopy; - - /** - * Name of the file used as input (if available). - */ - private String layoutFileName; - - /** - * Determines if creation of the output files should be done asynchronously - * who creates the layout. - * - */ - private boolean async = false; - - /** - * Type of the uploaded file. - */ - private ColorSchemaType colorSchemaType; - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - * @return {@link CreateLayoutParams} object - */ - public CreateLayoutParams name(String name) { - this.name = name; - return this; - } - - /** - * @return the directory - * @see #directory - */ - public String getDirectory() { - return directory; - } - - /** - * @param directory - * the directory to set - * @see #directory - * @return {@link CreateLayoutParams} object - */ - public CreateLayoutParams directory(String directory) { - this.directory = directory; - return this; - } - - /** - * @return the model - * @see #model - */ - public Model getModel() { - return model; - } - - /** - * @param model - * the model to set - * @see #model - * @return {@link CreateLayoutParams} object - */ - public CreateLayoutParams model(Model model) { - this.model = model; - return this; - } - - /** - * @return the user - * @see #user - */ - public User getUser() { - return user; - } - - /** - * @param user - * the user to set - * @see #user - * @return {@link CreateLayoutParams} object - */ - public CreateLayoutParams user(User user) { - this.user = user; - return this; - } - - /** - * @return the colorInputStream - * @see #colorInputStream - */ - public InputStream getColorInputStream() { - return new ByteArrayInputStream(colorInputStreamCopy.toByteArray()); - } - - /** - * @param colorInputStream - * the colorInputStream to set - * @see #colorInputStream - * @return {@link CreateLayoutParams} object - * @throws IOException - * thrown when there is a problem with accessing input stream - */ - public CreateLayoutParams colorInputStream(InputStream colorInputStream) throws IOException { - if (colorInputStream == null) { - this.colorInputStreamCopy = null; - } else { - this.colorInputStreamCopy = new ByteArrayOutputStream(); - - byte[] buffer = new byte[BUFFER_SIZE]; - int len; - while ((len = colorInputStream.read(buffer)) > -1) { - this.colorInputStreamCopy.write(buffer, 0, len); - } - this.colorInputStreamCopy.flush(); - } - return this; - } - - /** - * @return the async - * @see #async - */ - public boolean isAsync() { - return async; - } - - /** - * @param async - * the async to set - * @see #async - * @return {@link CreateLayoutParams} object - */ - public CreateLayoutParams async(boolean async) { - this.async = async; - return this; - } - - /** - * @return the description - * @see #description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - * @see #description - * @return {@link CreateLayoutParams} object - */ - public CreateLayoutParams description(String description) { - this.description = description; - return this; - } - - /** - * - * @return {@link #colorSchemaType} - */ - public ColorSchemaType getColorSchemaType() { - return colorSchemaType; - } - - /** - * @param colorSchemaType - * the colorSchemaType to set - * @see #colorSchemaType - * @return {@link CreateLayoutParams} object - */ - public CreateLayoutParams colorSchemaType(ColorSchemaType colorSchemaType) { - this.colorSchemaType = colorSchemaType; - return this; - } - - /** - * @return the layoutFileName - * @see #layoutFileName - */ - public String getLayoutFileName() { - return layoutFileName; - } - - /** - * @param layoutFileName - * the layoutFileName to set - * @return {@link CreateLayoutParams} object - * @see #layoutFileName - */ - public CreateLayoutParams layoutFileName(String layoutFileName) { - this.layoutFileName = layoutFileName; - return this; - } - } - - /** - * Returns true if user can add layout to the model. - * - * @param model - * to which model user wants to add layout - * @param user - * who wants to add layout - * @return <code>true</code> if user can add layout, <code>false</code> - * otherwise - */ - boolean userCanAddLayout(Model model, User user); - - /** - * Returns true if user can remove layout from the model. - * - * @param layout - * which layout user want to remove - * @param user - * who wants to remove layout - * @return <code>true</code> if user can remove layout, <code>false</code> - * otherwise - */ - boolean userCanRemoveLayout(LayoutView layout, User user); - - /** - * Returns list of custom layouts. - * - * @param model - * model where the layouts lay on - * @param user - * user who asks for the layouts - * @return list of custom layouts - */ - List<LayoutView> getCustomLayouts(Model model, User user, Boolean publicOverlay, User creator); - - /** - * Returns list of general publicly available layouts. - * - * @param model - * model where the layouts lay on - * @return list of custom layouts - */ - List<LayoutView> getGeneralLayouts(Model model); - - /** - * Removes layout from the system. - * - * @param layout - * layout to remove - * @param homeDir - * directory where the system is deployed - * @throws IOException - * thrown when there are problems with removing layout files - */ - void removeLayout(LayoutView layout, String homeDir) throws IOException; - - /** - * Updates data about the layout. - * - * @param layout - * layout to update - */ - void updateLayout(LayoutView layout); - - /** - * Adds view privilege to the layout for the user. - * - * @param layout - * layout for privilege - * @param user - * who should own the privilege - */ - void addViewPrivilegeToLayout(LayoutView layout, User user); - - /** - * Removes view privilege to the layout from the user. - * - * @param layout - * layout for privilege remove - * @param user - * who shouldn't have the privilege - */ - void dropViewPrivilegeFromLayout(LayoutView layout, User user); - - /** - * Create layout based on the data in the parameter. - * - * @param params - * list of {@link CreateLayoutParams params} necessary to create - * layout - * @return object that refers to created layout - * @throws IOException - * thrown when there are problems with files - * @throws InvalidColorSchemaException - * if the coloring source is invalid - * @throws CommandExecutionException - */ - LayoutView createLayout(CreateLayoutParams params) throws IOException, InvalidColorSchemaException; - - /** - * Create layout based on the data in the parameter. Layout will contain set - * of images that can be further visualized in goolge maps api. - * - * @param params - * list of {@link CreateLayoutParams params} necessary to create - * layout - * @return object that refers to created layout - * @throws IOException - * thrown when there are problems with files - * @throws CommandExecutionException - * if the coloring source is invalid - * @throws InvalidColorSchemaException - * if the coloring source is invalid - */ - LayoutView createLayoutWithImages(CreateLayoutParams params) throws IOException, CommandExecutionException, InvalidColorSchemaException; - - /** - * Returns number of still available custom layouts for the user. - * - * @param user - * user for which the number of available custom layouts will be - * returned - * @return number of available custom layouts - */ - long getAvailableCustomLayoutsNumber(User user); - - /** - * Returns layout identified by name and model. - * - * @param model - * model where the layouts lay on - * @param name - * name of the layout - * @return layout - */ - LayoutView getLayoutByName(Model model, String name); - - /** - * Returns byte array containing data from original input file that was used - * to generate the layout. - * - * @param layout - * layout for which we want to retrieve original file data - * @return original data file for given layout, if such file is not stored in - * database (compatibility reasons) then null is returned - * @throws SecurityException - */ - byte[] getInputDataForLayout(LayoutView layout, AuthenticationToken token) throws SecurityException; - - /** - * Returns a list of {@link LightLayoutAliasView aliases} that are visualized - * in a {@link lcsb.mapviewer.model.map.layout.Layout}. - * - * @param model - * model where data is located - * @param layoutId - * identifier of the layout - * @return a list of {@link LightLayoutAliasView aliases} that are visualized - * in a {@link lcsb.mapviewer.model.map.layout.Layout} - * @throws SecurityException - */ - List<LightLayoutAliasView> getAliasesForLayout(Model model, int layoutId, AuthenticationToken token) throws SecurityException; - - /** - * Returns a list of {@link LightLayoutReactionView reactions} that are - * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout}. - * - * @param model - * model where data is located - * @param layoutId - * identifier of the layout - * @return a list of {@link LightLayoutReactionView reactions} that are - * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout} - * @throws SecurityException - */ - List<LightLayoutReactionView> getReactionsForLayout(Model model, int layoutId, AuthenticationToken token) throws SecurityException; - - /** - * Returns mapping between {@link lcsb.mapviewer.model.map.species.Element - * Alias}/ {@link lcsb.mapviewer.model.map.reaction.Reaction Reaction} and - * {@link ColorSchema} used for coloring object in the layout given in the - * parameter. - * - * @param model - * model where data is lcoated - * @param layoutId - * identifier of the layout - * @return a list of {@link LightLayoutReactionView reactions} that are - * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout} - * @throws SecurityException - */ - Map<Object, ColorSchema> getElementsForLayout(Model model, Integer layoutId, AuthenticationToken token) throws SecurityException; - - /** - * Returns a list of {@link FullLayoutAliasView aliases} that are visualized - * in a {@link lcsb.mapviewer.model.map.layout.Layout} and have given - * identifiers. - * - * @param model - * model where data is lcoated - * @param layoutId - * identifier of the layout - * @param identifiers - * list of alias identifiers in a given submodel. Every {@link Pair} - * contains information about {@link Model#getId() model identifier} - * (in {@link Pair#left}) and - * {@link lcsb.mapviewer.model.map.species.Element#getId() alias - * identifier} (in {@link Pair#right}). - * @return a list of {@link LightLayoutAliasView aliases} that are visualized - * in a {@link lcsb.mapviewer.model.map.layout.Layout} - * @throws SecurityException - */ - List<FullLayoutAliasView> getFullAliasesForLayoutByIds(Model model, List<Pair<Integer, Integer>> identifiers, int layoutId, AuthenticationToken token) - throws SecurityException; - - FullLayoutAliasView getFullAliasForLayout(Model model, Integer id, int layoutId, AuthenticationToken token) throws SecurityException; - - FullLayoutReactionView getFullReactionForLayout(Model model, Integer id, int layoutId, AuthenticationToken token) throws SecurityException; - - /** - * Returns {@link EmailSender} used by the service. - * - * @return {@link EmailSender} used by the service - */ - EmailSender getEmailSender(); - - /** - * Sets {@link EmailSender} used by the service. - * - * @param emailSender - * {@link EmailSender} used by the service - */ - void setEmailSender(EmailSender emailSender); - - List<LayoutView> getCustomLayouts(Model model, String token, Boolean publicOverlay, User creator) throws SecurityException; - - LayoutView getLayoutById(int overlayId, AuthenticationToken token) throws SecurityException; - - Layout getLayoutDataById(int overlayId, AuthenticationToken authenticationToken) throws SecurityException; - - boolean userCanRemoveLayout(LayoutView layout, AuthenticationToken authenticationToken); + /** + * Parameters used for creation of the layout. + * + * @author Piotr Gawron + * + */ + class CreateLayoutParams { + + /** + * Size of the buffer used to copy stream data. + */ + private static final int BUFFER_SIZE = 1024; + + /** + * Name of the layout. + * + */ + private String name; + + /** + * Description of the layout. + * + */ + private String description; + + /** + * Where the graphic files should be saved. + * + */ + private String directory; + + /** + * + * {@link Model} for which the layout is created. + */ + private Model model; + + /** + * Who creates the layout. + * + */ + private User user; + + /** + * + * Input stream with coloring information data in the stream should correspond + * to a file that can be parsed by + * {@link lcsb.mapviewer.services.utils.ColorSchemaXlsxReader ColorSchemaReader} + * . This is a copy of original input stream, so we can read this input stream + * multiple times. + */ + private ByteArrayOutputStream colorInputStreamCopy; + + /** + * Name of the file used as input (if available). + */ + private String layoutFileName; + + /** + * Determines if creation of the output files should be done asynchronously who + * creates the layout. + * + */ + private boolean async = false; + + /** + * Type of the uploaded file. + */ + private ColorSchemaType colorSchemaType; + + /** + * @return the name + * @see #name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + * @see #name + * @return {@link CreateLayoutParams} object + */ + public CreateLayoutParams name(String name) { + this.name = name; + return this; + } + + /** + * @return the directory + * @see #directory + */ + public String getDirectory() { + return directory; + } + + /** + * @param directory + * the directory to set + * @see #directory + * @return {@link CreateLayoutParams} object + */ + public CreateLayoutParams directory(String directory) { + this.directory = directory; + return this; + } + + /** + * @return the model + * @see #model + */ + public Model getModel() { + return model; + } + + /** + * @param model + * the model to set + * @see #model + * @return {@link CreateLayoutParams} object + */ + public CreateLayoutParams model(Model model) { + this.model = model; + return this; + } + + /** + * @return the user + * @see #user + */ + public User getUser() { + return user; + } + + /** + * @param user + * the user to set + * @see #user + * @return {@link CreateLayoutParams} object + */ + public CreateLayoutParams user(User user) { + this.user = user; + return this; + } + + /** + * @return the colorInputStream + * @see #colorInputStream + */ + public InputStream getColorInputStream() { + return new ByteArrayInputStream(colorInputStreamCopy.toByteArray()); + } + + /** + * @param colorInputStream + * the colorInputStream to set + * @see #colorInputStream + * @return {@link CreateLayoutParams} object + * @throws IOException + * thrown when there is a problem with accessing input stream + */ + public CreateLayoutParams colorInputStream(InputStream colorInputStream) throws IOException { + if (colorInputStream == null) { + this.colorInputStreamCopy = null; + } else { + this.colorInputStreamCopy = new ByteArrayOutputStream(); + + byte[] buffer = new byte[BUFFER_SIZE]; + int len; + while ((len = colorInputStream.read(buffer)) > -1) { + this.colorInputStreamCopy.write(buffer, 0, len); + } + this.colorInputStreamCopy.flush(); + } + return this; + } + + /** + * @return the async + * @see #async + */ + public boolean isAsync() { + return async; + } + + /** + * @param async + * the async to set + * @see #async + * @return {@link CreateLayoutParams} object + */ + public CreateLayoutParams async(boolean async) { + this.async = async; + return this; + } + + /** + * @return the description + * @see #description + */ + public String getDescription() { + return description; + } + + /** + * @param description + * the description to set + * @see #description + * @return {@link CreateLayoutParams} object + */ + public CreateLayoutParams description(String description) { + this.description = description; + return this; + } + + /** + * + * @return {@link #colorSchemaType} + */ + public ColorSchemaType getColorSchemaType() { + return colorSchemaType; + } + + /** + * @param colorSchemaType + * the colorSchemaType to set + * @see #colorSchemaType + * @return {@link CreateLayoutParams} object + */ + public CreateLayoutParams colorSchemaType(ColorSchemaType colorSchemaType) { + this.colorSchemaType = colorSchemaType; + return this; + } + + /** + * @return the layoutFileName + * @see #layoutFileName + */ + public String getLayoutFileName() { + return layoutFileName; + } + + /** + * @param layoutFileName + * the layoutFileName to set + * @return {@link CreateLayoutParams} object + * @see #layoutFileName + */ + public CreateLayoutParams layoutFileName(String layoutFileName) { + this.layoutFileName = layoutFileName; + return this; + } + } + + /** + * Returns true if user can add layout to the model. + * + * @param model + * to which model user wants to add layout + * @param user + * who wants to add layout + * @return <code>true</code> if user can add layout, <code>false</code> + * otherwise + */ + boolean userCanAddLayout(Model model, User user); + + /** + * Returns true if user can remove layout from the model. + * + * @param layout + * which layout user want to remove + * @param user + * who wants to remove layout + * @return <code>true</code> if user can remove layout, <code>false</code> + * otherwise + */ + boolean userCanRemoveLayout(LayoutView layout, User user); + + /** + * Returns list of custom layouts. + * + * @param model + * model where the layouts lay on + * @param user + * user who asks for the layouts + * @return list of custom layouts + */ + List<LayoutView> getCustomLayouts(Model model, User user, Boolean publicOverlay, User creator); + + /** + * Returns list of general publicly available layouts. + * + * @param model + * model where the layouts lay on + * @return list of custom layouts + */ + List<LayoutView> getGeneralLayouts(Model model); + + /** + * Removes layout from the system. + * + * @param layout + * layout to remove + * @param homeDir + * directory where the system is deployed + * @throws IOException + * thrown when there are problems with removing layout files + */ + void removeLayout(LayoutView layout, String homeDir) throws IOException; + + /** + * Updates data about the layout. + * + * @param layout + * layout to update + */ + void updateLayout(LayoutView layout); + + /** + * Adds view privilege to the layout for the user. + * + * @param layout + * layout for privilege + * @param user + * who should own the privilege + */ + void addViewPrivilegeToLayout(LayoutView layout, User user); + + /** + * Removes view privilege to the layout from the user. + * + * @param layout + * layout for privilege remove + * @param user + * who shouldn't have the privilege + */ + void dropViewPrivilegeFromLayout(LayoutView layout, User user); + + /** + * Create layout based on the data in the parameter. + * + * @param params + * list of {@link CreateLayoutParams params} necessary to create layout + * @return object that refers to created layout + * @throws IOException + * thrown when there are problems with files + * @throws InvalidColorSchemaException + * if the coloring source is invalid + * @throws CommandExecutionException + */ + LayoutView createLayout(CreateLayoutParams params) throws IOException, InvalidColorSchemaException; + + /** + * Create layout based on the data in the parameter. Layout will contain set of + * images that can be further visualized in goolge maps api. + * + * @param params + * list of {@link CreateLayoutParams params} necessary to create layout + * @return object that refers to created layout + * @throws IOException + * thrown when there are problems with files + * @throws CommandExecutionException + * if the coloring source is invalid + * @throws InvalidColorSchemaException + * if the coloring source is invalid + */ + LayoutView createLayoutWithImages(CreateLayoutParams params) + throws IOException, CommandExecutionException, InvalidColorSchemaException; + + /** + * Returns number of still available custom layouts for the user. + * + * @param user + * user for which the number of available custom layouts will be + * returned + * @return number of available custom layouts + */ + long getAvailableCustomLayoutsNumber(User user); + + /** + * Returns layout identified by name and model. + * + * @param model + * model where the layouts lay on + * @param name + * name of the layout + * @return layout + */ + LayoutView getLayoutByName(Model model, String name); + + /** + * Returns byte array containing data from original input file that was used to + * generate the layout. + * + * @param layout + * layout for which we want to retrieve original file data + * @return original data file for given layout, if such file is not stored in + * database (compatibility reasons) then null is returned + * @throws SecurityException + */ + byte[] getInputDataForLayout(LayoutView layout, String token) throws SecurityException; + + /** + * Returns a list of {@link LightLayoutAliasView aliases} that are visualized in + * a {@link lcsb.mapviewer.model.map.layout.Layout}. + * + * @param model + * model where data is located + * @param layoutId + * identifier of the layout + * @return a list of {@link LightLayoutAliasView aliases} that are visualized in + * a {@link lcsb.mapviewer.model.map.layout.Layout} + * @throws SecurityException + */ + List<LightLayoutAliasView> getAliasesForLayout(Model model, int layoutId, String token) throws SecurityException; + + /** + * Returns a list of {@link LightLayoutReactionView reactions} that are + * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout}. + * + * @param model + * model where data is located + * @param layoutId + * identifier of the layout + * @return a list of {@link LightLayoutReactionView reactions} that are + * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout} + * @throws SecurityException + */ + List<LightLayoutReactionView> getReactionsForLayout(Model model, int layoutId, String token) throws SecurityException; + + /** + * Returns mapping between {@link lcsb.mapviewer.model.map.species.Element + * Alias}/ {@link lcsb.mapviewer.model.map.reaction.Reaction Reaction} and + * {@link ColorSchema} used for coloring object in the layout given in the + * parameter. + * + * @param model + * model where data is lcoated + * @param layoutId + * identifier of the layout + * @return a list of {@link LightLayoutReactionView reactions} that are + * visualized in a {@link lcsb.mapviewer.model.map.layout.Layout} + * @throws SecurityException + */ + Map<Object, ColorSchema> getElementsForLayout(Model model, Integer layoutId, String token) throws SecurityException; + + /** + * Returns a list of {@link FullLayoutAliasView aliases} that are visualized in + * a {@link lcsb.mapviewer.model.map.layout.Layout} and have given identifiers. + * + * @param model + * model where data is located + * @param layoutId + * identifier of the layout + * @param identifiers + * list of alias identifiers in a given submodel. Every {@link Pair} + * contains information about {@link Model#getId() model identifier} + * (in {@link Pair#left}) and + * {@link lcsb.mapviewer.model.map.species.Element#getId() alias + * identifier} (in {@link Pair#right}). + * @return a list of {@link LightLayoutAliasView aliases} that are visualized in + * a {@link lcsb.mapviewer.model.map.layout.Layout} + * @throws SecurityException + */ + List<FullLayoutAliasView> getFullAliasesForLayoutByIds(Model model, List<Pair<Integer, Integer>> identifiers, + int layoutId, String token) throws SecurityException; + + FullLayoutAliasView getFullAliasForLayout(Model model, Integer id, int layoutId, String token) + throws SecurityException; + + FullLayoutReactionView getFullReactionForLayout(Model model, Integer id, int layoutId, String token) + throws SecurityException; + + /** + * Returns {@link EmailSender} used by the service. + * + * @return {@link EmailSender} used by the service + */ + EmailSender getEmailSender(); + + /** + * Sets {@link EmailSender} used by the service. + * + * @param emailSender + * {@link EmailSender} used by the service + */ + void setEmailSender(EmailSender emailSender); + + List<LayoutView> getCustomLayouts(Model model, String token, Boolean publicOverlay, User creator) + throws SecurityException; + + LayoutView getLayoutById(int overlayId, String token) throws SecurityException; + + Layout getLayoutDataById(int overlayId, String authenticationToken) throws SecurityException; + + boolean userCanRemoveLayout(LayoutView layout, String authenticationToken) throws SecurityException; } diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/IModelService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/IModelService.java index 53fda094d003d47b8f2d2a0f95531517194f9227..57495869e7ca7959078d9ee7cc9ba1d7148c1ab4 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IModelService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IModelService.java @@ -7,9 +7,9 @@ import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelData; import lcsb.mapviewer.model.user.User; +import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.search.data.LightAliasView; import lcsb.mapviewer.services.search.data.LightReactionView; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ModelView; import lcsb.mapviewer.services.view.ProjectView; @@ -28,8 +28,9 @@ public interface IModelService { * @param projectId * {@link lcsb.mapviewer.model.Project#projectId project identifier} * @return the newest model for the project + * @throws SecurityException */ - Model getLastModelByProjectId(String projectId, AuthenticationToken token); + Model getLastModelByProjectId(String projectId, String token) throws SecurityException; /** * Caches information about all pubmed articles for the given model. @@ -126,5 +127,5 @@ public interface IModelService { */ List<LightReactionView> getLightReactionsByIds(Model model, List<Pair<Integer, Integer>> identifiers); - void updateModel(ModelData model, AuthenticationToken token); + void updateModel(ModelData model, String token) throws SecurityException; } diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/IProjectService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/IProjectService.java index b802cfe8897af65cc9a6d99b1b2af672d19c5806..aaf3bbf5d8a6a7a3a0e14a322ab9fe79a526c020 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IProjectService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IProjectService.java @@ -11,7 +11,6 @@ import lcsb.mapviewer.model.user.UserAnnotatorsParam; import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.UserAccessException; import lcsb.mapviewer.services.utils.CreateProjectParams; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ProjectView; /** @@ -29,8 +28,9 @@ public interface IProjectService { * {@link Project#projectId project identifier} * @return project with an identifier given as parameter. Null if such project * doesn't exist. + * @throws SecurityException */ - Project getProjectByProjectId(String projectId, AuthenticationToken token) throws UserAccessException; + Project getProjectByProjectId(String projectId, String token) throws UserAccessException, SecurityException; /** * Checks if project with a given {@link Project#projectId identifier} exists. @@ -46,15 +46,17 @@ public interface IProjectService { * Returns list of all projects. * * @return list of all projects. + * @throws SecurityException */ - List<Project> getAllProjects(AuthenticationToken token); + List<Project> getAllProjects(String token) throws SecurityException; /** * Returns a list of Project views for all projects. * * @return list of Project views for all projects + * @throws SecurityException */ - List<ProjectView> getAllProjectViews(AuthenticationToken token); + List<ProjectView> getAllProjectViews(String token) throws SecurityException; /** * Updates project. @@ -74,10 +76,9 @@ public interface IProjectService { * information about project to remove * @param async * should the operation be done asynchronously - * @throws UserAccessException + * @throws SecurityException */ - void removeProject(ProjectView projectView, String homeDir, boolean async, AuthenticationToken token) - throws UserAccessException; + void removeProject(ProjectView projectView, String homeDir, boolean async, String token) throws SecurityException; /** * Removes project from the system. @@ -88,10 +89,9 @@ public interface IProjectService { * object to remove * @param async * should the operation be done asynchronously - * @throws UserAccessException + * @throws SecurityException */ - void removeProject(Project project, String homeDir, boolean async, AuthenticationToken token) - throws UserAccessException; + void removeProject(Project project, String homeDir, boolean async, String token) throws SecurityException; /** * Gets view of the project by the {@link Project#projectId project identifier}. @@ -100,8 +100,9 @@ public interface IProjectService { * {@link Project#projectId project identifier} * @return view of the project * @throws UserAccessException + * @throws SecurityException */ - ProjectView getProjectViewByProjectId(String projectId, AuthenticationToken token) throws UserAccessException; + ProjectView getProjectViewByProjectId(String projectId, String token) throws UserAccessException, SecurityException; /** * Adds project to the system. @@ -118,8 +119,9 @@ public interface IProjectService { * database identifier of the project * @return project view * @throws UserAccessException + * @throws SecurityException */ - ProjectView getProjectViewById(Integer id, AuthenticationToken token) throws UserAccessException; + ProjectView getProjectViewById(Integer id, String token) throws UserAccessException, SecurityException; /** * Creates project using give parameters. See {@link CreateProjectParams}. diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/IReferenceGenomeService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/IReferenceGenomeService.java index a588d82b4373573a0d96437013b223ea6148aad1..1857baf300e4fd52b8de9b59794c78b985c5c244 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IReferenceGenomeService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IReferenceGenomeService.java @@ -9,7 +9,6 @@ import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.layout.ReferenceGenome; import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ReferenceGenomeView; /** @@ -20,129 +19,131 @@ import lcsb.mapviewer.services.view.ReferenceGenomeView; */ public interface IReferenceGenomeService { - /** - * Adds reference genome to the system. - * - * @param type - * {@link ReferenceGenomeType type} of reference genome - * @param organism - * organism for which renference genome is added - * @param version - * version of the reference genome - * @param customUrl - * url from which reference genome should be downloaded - * @throws IOException - * thrown when there is a problem with downloading file - * @throws URISyntaxException - * thrown when url is invalid - * @throws ReferenceGenomeConnectorException - * thrown when reference genome already exists or there is problem - * wirh adding genome - */ - void addReferenceGenome(ReferenceGenomeType type, MiriamData organism, String version, String customUrl) - throws IOException, URISyntaxException, ReferenceGenomeConnectorException; + /** + * Adds reference genome to the system. + * + * @param type + * {@link ReferenceGenomeType type} of reference genome + * @param organism + * organism for which renference genome is added + * @param version + * version of the reference genome + * @param customUrl + * url from which reference genome should be downloaded + * @throws IOException + * thrown when there is a problem with downloading file + * @throws URISyntaxException + * thrown when url is invalid + * @throws ReferenceGenomeConnectorException + * thrown when reference genome already exists or there is problem + * wirh adding genome + */ + void addReferenceGenome(ReferenceGenomeType type, MiriamData organism, String version, String customUrl) + throws IOException, URISyntaxException, ReferenceGenomeConnectorException; - /** - * Returns list of organisms available for {@link ReferenceGenomeType - * reference genome type}. - * - * @param type - * type of reference genome - * @return list of available organisms - * @throws ReferenceGenomeConnectorException - * thrown when there is a problem with accessing information about - * reference genoems - */ - List<MiriamData> getOrganismsByReferenceGenomeType(ReferenceGenomeType type) throws ReferenceGenomeConnectorException; + /** + * Returns list of organisms available for {@link ReferenceGenomeType reference + * genome type}. + * + * @param type + * type of reference genome + * @return list of available organisms + * @throws ReferenceGenomeConnectorException + * thrown when there is a problem with accessing information about + * reference genoems + */ + List<MiriamData> getOrganismsByReferenceGenomeType(ReferenceGenomeType type) throws ReferenceGenomeConnectorException; - /** - * Returns list of genome versions available for organism of specific - * {@link ReferenceGenomeType reference genome type}. - * - * @param type - * type of reference genome - * @param organism - * organism for which we check genome versions - * @return list of available organisms - * @throws ReferenceGenomeConnectorException - * thrown when there is a problem with accessing information about - * reference genoems - */ - List<String> getAvailableGenomeVersions(ReferenceGenomeType type, MiriamData organism) throws ReferenceGenomeConnectorException; + /** + * Returns list of genome versions available for organism of specific + * {@link ReferenceGenomeType reference genome type}. + * + * @param type + * type of reference genome + * @param organism + * organism for which we check genome versions + * @return list of available organisms + * @throws ReferenceGenomeConnectorException + * thrown when there is a problem with accessing information about + * reference genoems + */ + List<String> getAvailableGenomeVersions(ReferenceGenomeType type, MiriamData organism) + throws ReferenceGenomeConnectorException; - /** - * Returns url to the file that describes genome. - * - * @param type - * type of reference genome - * @param organism - * organism of reference genome - * @param version - * version of reference genome - * @return url to the file that describes genome - */ - String getUrlForGenomeVersion(ReferenceGenomeType type, MiriamData organism, String version); + /** + * Returns url to the file that describes genome. + * + * @param type + * type of reference genome + * @param organism + * organism of reference genome + * @param version + * version of reference genome + * @return url to the file that describes genome + */ + String getUrlForGenomeVersion(ReferenceGenomeType type, MiriamData organism, String version); - /** - * Returns list of all downladed reference genomes. - * - * @return list of all downladed reference genomes - */ - List<ReferenceGenome> getDownloadedGenomes(); + /** + * Returns list of all downladed reference genomes. + * + * @return list of all downladed reference genomes + */ + List<ReferenceGenome> getDownloadedGenomes(); - /** - * Removes reference genome from the system. - * - * @param genome - * genome to be removed - * @throws IOException - * thrown when there is a problem with removing genome - */ - void removeGenome(ReferenceGenome genome) throws IOException; + /** + * Removes reference genome from the system. + * + * @param genome + * genome to be removed + * @throws IOException + * thrown when there is a problem with removing genome + */ + void removeGenome(ReferenceGenome genome) throws IOException; - /** - * Adds gene mapping to refernce genome. - * - * @param referenceGenome - * reference genome where we add mapping - * @param name - * name of the mapping - * @param url - * url to the file that describes mapping - * @throws IOException - * thrown when there is a problem with downloading file - * @throws URISyntaxException - * thrown when url is invalid - * @throws ReferenceGenomeConnectorException - * thrown when there is a problem with manipulatinf information - * about reference genome - */ - void addReferenceGenomeGeneMapping(ReferenceGenome referenceGenome, String name, String url) - throws IOException, URISyntaxException, ReferenceGenomeConnectorException; + /** + * Adds gene mapping to refernce genome. + * + * @param referenceGenome + * reference genome where we add mapping + * @param name + * name of the mapping + * @param url + * url to the file that describes mapping + * @throws IOException + * thrown when there is a problem with downloading file + * @throws URISyntaxException + * thrown when url is invalid + * @throws ReferenceGenomeConnectorException + * thrown when there is a problem with manipulatinf information about + * reference genome + */ + void addReferenceGenomeGeneMapping(ReferenceGenome referenceGenome, String name, String url) + throws IOException, URISyntaxException, ReferenceGenomeConnectorException; - /** - * Removes gene mapping for reference genome. - * - * @param mapping - * mapping to be removed - * @throws IOException - * thrown when there is a problem with removing file - */ - void removeReferenceGenomeGeneMapping(ReferenceGenomeGeneMapping mapping) throws IOException; + /** + * Removes gene mapping for reference genome. + * + * @param mapping + * mapping to be removed + * @throws IOException + * thrown when there is a problem with removing file + */ + void removeReferenceGenomeGeneMapping(ReferenceGenomeGeneMapping mapping) throws IOException; - /** - * Returns {@link ReferenceGenomeView} for specific reference genome. - * - * @param organism - * organism of reference genome - * @param genomeType - * reference genome type - * @param version - * version of the reference genome - * @return {@link ReferenceGenomeView} for specific reference genome - */ - ReferenceGenomeView getReferenceGenomeViewByParams(MiriamData organism, ReferenceGenomeType genomeType, String version); + /** + * Returns {@link ReferenceGenomeView} for specific reference genome. + * + * @param organism + * organism of reference genome + * @param genomeType + * reference genome type + * @param version + * version of the reference genome + * @return {@link ReferenceGenomeView} for specific reference genome + */ + ReferenceGenomeView getReferenceGenomeViewByParams(MiriamData organism, ReferenceGenomeType genomeType, + String version); - ReferenceGenomeView getReferenceGenomeViewByParams(MiriamData organism, ReferenceGenomeType genomeType, String version, - AuthenticationToken authenticationToken); + ReferenceGenomeView getReferenceGenomeViewByParams(MiriamData organism, ReferenceGenomeType genomeType, + String version, String authenticationToken); } diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java index 5cc8b181b26587cdb38e4360d3edae6343d669a9..b0078cba8cceb46ada46588a90b7eb7e046bddb2 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java @@ -8,7 +8,6 @@ import lcsb.mapviewer.model.user.BasicPrivilege; import lcsb.mapviewer.model.user.PrivilegeType; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.services.SecurityException; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.UserView; /** @@ -25,10 +24,10 @@ public interface IUserService { * user login * @param password * plan password - * @return {@link AuthenticationToken} if credentials are valid, + * @return {@link String} containing session id if credentials are valid, * <code>null</code> otherwise */ - AuthenticationToken login(String login, String password); + String login(String login, String password); /** * Returns user by login. @@ -50,8 +49,6 @@ public interface IUserService { */ boolean userHasPrivilege(User user, PrivilegeType type); - boolean userHasPrivilege(String token, PrivilegeType type) throws SecurityException; - /** * Returns level of the user privilege. * @@ -241,32 +238,26 @@ public interface IUserService { */ ColorExtractor getColorExtractorForUser(User user); - User getUserByToken(AuthenticationToken token); - User getUserByToken(String token) throws SecurityException; - AuthenticationToken getToken(String token) throws SecurityException; - - boolean userHasPrivilege(AuthenticationToken token, PrivilegeType type, Object object); + boolean userHasPrivilege(String token, PrivilegeType type, Object object) throws SecurityException; void logout(String tokenString) throws SecurityException; - void logout(AuthenticationToken token); - - boolean userHasPrivilege(AuthenticationToken token, PrivilegeType addMap); + boolean userHasPrivilege(String token, PrivilegeType addMap) throws SecurityException; - User getUserById(String creatorId, AuthenticationToken authenticationToken) throws SecurityException; + User getUserById(String creatorId, String token) throws SecurityException; - List<User> getUsers(AuthenticationToken token) throws SecurityException; + List<User> getUsers(String token) throws SecurityException; - void setUserPrivilege(User modifiedUser, PrivilegeType type, Object privilegeToSet, - AuthenticationToken authenticationToken) throws SecurityException; + void setUserPrivilege(User modifiedUser, PrivilegeType type, Object privilegeToSet, String authenticationToken) + throws SecurityException; void setUserPrivilege(User modifiedUser, PrivilegeType type, Object privilegeToSet, Integer objectId, - AuthenticationToken authenticationToken) throws SecurityException; + String authenticationToken) throws SecurityException; - void updateUser(User modifiedUser, AuthenticationToken authenticationToken) throws SecurityException; + void updateUser(User modifiedUser, String authenticationToken) throws SecurityException; - AuthenticationToken login(String login, String password, String id); + String login(String login, String password, String id); } diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/CreateProjectParams.java b/service/src/main/java/lcsb/mapviewer/services/utils/CreateProjectParams.java index 8a253f27423751210ba30cb81ff757af5577968c..451ed2a5d46f8fef5f6759eaa58b6a28df3ab193 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/CreateProjectParams.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/CreateProjectParams.java @@ -16,14 +16,12 @@ import java.util.Set; import org.apache.commons.io.IOUtils; import org.primefaces.model.TreeNode; -import lcsb.mapviewer.annotation.services.annotators.AnnotatorParamDefinition; import lcsb.mapviewer.converter.IConverter; import lcsb.mapviewer.converter.zip.ZipEntryFile; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.user.UserAnnotatorsParam; import lcsb.mapviewer.services.overlay.AnnotatedObjectTreeRow; -import lcsb.mapviewer.services.view.AuthenticationToken; /** * Set of parameters used during creation of new project. @@ -143,7 +141,7 @@ public class CreateProjectParams { */ private String projectDir; - private AuthenticationToken authenticationToken; + private String authenticationToken; /** * Map that contains information what kind of annotators should be used for @@ -162,11 +160,11 @@ public class CreateProjectParams { * obligatory for which class. */ private Map<Class<? extends BioEntity>, Set<MiriamType>> requiredAnnotations = null; - + /** * List with annotators parameters. */ - private List<UserAnnotatorsParam> annotatorsParams = null; + private List<UserAnnotatorsParam> annotatorsParams = new ArrayList<>(); /** * @param projectId @@ -551,27 +549,27 @@ public class CreateProjectParams { public void setAnnotatorsMap(Map<Class<?>, List<String>> annotatorsMap) { this.annotatorsMap = annotatorsMap; } - + /** * @return the annotators params */ public List<UserAnnotatorsParam> getAnnotatorsParams() { return annotatorsParams; } - - public Map<Class<?>, List<UserAnnotatorsParam>> getAnnotatorsParamsAsMap(){ - - Map<Class<?>, List<UserAnnotatorsParam>> paramsMap = new HashMap<>(); - - for (UserAnnotatorsParam param: getAnnotatorsParams()){ - Class<?> annotatorClassName = param.getAnnotatorClassName(); - if (!paramsMap.containsKey(annotatorClassName)) { - paramsMap.put(annotatorClassName, new ArrayList<>()); - } - paramsMap.get(annotatorClassName).add(param); - } - - return paramsMap; + + public Map<Class<?>, List<UserAnnotatorsParam>> getAnnotatorsParamsAsMap() { + + Map<Class<?>, List<UserAnnotatorsParam>> paramsMap = new HashMap<>(); + + for (UserAnnotatorsParam param : getAnnotatorsParams()) { + Class<?> annotatorClassName = param.getAnnotatorClassName(); + if (!paramsMap.containsKey(annotatorClassName)) { + paramsMap.put(annotatorClassName, new ArrayList<>()); + } + paramsMap.get(annotatorClassName).add(param); + } + + return paramsMap; } /** @@ -765,7 +763,7 @@ public class CreateProjectParams { * @return the authenticationToken * @see #authenticationToken */ - public AuthenticationToken getAuthenticationToken() { + public String getAuthenticationToken() { return authenticationToken; } @@ -774,7 +772,7 @@ public class CreateProjectParams { * the authenticationToken to set * @see #authenticationToken */ - public CreateProjectParams authenticationToken(AuthenticationToken authenticationToken) { + public CreateProjectParams authenticationToken(String authenticationToken) { this.authenticationToken = authenticationToken; return this; diff --git a/service/src/main/java/lcsb/mapviewer/services/view/AuthenticationToken.java b/service/src/main/java/lcsb/mapviewer/services/view/AuthenticationToken.java deleted file mode 100644 index 0c826590405fd40e0e271632fe60303855c13090..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/AuthenticationToken.java +++ /dev/null @@ -1,43 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.math.BigInteger; -import java.security.SecureRandom; -import java.text.SimpleDateFormat; -import java.util.Calendar; - -public class AuthenticationToken { - private String id; -// private Calendar expires; - - public AuthenticationToken() { - this(new BigInteger(130, new SecureRandom()).toString(32)); - } - - public AuthenticationToken(String id) { - this.id = id; -// expires = Calendar.getInstance(); -// expires.add(Calendar.HOUR, 2); - } - - /** - * @return the id - * @see #id - */ - public String getId() { - return id; - } - -// /** -// * @return the expires -// * @see #expires -// */ -// public Calendar getExpires() { -// return expires; -// } -// -// @Override -// public String toString() { -// return getId() + ", expirese: " + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(expires.getTime()); -// } -// -} diff --git a/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java b/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java index b7eaa4225800da8e01abf213f9944b4b7d6705b5..118a8d67e51e24e700449ceab05c1d1f4e9feabf 100644 --- a/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java +++ b/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java @@ -86,6 +86,7 @@ import lcsb.mapviewer.services.search.db.drug.IDrugService; @ContextConfiguration(locations = { "/applicationContext-annotation.xml", // "/applicationContext-persist.xml", // "/applicationContext-service.xml", // + "/test-applicationContext.xml", // "/dataSource.xml", // }) @RunWith(SpringJUnit4ClassRunner.class) diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java index ef435d1a1c393df4a69a7597a60ff845caab5dd9..4f8644c3d0fc39cf56a41712bda473bd3bcbe6e2 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java @@ -26,223 +26,232 @@ import lcsb.mapviewer.model.user.PrivilegeType; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.services.ServiceTestFunctions; import lcsb.mapviewer.services.search.comment.FullCommentView; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.CommentView; @Rollback(true) public class CommentServiceTest extends ServiceTestFunctions { - static Logger logger = Logger.getLogger(CommentServiceTest.class); - Model model; - Project project; - Element alias; - Element alias2; - private String projectId = "Some_id"; - - @Before - public void setUp() throws Exception { - try { - dbUtils.setAutoFlush(true); - project = projectDao.getProjectByProjectId(projectId); - if (project != null) { - projectDao.delete(project); - } - project = new Project(); - project.setProjectId(projectId); - model = getModelForFile("testFiles/centeredAnchorInModifier.xml", false); - model.setTileSize(128); - Set<Element> aliases = model.getElements(); - alias = null; - alias2 = null; - for (Element nAlias : aliases) { - alias2 = alias; - alias = nAlias; - } - project.addModel(model); - projectDao.add(project); - - - projectDao.evict(project); - modelDao.evict(model); - - project = projectDao.getById(project.getId()); - model = new ModelFullIndexed(modelDao.getLastModelForProjectIdentifier(project.getProjectId(), false)); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @After - public void tearDown() throws Exception { - try { - projectDao.delete(project); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testGetAgregatedComments() throws Exception { - try { - commentService.addComment("John Doe", "a@a.pl", "Conteneta 1", model, new Point2D.Double(0, 1), alias, false, model); - commentService.addComment("John Doe", "a@a.pl", "Contenetb 2", model, new Point2D.Double(0, 2), alias, false, model); - commentService.addComment("John Doe", "a@a.pl", "Contenetc 3", model, new Point2D.Double(0, 3), alias2, false, model); - commentService.addComment("John Doe", "a@a.pl", "Contenetc 4", model, new Point2D.Double(0, 4), null, false, model); - commentService.addComment("John Doe", "a@a.pl", "Contenetc 5", model, new Point2D.Double(0, 5), null, false, model); - CommentService service = new CommentService(); - service.setCommentDao(commentDao); - List<List<Comment>> comments = service.getAgregatedComments(model, null); - assertEquals(4, comments.size()); - int size = 0; - for (List<Comment> list : comments) { - size += list.size(); - } - assertEquals(5, size); - - List<Comment> allComments = commentDao.getCommentByModel(model, null, null); - assertEquals(5, allComments.size()); - for (Comment comment : allComments) { - commentDao.delete(comment); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAgregatedCommentsIntoMarker() throws Exception { - try { - commentService.addComment("John Doe", "a@a.pl", "Conteneta 1", model, new Point2D.Double(0, 1), alias, false, model); - commentService.addComment("John Doe", "a@a.pl", "Contenetb 2", model, new Point2D.Double(0, 2), alias, false, model); - commentService.addComment("John Doe", "a@a.pl", "Contenetc 3", model, new Point2D.Double(0, 3), alias2, false, model); - commentService.addComment("John Doe", "a@a.pl", "Contenetc 4", model, new Point2D.Double(0, 4), null, false, model); - commentService.addComment("John Doe", "a@a.pl", "Contenetc 5", model, new Point2D.Double(0, 5), null, false, model); - CommentService service = new CommentService(); - service.setCommentDao(commentDao); - List<List<Comment>> comments = service.getAgregatedComments(model, null); - assertEquals(4, comments.size()); - - List<FullCommentView> markers = service.agregatedCommentsIntoMarker(comments, model); - assertNotNull(markers); - assertEquals(4, markers.size()); - - assertEquals(2, markers.get(0).getComments().size()); - assertEquals("Conteneta 1", markers.get(0).getComments().get(0).getRight()); - assertEquals(1, markers.get(1).getComments().size()); - - List<Comment> allComments = commentDao.getCommentByModel(model, null, null); - assertEquals(5, allComments.size()); - for (Comment comment : allComments) { - commentDao.delete(comment); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddComment() throws Exception { - try { - - long counter = commentService.getCommentCount(); - Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), null, false, model); - long counter2 = commentService.getCommentCount(); - assertEquals(counter + 1, counter2); - commentDao.delete(feedback); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddCommentForReaction() throws Exception { - try { - - long counter = commentService.getCommentCount(); - Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), model.getReactions().iterator().next(), false, model); - long counter2 = commentService.getCommentCount(); - assertEquals(counter + 1, counter2); - commentDao.delete(feedback); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAddCommentForAlias() throws Exception { - try { - Element alias = model.getElementByElementId("sa1"); - long counter = commentService.getCommentCount(); - Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), alias, false, model); - long counter2 = commentService.getCommentCount(); - assertEquals(counter + 1, counter2); - commentDao.delete(feedback); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testReactionComment() throws Exception { - try { - User admin = userService.getUserByLogin("admin"); - userService.setUserPrivilege(admin, new ObjectPrivilege(project, 1, PrivilegeType.VIEW_PROJECT, admin)); - - Reaction reaction = model.getReactionByReactionId("re3"); - Comment comment = commentService.addComment("John Doe", "a@a.pl", "Conteneta 1", model, new Point2D.Double(0, 1), reaction, false, model); - - AuthenticationToken adminToken; - // assume that we have admin account with all the privileges - adminToken = userService.login("admin", "admin"); - - List<CommentView> views = commentService.getCommentsByMap(model, adminToken); - assertNotNull(views.get(0).getTitle()); - commentDao.delete(comment); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testComparePointCommentId() throws Exception { - try { - CommentService cs = new CommentService(); - assertTrue(cs.equalPoints("Point2D.Double[117.685546875, 204.6923828125001]", "(117.69, 204.69)")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testComparePointCommentId2() throws Exception { - try { - CommentService cs = new CommentService(); - assertFalse(cs.equalPoints("Point2D.Double[118.685546875, 204.6923828125001]", "(117.69, 204.69)")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testComparePointCommentId3() throws Exception { - try { - CommentService cs = new CommentService(); - assertFalse(cs.equalPoints("Point2D.Double[117.685546875, 205.6923828125001]", "(117.69, 204.69)")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + static Logger logger = Logger.getLogger(CommentServiceTest.class); + Model model; + Project project; + Element alias; + Element alias2; + private String projectId = "Some_id"; + + @Before + public void setUp() throws Exception { + try { + dbUtils.setAutoFlush(true); + project = projectDao.getProjectByProjectId(projectId); + if (project != null) { + projectDao.delete(project); + } + project = new Project(); + project.setProjectId(projectId); + model = getModelForFile("testFiles/centeredAnchorInModifier.xml", false); + model.setTileSize(128); + Set<Element> aliases = model.getElements(); + alias = null; + alias2 = null; + for (Element nAlias : aliases) { + alias2 = alias; + alias = nAlias; + } + project.addModel(model); + projectDao.add(project); + + projectDao.evict(project); + modelDao.evict(model); + + project = projectDao.getById(project.getId()); + model = new ModelFullIndexed(modelDao.getLastModelForProjectIdentifier(project.getProjectId(), false)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @After + public void tearDown() throws Exception { + try { + projectDao.delete(project); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testGetAgregatedComments() throws Exception { + try { + commentService.addComment("John Doe", "a@a.pl", "Conteneta 1", model, new Point2D.Double(0, 1), alias, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetb 2", model, new Point2D.Double(0, 2), alias, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetc 3", model, new Point2D.Double(0, 3), alias2, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetc 4", model, new Point2D.Double(0, 4), null, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetc 5", model, new Point2D.Double(0, 5), null, false, + model); + CommentService service = new CommentService(); + service.setCommentDao(commentDao); + List<List<Comment>> comments = service.getAgregatedComments(model, null); + assertEquals(4, comments.size()); + int size = 0; + for (List<Comment> list : comments) { + size += list.size(); + } + assertEquals(5, size); + + List<Comment> allComments = commentDao.getCommentByModel(model, null, null); + assertEquals(5, allComments.size()); + for (Comment comment : allComments) { + commentDao.delete(comment); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAgregatedCommentsIntoMarker() throws Exception { + try { + commentService.addComment("John Doe", "a@a.pl", "Conteneta 1", model, new Point2D.Double(0, 1), alias, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetb 2", model, new Point2D.Double(0, 2), alias, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetc 3", model, new Point2D.Double(0, 3), alias2, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetc 4", model, new Point2D.Double(0, 4), null, false, + model); + commentService.addComment("John Doe", "a@a.pl", "Contenetc 5", model, new Point2D.Double(0, 5), null, false, + model); + CommentService service = new CommentService(); + service.setCommentDao(commentDao); + List<List<Comment>> comments = service.getAgregatedComments(model, null); + assertEquals(4, comments.size()); + + List<FullCommentView> markers = service.agregatedCommentsIntoMarker(comments, model); + assertNotNull(markers); + assertEquals(4, markers.size()); + + assertEquals(2, markers.get(0).getComments().size()); + assertEquals("Conteneta 1", markers.get(0).getComments().get(0).getRight()); + assertEquals(1, markers.get(1).getComments().size()); + + List<Comment> allComments = commentDao.getCommentByModel(model, null, null); + assertEquals(5, allComments.size()); + for (Comment comment : allComments) { + commentDao.delete(comment); + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAddComment() throws Exception { + try { + + long counter = commentService.getCommentCount(); + Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), null, false, model); + long counter2 = commentService.getCommentCount(); + assertEquals(counter + 1, counter2); + commentDao.delete(feedback); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAddCommentForReaction() throws Exception { + try { + + long counter = commentService.getCommentCount(); + Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), + model.getReactions().iterator().next(), false, model); + long counter2 = commentService.getCommentCount(); + assertEquals(counter + 1, counter2); + commentDao.delete(feedback); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAddCommentForAlias() throws Exception { + try { + Element alias = model.getElementByElementId("sa1"); + long counter = commentService.getCommentCount(); + Comment feedback = commentService.addComment("a", "b", "c", model, new Point2D.Double(0, 0), alias, false, model); + long counter2 = commentService.getCommentCount(); + assertEquals(counter + 1, counter2); + commentDao.delete(feedback); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testReactionComment() throws Exception { + try { + User admin = userService.getUserByLogin("admin"); + userService.setUserPrivilege(admin, new ObjectPrivilege(project, 1, PrivilegeType.VIEW_PROJECT, admin)); + + Reaction reaction = model.getReactionByReactionId("re3"); + Comment comment = commentService.addComment("John Doe", "a@a.pl", "Conteneta 1", model, new Point2D.Double(0, 1), + reaction, false, model); + + // assume that we have admin account with all the privileges + String adminToken = userService.login("admin", "admin"); + + List<CommentView> views = commentService.getCommentsByMap(model, adminToken); + assertNotNull(views.get(0).getTitle()); + commentDao.delete(comment); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testComparePointCommentId() throws Exception { + try { + CommentService cs = new CommentService(); + assertTrue(cs.equalPoints("Point2D.Double[117.685546875, 204.6923828125001]", "(117.69, 204.69)")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testComparePointCommentId2() throws Exception { + try { + CommentService cs = new CommentService(); + assertFalse(cs.equalPoints("Point2D.Double[118.685546875, 204.6923828125001]", "(117.69, 204.69)")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testComparePointCommentId3() throws Exception { + try { + CommentService cs = new CommentService(); + assertFalse(cs.equalPoints("Point2D.Double[117.685546875, 205.6923828125001]", "(117.69, 204.69)")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java index ca85d27c3a208e4abbd7c949575e776baaa96e46..3e3cc18f68168b3cebf88b489fd261cb3ef847d6 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java @@ -39,7 +39,6 @@ import lcsb.mapviewer.services.interfaces.ILayoutService.CreateLayoutParams; import lcsb.mapviewer.services.search.layout.LightLayoutAliasView; import lcsb.mapviewer.services.search.layout.LightLayoutReactionView; import lcsb.mapviewer.services.utils.EmailSender; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.LayoutView; public class LayoutServiceTest extends ServiceTestFunctions { @@ -60,7 +59,7 @@ public class LayoutServiceTest extends ServiceTestFunctions { ILayoutService layoutService; // assume that we have admin account with all the privileges - AuthenticationToken adminToken; + String adminToken; @Before public void setUp() throws Exception { @@ -362,7 +361,7 @@ public class LayoutServiceTest extends ServiceTestFunctions { layoutService.createLayout(params); - AuthenticationToken token = userService.login(user.getLogin(), "passwd"); + String token = userService.login(user.getLogin(), "passwd"); Project pr2 = projectService.getProjectByProjectId(localProject.getProjectId(), token); Model fromDbModel = pr2.getModels().iterator().next().getModel(); @@ -402,7 +401,7 @@ public class LayoutServiceTest extends ServiceTestFunctions { LayoutView row = layoutService.createLayout(params); - AuthenticationToken token = userService.login(user.getLogin(), "passwd"); + String token = userService.login(user.getLogin(), "passwd"); assertNotNull(row); assertNotNull(row.getIdObject()); @@ -440,7 +439,7 @@ public class LayoutServiceTest extends ServiceTestFunctions { LayoutView row = layoutService.createLayout(params); - AuthenticationToken token = userService.login(user.getLogin(), "passwd"); + String token = userService.login(user.getLogin(), "passwd"); List<LightLayoutAliasView> result = layoutService.getAliasesForLayout(model, row.getIdObject(), token); diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/ModelServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/ModelServiceTest.java index 8ba0310fdeb3adec3616b12484db01e264cc3f3d..11cc1b98006d3ffbf892157e35d3f2b6fef8575d 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/ModelServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/ModelServiceTest.java @@ -27,140 +27,139 @@ import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.services.ServiceTestFunctions; import lcsb.mapviewer.services.interfaces.IModelService; import lcsb.mapviewer.services.search.data.LightAliasView; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ProjectView; @Rollback(true) public class ModelServiceTest extends ServiceTestFunctions { - static Logger logger = Logger.getLogger(ModelServiceTest.class); - @Autowired - IModelService modelService; - - @Autowired - PubmedParser backend; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testRemoveModel() throws Exception { - try { - String directory = "test_directory"; - String projectId = "Some_id"; - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - - Model model = getModelForFile("testFiles/sample.xml", false); - model.addLayout(new Layout("test", directory, false)); - - project.addModel(model); - projectDao.update(project); - - MapGenerator generator = new MapGenerator(); - MapGeneratorParams params = generator.new MapGeneratorParams().model(model).directory(directory); - generator.generateMapImages(params); - - AuthenticationToken adminToken = userService.login("admin", "admin"); - ProjectView row = projectService.getProjectViewByProjectId(project.getProjectId(), adminToken); - projectService.removeProject(row, null, false, adminToken); - - File file = new File(directory); - assertFalse(file.exists()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testGetAliasByIds() throws Exception { - try { - Model model = getModelForFile("testFiles/sample.xml", false); - int counter = 0; - Element alias0 = null; - for (Element alias : model.getElements()) { - if (counter == 0) { - alias0 = alias; - } - alias.setId(counter++); - } - List<Pair<Integer, Integer>> identifiers = new ArrayList<>(); - identifiers.add(new Pair<Integer, Integer>(0, 0)); - List<LightAliasView> list = modelService.getLightAliasesByIds(model, identifiers); - assertEquals(1, list.size()); - assertEquals(alias0.getX(), list.get(0).getBounds().getX(), EPSILON); - assertEquals(alias0.getY(), list.get(0).getBounds().getY(), EPSILON); - assertEquals(alias0.getWidth(), list.get(0).getBounds().getWidth(), EPSILON); - assertEquals(alias0.getHeight(), list.get(0).getBounds().getHeight(), EPSILON); - identifiers.add(new Pair<Integer, Integer>(0, 5)); - list = modelService.getLightAliasesByIds(model, identifiers); - assertEquals(2, list.size()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testGetAliasByInvalidIds() throws Exception { - try { - Model model = getModelForFile("testFiles/db_problem_model.xml", false); - List<Pair<Integer, Integer>> identifiers = new ArrayList<>(); - // check with wrong alias id - identifiers.add(new Pair<Integer, Integer>(0, 1)); - try { - modelService.getLightAliasesByIds(model, identifiers); - fail(InvalidArgumentException.class + " expected"); - } catch (InvalidArgumentException e) { - - } - identifiers = new ArrayList<>(); - // check with wrong model id - identifiers.add(new Pair<Integer, Integer>(1, 0)); - try { - modelService.getLightAliasesByIds(model, identifiers); - fail(InvalidArgumentException.class + " expected"); - } catch (InvalidArgumentException e) { - - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testAddModel() throws Exception { - try { - String projectId = "Some_id"; - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - - Model model = getModelForFile("testFiles/db_problem_model.xml", false); - - project.addModel(model); - projectDao.update(project); - - AuthenticationToken adminToken = userService.login("admin", "admin"); - ProjectView row = projectService.getProjectViewByProjectId(project.getProjectId(), adminToken); - projectService.removeProject(row, null, false, adminToken); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } + static Logger logger = Logger.getLogger(ModelServiceTest.class); + @Autowired + IModelService modelService; + + @Autowired + PubmedParser backend; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testRemoveModel() throws Exception { + try { + String directory = "test_directory"; + String projectId = "Some_id"; + Project project = new Project(); + project.setProjectId(projectId); + projectDao.add(project); + + Model model = getModelForFile("testFiles/sample.xml", false); + model.addLayout(new Layout("test", directory, false)); + + project.addModel(model); + projectDao.update(project); + + MapGenerator generator = new MapGenerator(); + MapGeneratorParams params = generator.new MapGeneratorParams().model(model).directory(directory); + generator.generateMapImages(params); + + String adminToken = userService.login("admin", "admin"); + ProjectView row = projectService.getProjectViewByProjectId(project.getProjectId(), adminToken); + projectService.removeProject(row, null, false, adminToken); + + File file = new File(directory); + assertFalse(file.exists()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testGetAliasByIds() throws Exception { + try { + Model model = getModelForFile("testFiles/sample.xml", false); + int counter = 0; + Element alias0 = null; + for (Element alias : model.getElements()) { + if (counter == 0) { + alias0 = alias; + } + alias.setId(counter++); + } + List<Pair<Integer, Integer>> identifiers = new ArrayList<>(); + identifiers.add(new Pair<Integer, Integer>(0, 0)); + List<LightAliasView> list = modelService.getLightAliasesByIds(model, identifiers); + assertEquals(1, list.size()); + assertEquals(alias0.getX(), list.get(0).getBounds().getX(), EPSILON); + assertEquals(alias0.getY(), list.get(0).getBounds().getY(), EPSILON); + assertEquals(alias0.getWidth(), list.get(0).getBounds().getWidth(), EPSILON); + assertEquals(alias0.getHeight(), list.get(0).getBounds().getHeight(), EPSILON); + identifiers.add(new Pair<Integer, Integer>(0, 5)); + list = modelService.getLightAliasesByIds(model, identifiers); + assertEquals(2, list.size()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testGetAliasByInvalidIds() throws Exception { + try { + Model model = getModelForFile("testFiles/db_problem_model.xml", false); + List<Pair<Integer, Integer>> identifiers = new ArrayList<>(); + // check with wrong alias id + identifiers.add(new Pair<Integer, Integer>(0, 1)); + try { + modelService.getLightAliasesByIds(model, identifiers); + fail(InvalidArgumentException.class + " expected"); + } catch (InvalidArgumentException e) { + + } + identifiers = new ArrayList<>(); + // check with wrong model id + identifiers.add(new Pair<Integer, Integer>(1, 0)); + try { + modelService.getLightAliasesByIds(model, identifiers); + fail(InvalidArgumentException.class + " expected"); + } catch (InvalidArgumentException e) { + + } + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testAddModel() throws Exception { + try { + String projectId = "Some_id"; + Project project = new Project(); + project.setProjectId(projectId); + projectDao.add(project); + + Model model = getModelForFile("testFiles/db_problem_model.xml", false); + + project.addModel(model); + projectDao.update(project); + + String adminToken = userService.login("admin", "admin"); + ProjectView row = projectService.getProjectViewByProjectId(project.getProjectId(), adminToken); + projectService.removeProject(row, null, false, adminToken); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java index 67a3fcdfd6b2136bcbcbb6f580c2402ae194855d..de1196579ef6b56fe915a0cab70fa3b7d88b069a 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java @@ -55,7 +55,6 @@ import lcsb.mapviewer.services.ServiceTestFunctions; import lcsb.mapviewer.services.overlay.AnnotatedObjectTreeRow; import lcsb.mapviewer.services.utils.CreateProjectParams; import lcsb.mapviewer.services.utils.data.BuildInLayout; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ConfigurationView; import lcsb.mapviewer.services.view.ProjectView; @@ -72,7 +71,7 @@ public class ProjectServiceTest extends ServiceTestFunctions { ElementDao aliasDao; // assume that we have admin account with all the privileges - AuthenticationToken adminToken; + String adminToken; @Before public void setUp() throws Exception { @@ -84,10 +83,10 @@ public class ProjectServiceTest extends ServiceTestFunctions { } @Test - public void testGetProjectWithoutAccessToEverything() { + public void testGetProjectWithoutAccessToEverything() throws Exception { try { createUser(); - AuthenticationToken token = userService.login(user.getLogin(), "passwd"); + String token = userService.login(user.getLogin(), "passwd"); List<Project> projects = projectService.getAllProjects(token); assertNotNull(projects); } catch (Exception e) { @@ -97,7 +96,7 @@ public class ProjectServiceTest extends ServiceTestFunctions { } @Test - public void test() { + public void test() throws Exception { try { List<Project> projects = projectService.getAllProjects(adminToken); @@ -251,9 +250,6 @@ public class ProjectServiceTest extends ServiceTestFunctions { public void testCreateComplex() throws Exception { String projectId = "test_id"; try { - createUser(); - AuthenticationToken token = userService.login(user.getLogin(), "passwd"); - ZipEntryFile entry1 = new ModelZipEntryFile("main.xml", "main", true, false, SubmodelType.UNKNOWN); ZipEntryFile entry2 = new ModelZipEntryFile("s1.xml", "s1", false, false, SubmodelType.UNKNOWN); ZipEntryFile entry3 = new ModelZipEntryFile("s2.xml", "s2", false, false, SubmodelType.UNKNOWN); @@ -275,11 +271,11 @@ public class ProjectServiceTest extends ServiceTestFunctions { images(true).// async(false).// projectDir(tmpResultDir).// - addUser(user.getLogin(), "admin").// + addUser("admin", "admin").// analyzeAnnotations(true)); - Project project = projectService.getProjectByProjectId(projectId, token); + Project project = projectService.getProjectByProjectId(projectId, adminToken); - Model model = modelService.getLastModelByProjectId(projectId, token); + Model model = modelService.getLastModelByProjectId(projectId, adminToken); assertNotNull(model); assertEquals("main", model.getName()); assertEquals(3, model.getSubmodelConnections().size()); @@ -691,7 +687,7 @@ public class ProjectServiceTest extends ServiceTestFunctions { } assertTrue("Cannot find data mining information for the model", dmFound); projectService.removeProject(project, null, false, adminToken); - AuthenticationToken token = userService.login(Configuration.ANONYMOUS_LOGIN, null); + String token = userService.login(Configuration.ANONYMOUS_LOGIN, null); assertNull(projectService.getProjectByProjectId(name, token)); } catch (Exception e) { e.printStackTrace(); @@ -723,8 +719,7 @@ public class ProjectServiceTest extends ServiceTestFunctions { projectDir(tmpResultDir).// addUser("admin", "admin").// analyzeAnnotations(true)); - AuthenticationToken token = userService.login("admin", "admin"); - Project project = projectService.getProjectByProjectId(projectId, token); + Project project = projectService.getProjectByProjectId(projectId, adminToken); return project; } diff --git a/service/src/test/resources/test-applicationContext.xml b/service/src/test/resources/test-applicationContext.xml new file mode 100644 index 0000000000000000000000000000000000000000..9bd238746219dfb4bf7a443451209c5d8ecb9116 --- /dev/null +++ b/service/src/test/resources/test-applicationContext.xml @@ -0,0 +1,14 @@ +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:context="http://www.springframework.org/schema/context" + xsi:schemaLocation="http://www.springframework.org/schema/beans + http://www.springframework.org/schema/beans/spring-beans-4.0.xsd + http://www.springframework.org/schema/tx + http://www.springframework.org/schema/tx/spring-tx-4.0.xsd + http://www.springframework.org/schema/context + http://www.springframework.org/schema/context/spring-context-4.0.xsd"> + + <bean id="SessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/> + +</beans> diff --git a/web/src/main/java/lcsb/mapviewer/bean/ConfigurationBean.java b/web/src/main/java/lcsb/mapviewer/bean/ConfigurationBean.java index b93fdd83be4beaa8cbf60a0da5a956f6af3e40ac..692c2af511d270b38661eeca476e730ec688d347 100644 --- a/web/src/main/java/lcsb/mapviewer/bean/ConfigurationBean.java +++ b/web/src/main/java/lcsb/mapviewer/bean/ConfigurationBean.java @@ -25,7 +25,6 @@ import lcsb.mapviewer.common.FrameworkVersion; import lcsb.mapviewer.model.user.ConfigurationElementType; import lcsb.mapviewer.model.user.PrivilegeType; import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.UserAccessException; import lcsb.mapviewer.services.interfaces.IConfigurationService; import lcsb.mapviewer.services.interfaces.IProjectService; import lcsb.mapviewer.services.interfaces.IUserService; @@ -42,468 +41,470 @@ import lcsb.mapviewer.services.view.ProjectView; @ViewScoped public class ConfigurationBean extends AbstractManagedBean implements Serializable { - /** - * String representing {@link ConfigurationElementType#DEFAULT_MAP} system - * property used by {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String DEFAULT_MODEL_PROPERTY = "DEFAULT_MODEL"; - - /** - * String representing {@link ConfigurationElementType#X_FRAME_DOMAIN} system - * property used by {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String X_FRAME_PROPERTY = "X_FRAME"; - - /** - * String representing {@link #logoImg} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String LOGO_IMG_PROPERTY = "LOGO_IMG"; - - /** - * String representing {@link #logoLink} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String LOGO_LINK_PROPERTY = "LOGO_LINK"; - - /** - * String representing {@link #logoText} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String LOGO_TEXT_PROPERTY = "LOGO_TEXT"; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(ConfigurationBean.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * List of values for all possible configurable parameters. - */ - private List<ConfigurationView> values = new ArrayList<>(); - - /** - * Release version of the framework. - */ - private FrameworkVersion version; - - /** - * Configrutaion params value. - */ - private Map<ConfigurationElementType, String> valueMap = new HashMap<>(); - - /** - * Bean used for communication with the client side about the data related to - * users (including information about currently logged user). - * - * @see UserBean - */ - @ManagedProperty(value = "#{userMB}") - private transient UserBean userBean; - - /** - * Service used to access configuration parameters. - * - * @see IConfigurationService - */ - @ManagedProperty(value = "#{ConfigurationService}") - private transient IConfigurationService configurationService; - - /** - * Service used to access information about users. - * - * @see IUserService - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * Service used to access information about projects. - * - * @see IProjectService - */ - @ManagedProperty(value = "#{ProjectService}") - private transient IProjectService projectService; - - @Override - public final void init() { - // listener that checks if the new default map exists in the system - VetoableChangeListener selectedMapVetoChanged = new VetoableChangeListener() { - @Override - public void vetoableChange(final PropertyChangeEvent arg0) throws PropertyVetoException { - if ((DEFAULT_MODEL_PROPERTY).equals(arg0.getPropertyName())) { - if (!projectService.projectExists((String) arg0.getNewValue())) { - throw new PropertyVetoException("Project " + arg0.getNewValue() + " doesn't exist", arg0); - } else { - ProjectView view; - try { - view = projectService.getProjectViewByProjectId((String) arg0.getNewValue(), userBean.getAuthenticationToken()); - } catch (UserAccessException e) { - throw new PropertyVetoException("You have no privilege to perform this operation", arg0); - } - if (!view.getStatus().equalsIgnoreCase("OK")) { - throw new PropertyVetoException("Project " + arg0.getNewValue() + " is invalid. Project status: " + view.getStatus(), arg0); - } - } - } - } - }; - addVetoablePropertyChangeListener(selectedMapVetoChanged); - - PropertyChangeListener xFrameChanged = new PropertyChangeListener() { - - @Override - public void propertyChange(PropertyChangeEvent arg0) { - if ((X_FRAME_PROPERTY).equals(arg0.getPropertyName())) { - Configuration.setxFrameDomain((String) arg0.getNewValue()); - } - } - }; - addPropertyChangeListener(xFrameChanged); - - // listener that checks if the new x-fram address is valid - VetoableChangeListener xFrameVetoChanged = new VetoableChangeListener() { - @Override - public void vetoableChange(final PropertyChangeEvent arg0) throws PropertyVetoException { - if ((X_FRAME_PROPERTY).equals(arg0.getPropertyName())) { - String domain = (String) arg0.getNewValue(); - if (!new UrlValidator().isValid(domain) && !(domain != null && domain.contains("localhost"))) { - throw new PropertyVetoException("Invalid address: " + domain, arg0); - } - } - } - }; - addVetoablePropertyChangeListener(xFrameVetoChanged); - - version = configurationService.getSystemVersion(getProjectDeployPath()); - - refreshValues(null); - - Configuration.setWebAppDir(new File(getPrimefacesUtils().getPath() + "../").getAbsolutePath() + "/"); - } - - /** - * Refresh values from the database. - * - * @param actionEvent - * event from thefrom the client - */ - public final void refreshValues(final ActionEvent actionEvent) { - values = configurationService.getAllValues(); - for (ConfigurationView view : values) { - valueMap.put(view.getType(), view.getValue()); - } - } - - /** - * Save values to the database. - * - * @param actionEvent - * event from thefrom the client - */ - public final void saveValues(final ActionEvent actionEvent) { - // first check if we have privileges - if (getUserHasConfigurationView()) { - setValues(values); - configurationService.updateConfiguration(values); - values = configurationService.getAllValues(); - } - } - - /** - * Checks if logged user can manage the configuration of the system. - * - * @return <code>true</code> if logged user can manage the configuration, - * <code>false</code> otherwise - */ - public final boolean getUserHasConfigurationView() { - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.CONFIGURATION_MANAGE); - return result; - } - - /** - * - * @return list of all configuration values - * @see #values - */ - public final List<ConfigurationView> getValues() { - if (getUserHasConfigurationView()) { - return values; - } else { - return new ArrayList<>(); - } - } - - /** - * Sets the new list of configurable parameters. - * - * @param values - * list of configurable parameters with new values - */ - public final void setValues(final List<ConfigurationView> values) { - // when we set new values we should: - // 1) check if they are correct (vchs listeners) - // 2) notify apropriate listeners - - // for the naming convention of parameters take a look at {@link #vchs} - - // remember the old values from the system (!! not from the bean !!) - List<ConfigurationView> old = configurationService.getAllValues(); - this.values = values; - for (ConfigurationView el : values) { - String newVal = el.getValue(); - String oldVal = null; - for (ConfigurationView oldEl : old) { - if (oldEl.getType().equals(el.getType())) { - oldVal = oldEl.getValue(); - } - } - try { - if (el.getType().equals(ConfigurationElementType.DEFAULT_MAP)) { - fireVetoableChange(DEFAULT_MODEL_PROPERTY, oldVal, newVal); - } - } catch (PropertyVetoException e) { // if there was a veto then rollback - // to system parameters - this.values = old; - logger.debug("Rollback because parameter " + el.getType().name() + " contains inproper value: " + newVal); - sendError(e.getMessage()); - return; - } - } - for (ConfigurationView el : values) { - String newVal = el.getValue(); - String oldVal = null; - for (ConfigurationView oldEl : old) { - if (oldEl.getType().equals(el.getType())) { - oldVal = oldEl.getValue(); - } - } - if (el.getType().equals(ConfigurationElementType.DEFAULT_MAP)) { - firePropertyChange(DEFAULT_MODEL_PROPERTY, oldVal, newVal); - } else if (el.getType().equals(ConfigurationElementType.X_FRAME_DOMAIN)) { - firePropertyChange(X_FRAME_PROPERTY, oldVal, newVal); - } - - } - } - - @Override - public void clear() { - setValues(new ArrayList<ConfigurationView>()); - } - - /** - * @return the userBean - * @see #userBean - */ - public UserBean getUserBean() { - return userBean; - } - - /** - * @param userBean - * the userBean to set - * @see #userBean - */ - public void setUserBean(UserBean userBean) { - this.userBean = userBean; - } - - /** - * @return the configurationService - * @see #configurationService - */ - public IConfigurationService getConfigurationService() { - return configurationService; - } - - /** - * @param configurationService - * the configurationService to set - * @see #configurationService - */ - public void setConfigurationService(IConfigurationService configurationService) { - this.configurationService = configurationService; - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - /** - * @return the projectService - * @see #projectService - */ - public IProjectService getProjectService() { - return projectService; - } - - /** - * @param projectService - * the projectService to set - * @see #projectService - */ - public void setProjectService(IProjectService projectService) { - this.projectService = projectService; - } - - /** - * @return the version - * @see #version - */ - public FrameworkVersion getVersion() { - return version; - } - - /** - * @param version - * the version to set - * @see #version - */ - public void setVersion(FrameworkVersion version) { - this.version = version; - } - - /** - * Returns {@link ConfigurationElementType#GOOGLE_ANALYTICS_IDENTIFIER google - * analytics identifier} used for tracking web-service usage. - * - * @return {@link ConfigurationElementType#GOOGLE_ANALYTICS_IDENTIFIER google - * analytics identifier} used for tracking web-service usage - */ - public String getGoogleAnalyticsIdentifier() { - return valueMap.get(ConfigurationElementType.GOOGLE_ANALYTICS_IDENTIFIER); - } - - /** - * Returns {@link ConfigurationElementType#LOGO_IMG logo image}. - * - * @return {@link ConfigurationElementType#LOGO_IMG logo image} - */ - public String getLogoImg() { - return valueMap.get(ConfigurationElementType.LOGO_IMG); - } - - /** - * Returns {@link ConfigurationElementType#LOGO_LINK logo link}. - * - * @return {@link ConfigurationElementType#LOGO_LINK logo link} - */ - public String getLogoLink() { - return valueMap.get(ConfigurationElementType.LOGO_LINK); - } - - /** - * Returns {@link ConfigurationElementType#LOGO_TEXT alt text for logo}. - * - * @return {@link ConfigurationElementType#LOGO_TEXT alt text for logo} - */ - public String getLogoText() { - return valueMap.get(ConfigurationElementType.LOGO_TEXT); - } - - /** - * Returns {@link ConfigurationElementType#LEGEND_FILE_1 legend file 1}. - * - * @return {@link ConfigurationElementType#LEGEND_FILE_1 legend file 1} - */ - public String getLegendFile1() { - return valueMap.get(ConfigurationElementType.LEGEND_FILE_1); - } - - /** - * Returns {@link ConfigurationElementType#LEGEND_FILE_2 legend file 2}. - * - * @return {@link ConfigurationElementType#LEGEND_FILE_2 legend file 2} - */ - public String getLegendFile2() { - return valueMap.get(ConfigurationElementType.LEGEND_FILE_2); - } - - /** - * Returns {@link ConfigurationElementType#LEGEND_FILE_3 legend file 3}. - * - * @return {@link ConfigurationElementType#LEGEND_FILE_3 legend file 3} - */ - public String getLegendFile3() { - return valueMap.get(ConfigurationElementType.LEGEND_FILE_3); - } - - /** - * Returns {@link ConfigurationElementType#LEGEND_FILE_4 legend file 4}. - * - * @return {@link ConfigurationElementType#LEGEND_FILE_4 legend file 4} - */ - public String getLegendFile4() { - return valueMap.get(ConfigurationElementType.LEGEND_FILE_4); - } - - /** - * Returns {@link ConfigurationElementType#USER_MANUAL_FILE user manual file}. - * - * @return {@link ConfigurationElementType#USER_MANUAL_FILE user manual file} - */ - public String getUserManual() { - return valueMap.get(ConfigurationElementType.USER_MANUAL_FILE); - } - - /** - * Returns {@link String} with estimated current memory usage (in MB). - * - * @return estimated current memory usage (in MB) - */ - public String getMemoryUsage() { - return NumberFormat.getInstance().format(configurationService.getMemoryUsage()) + " MB"; - } - - /** - * Returns {@link String} with max memory available to JVM (in MB). - * - * @return max memory available to JVM (in MB) - */ - public String getMaxMemory() { - return NumberFormat.getInstance().format(configurationService.getMaxMemory()) + " MB"; - } - - /** - * Returns {@link ConfigurationElementType#MIN_COLOR_VAL color} used for - * representing overlay element with negative values. - * - * @return {@link ConfigurationElementType#MIN_COLOR_VAL color} used for - * representing overlay element with negative values - */ - public String getMinColor() { - return valueMap.get(ConfigurationElementType.MIN_COLOR_VAL); - } - - /** - * Returns {@link ConfigurationElementType#MIN_COLOR_VAL color} used for - * representing overlay element with negative values. - * - * @return {@link ConfigurationElementType#MIN_COLOR_VAL color} used for - * representing overlay element with positive values - */ - public String getMaxColor() { - return valueMap.get(ConfigurationElementType.MAX_COLOR_VAL); - } + /** + * String representing {@link ConfigurationElementType#DEFAULT_MAP} system + * property used by {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String DEFAULT_MODEL_PROPERTY = "DEFAULT_MODEL"; + + /** + * String representing {@link ConfigurationElementType#X_FRAME_DOMAIN} system + * property used by {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String X_FRAME_PROPERTY = "X_FRAME"; + + /** + * String representing {@link #logoImg} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String LOGO_IMG_PROPERTY = "LOGO_IMG"; + + /** + * String representing {@link #logoLink} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String LOGO_LINK_PROPERTY = "LOGO_LINK"; + + /** + * String representing {@link #logoText} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String LOGO_TEXT_PROPERTY = "LOGO_TEXT"; + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(ConfigurationBean.class); + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * List of values for all possible configurable parameters. + */ + private List<ConfigurationView> values = new ArrayList<>(); + + /** + * Release version of the framework. + */ + private FrameworkVersion version; + + /** + * Configrutaion params value. + */ + private Map<ConfigurationElementType, String> valueMap = new HashMap<>(); + + /** + * Bean used for communication with the client side about the data related to + * users (including information about currently logged user). + * + * @see UserBean + */ + @ManagedProperty(value = "#{userMB}") + private transient UserBean userBean; + + /** + * Service used to access configuration parameters. + * + * @see IConfigurationService + */ + @ManagedProperty(value = "#{ConfigurationService}") + private transient IConfigurationService configurationService; + + /** + * Service used to access information about users. + * + * @see IUserService + */ + @ManagedProperty(value = "#{UserService}") + private transient IUserService userService; + + /** + * Service used to access information about projects. + * + * @see IProjectService + */ + @ManagedProperty(value = "#{ProjectService}") + private transient IProjectService projectService; + + @Override + public final void init() { + // listener that checks if the new default map exists in the system + VetoableChangeListener selectedMapVetoChanged = new VetoableChangeListener() { + @Override + public void vetoableChange(final PropertyChangeEvent arg0) throws PropertyVetoException { + if ((DEFAULT_MODEL_PROPERTY).equals(arg0.getPropertyName())) { + if (!projectService.projectExists((String) arg0.getNewValue())) { + throw new PropertyVetoException("Project " + arg0.getNewValue() + " doesn't exist", arg0); + } else { + ProjectView view; + try { + view = projectService.getProjectViewByProjectId((String) arg0.getNewValue(), + userBean.getAuthenticationToken()); + } catch (lcsb.mapviewer.services.SecurityException e) { + throw new PropertyVetoException("You have no privilege to perform this operation", arg0); + } + if (!view.getStatus().equalsIgnoreCase("OK")) { + throw new PropertyVetoException( + "Project " + arg0.getNewValue() + " is invalid. Project status: " + view.getStatus(), arg0); + } + } + } + } + }; + addVetoablePropertyChangeListener(selectedMapVetoChanged); + + PropertyChangeListener xFrameChanged = new PropertyChangeListener() { + + @Override + public void propertyChange(PropertyChangeEvent arg0) { + if ((X_FRAME_PROPERTY).equals(arg0.getPropertyName())) { + Configuration.setxFrameDomain((String) arg0.getNewValue()); + } + } + }; + addPropertyChangeListener(xFrameChanged); + + // listener that checks if the new x-fram address is valid + VetoableChangeListener xFrameVetoChanged = new VetoableChangeListener() { + @Override + public void vetoableChange(final PropertyChangeEvent arg0) throws PropertyVetoException { + if ((X_FRAME_PROPERTY).equals(arg0.getPropertyName())) { + String domain = (String) arg0.getNewValue(); + if (!new UrlValidator().isValid(domain) && !(domain != null && domain.contains("localhost"))) { + throw new PropertyVetoException("Invalid address: " + domain, arg0); + } + } + } + }; + addVetoablePropertyChangeListener(xFrameVetoChanged); + + version = configurationService.getSystemVersion(getProjectDeployPath()); + + refreshValues(null); + + Configuration.setWebAppDir(new File(getPrimefacesUtils().getPath() + "../").getAbsolutePath() + "/"); + } + + /** + * Refresh values from the database. + * + * @param actionEvent + * event from thefrom the client + */ + public final void refreshValues(final ActionEvent actionEvent) { + values = configurationService.getAllValues(); + for (ConfigurationView view : values) { + valueMap.put(view.getType(), view.getValue()); + } + } + + /** + * Save values to the database. + * + * @param actionEvent + * event from thefrom the client + */ + public final void saveValues(final ActionEvent actionEvent) { + // first check if we have privileges + if (getUserHasConfigurationView()) { + setValues(values); + configurationService.updateConfiguration(values); + values = configurationService.getAllValues(); + } + } + + /** + * Checks if logged user can manage the configuration of the system. + * + * @return <code>true</code> if logged user can manage the configuration, + * <code>false</code> otherwise + */ + public final boolean getUserHasConfigurationView() { + User user = userBean.getLoggedUser(); + boolean result = userService.userHasPrivilege(user, PrivilegeType.CONFIGURATION_MANAGE); + return result; + } + + /** + * + * @return list of all configuration values + * @see #values + */ + public final List<ConfigurationView> getValues() { + if (getUserHasConfigurationView()) { + return values; + } else { + return new ArrayList<>(); + } + } + + /** + * Sets the new list of configurable parameters. + * + * @param values + * list of configurable parameters with new values + */ + public final void setValues(final List<ConfigurationView> values) { + // when we set new values we should: + // 1) check if they are correct (vchs listeners) + // 2) notify apropriate listeners + + // for the naming convention of parameters take a look at {@link #vchs} + + // remember the old values from the system (!! not from the bean !!) + List<ConfigurationView> old = configurationService.getAllValues(); + this.values = values; + for (ConfigurationView el : values) { + String newVal = el.getValue(); + String oldVal = null; + for (ConfigurationView oldEl : old) { + if (oldEl.getType().equals(el.getType())) { + oldVal = oldEl.getValue(); + } + } + try { + if (el.getType().equals(ConfigurationElementType.DEFAULT_MAP)) { + fireVetoableChange(DEFAULT_MODEL_PROPERTY, oldVal, newVal); + } + } catch (PropertyVetoException e) { // if there was a veto then rollback + // to system parameters + this.values = old; + logger.debug("Rollback because parameter " + el.getType().name() + " contains inproper value: " + newVal); + sendError(e.getMessage()); + return; + } + } + for (ConfigurationView el : values) { + String newVal = el.getValue(); + String oldVal = null; + for (ConfigurationView oldEl : old) { + if (oldEl.getType().equals(el.getType())) { + oldVal = oldEl.getValue(); + } + } + if (el.getType().equals(ConfigurationElementType.DEFAULT_MAP)) { + firePropertyChange(DEFAULT_MODEL_PROPERTY, oldVal, newVal); + } else if (el.getType().equals(ConfigurationElementType.X_FRAME_DOMAIN)) { + firePropertyChange(X_FRAME_PROPERTY, oldVal, newVal); + } + + } + } + + @Override + public void clear() { + setValues(new ArrayList<ConfigurationView>()); + } + + /** + * @return the userBean + * @see #userBean + */ + public UserBean getUserBean() { + return userBean; + } + + /** + * @param userBean + * the userBean to set + * @see #userBean + */ + public void setUserBean(UserBean userBean) { + this.userBean = userBean; + } + + /** + * @return the configurationService + * @see #configurationService + */ + public IConfigurationService getConfigurationService() { + return configurationService; + } + + /** + * @param configurationService + * the configurationService to set + * @see #configurationService + */ + public void setConfigurationService(IConfigurationService configurationService) { + this.configurationService = configurationService; + } + + /** + * @return the userService + * @see #userService + */ + public IUserService getUserService() { + return userService; + } + + /** + * @param userService + * the userService to set + * @see #userService + */ + public void setUserService(IUserService userService) { + this.userService = userService; + } + + /** + * @return the projectService + * @see #projectService + */ + public IProjectService getProjectService() { + return projectService; + } + + /** + * @param projectService + * the projectService to set + * @see #projectService + */ + public void setProjectService(IProjectService projectService) { + this.projectService = projectService; + } + + /** + * @return the version + * @see #version + */ + public FrameworkVersion getVersion() { + return version; + } + + /** + * @param version + * the version to set + * @see #version + */ + public void setVersion(FrameworkVersion version) { + this.version = version; + } + + /** + * Returns {@link ConfigurationElementType#GOOGLE_ANALYTICS_IDENTIFIER google + * analytics identifier} used for tracking web-service usage. + * + * @return {@link ConfigurationElementType#GOOGLE_ANALYTICS_IDENTIFIER google + * analytics identifier} used for tracking web-service usage + */ + public String getGoogleAnalyticsIdentifier() { + return valueMap.get(ConfigurationElementType.GOOGLE_ANALYTICS_IDENTIFIER); + } + + /** + * Returns {@link ConfigurationElementType#LOGO_IMG logo image}. + * + * @return {@link ConfigurationElementType#LOGO_IMG logo image} + */ + public String getLogoImg() { + return valueMap.get(ConfigurationElementType.LOGO_IMG); + } + + /** + * Returns {@link ConfigurationElementType#LOGO_LINK logo link}. + * + * @return {@link ConfigurationElementType#LOGO_LINK logo link} + */ + public String getLogoLink() { + return valueMap.get(ConfigurationElementType.LOGO_LINK); + } + + /** + * Returns {@link ConfigurationElementType#LOGO_TEXT alt text for logo}. + * + * @return {@link ConfigurationElementType#LOGO_TEXT alt text for logo} + */ + public String getLogoText() { + return valueMap.get(ConfigurationElementType.LOGO_TEXT); + } + + /** + * Returns {@link ConfigurationElementType#LEGEND_FILE_1 legend file 1}. + * + * @return {@link ConfigurationElementType#LEGEND_FILE_1 legend file 1} + */ + public String getLegendFile1() { + return valueMap.get(ConfigurationElementType.LEGEND_FILE_1); + } + + /** + * Returns {@link ConfigurationElementType#LEGEND_FILE_2 legend file 2}. + * + * @return {@link ConfigurationElementType#LEGEND_FILE_2 legend file 2} + */ + public String getLegendFile2() { + return valueMap.get(ConfigurationElementType.LEGEND_FILE_2); + } + + /** + * Returns {@link ConfigurationElementType#LEGEND_FILE_3 legend file 3}. + * + * @return {@link ConfigurationElementType#LEGEND_FILE_3 legend file 3} + */ + public String getLegendFile3() { + return valueMap.get(ConfigurationElementType.LEGEND_FILE_3); + } + + /** + * Returns {@link ConfigurationElementType#LEGEND_FILE_4 legend file 4}. + * + * @return {@link ConfigurationElementType#LEGEND_FILE_4 legend file 4} + */ + public String getLegendFile4() { + return valueMap.get(ConfigurationElementType.LEGEND_FILE_4); + } + + /** + * Returns {@link ConfigurationElementType#USER_MANUAL_FILE user manual file}. + * + * @return {@link ConfigurationElementType#USER_MANUAL_FILE user manual file} + */ + public String getUserManual() { + return valueMap.get(ConfigurationElementType.USER_MANUAL_FILE); + } + + /** + * Returns {@link String} with estimated current memory usage (in MB). + * + * @return estimated current memory usage (in MB) + */ + public String getMemoryUsage() { + return NumberFormat.getInstance().format(configurationService.getMemoryUsage()) + " MB"; + } + + /** + * Returns {@link String} with max memory available to JVM (in MB). + * + * @return max memory available to JVM (in MB) + */ + public String getMaxMemory() { + return NumberFormat.getInstance().format(configurationService.getMaxMemory()) + " MB"; + } + + /** + * Returns {@link ConfigurationElementType#MIN_COLOR_VAL color} used for + * representing overlay element with negative values. + * + * @return {@link ConfigurationElementType#MIN_COLOR_VAL color} used for + * representing overlay element with negative values + */ + public String getMinColor() { + return valueMap.get(ConfigurationElementType.MIN_COLOR_VAL); + } + + /** + * Returns {@link ConfigurationElementType#MIN_COLOR_VAL color} used for + * representing overlay element with negative values. + * + * @return {@link ConfigurationElementType#MIN_COLOR_VAL color} used for + * representing overlay element with positive values + */ + public String getMaxColor() { + return valueMap.get(ConfigurationElementType.MAX_COLOR_VAL); + } } diff --git a/web/src/main/java/lcsb/mapviewer/bean/GalaxyBean.java b/web/src/main/java/lcsb/mapviewer/bean/GalaxyBean.java index b3b6c2e1f3907eacc517e577959233942f258be6..278b5f362fc4403159aaeba007b62b53ea736b26 100644 --- a/web/src/main/java/lcsb/mapviewer/bean/GalaxyBean.java +++ b/web/src/main/java/lcsb/mapviewer/bean/GalaxyBean.java @@ -20,7 +20,6 @@ import lcsb.mapviewer.services.interfaces.ILayoutService; import lcsb.mapviewer.services.interfaces.ILayoutService.CreateLayoutParams; import lcsb.mapviewer.services.interfaces.IModelService; import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.LayoutView; /** @@ -32,190 +31,192 @@ import lcsb.mapviewer.services.view.LayoutView; @ManagedBean(name = "galaxyMB") @RequestScoped public class GalaxyBean extends AbstractManagedBean implements Serializable { - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(GalaxyBean.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Status of the processed request. - */ - private String status = null; - - /** - * Service that allows to access and manage models. - */ - @ManagedProperty(value = "#{ModelService}") - private transient IModelService modelService; - - /** - * Service that allows to access and manage models. - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * Service used for managing layouts. - */ - @ManagedProperty(value = "#{LayoutService}") - private transient ILayoutService layoutService; - - @Override - public void clear() { - status = null; - } - - /** - * @return the status - * @see #status - */ - public String getStatus() { - if (status == null) { - try { - Map<String, String> requestParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap(); - String identifier = requestParams.get("identifier"); - String schema = requestParams.get("expression_value"); - String login = requestParams.get("login"); - String password = requestParams.get("password"); - String modelName = requestParams.get("model"); - - AuthenticationToken token = userService.login(login, password); - Model model = (Model) modelService.getLastModelByProjectId(modelName, token); - User user = null; - if (token != null) { - user = userService.getUserByToken(token); - } - LayoutView layout = layoutService.getLayoutByName(model, identifier); - if (identifier == null) { - status = "ERROR. Identifier cannot be null"; - } else if (schema == null) { - status = "ERROR. Expression values schema cannot be null"; - } else if (user == null) { - status = "ERROR. Invalid credentials."; - } else if (modelName == null) { - status = "ERROR. Model cannot be null."; - } else if (model == null) { - status = "ERROR. " + modelName + " model doesn't exist."; - } else if (layout != null) { - status = "ERROR. Layout with given identifier (\"" + identifier + "\") already exists."; - } else { - createLayout(identifier, schema, model, user); - } - if (!status.equals("OK")) { - logger.warn("Problem in galaxy connector: " + status); - } - } catch (Exception e) { - logger.error(e, e); - status = "INTERNAL SERVER ERROR"; - } - } else { - logger.debug("Status already set..."); - } - return status; - } - - /** - * Creates layout from coloring data. - * - * @param identifier - * identifier of layout - * @param schema - * coloring schema (in string format) - * @param model - * model for which we create layout - * @param user - * user who will own the layout - */ - protected void createLayout(String identifier, String schema, Model model, User user) { - String directory = getProjectDeployPath() + "../map_images/" + model.getProject().getDirectory() + "/" + model.getProject().getProjectId() + Math.random(); - - InputStream stream = new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8)); - // the following call will execute asynchronically - try { - CreateLayoutParams params = new CreateLayoutParams().name(identifier).// - directory(directory).// - model(model).// - colorInputStream(stream).// - user(user).// - async(true); - layoutService.createLayout(params); - status = "OK"; - - } catch (InvalidColorSchemaException e) { - status = "Problem with input file: " + e.getMessage(); - } catch (Exception e) { - logger.error(e, e); - status = "Internal server error. More details can be found in log file."; - } - } - - /** - * @param status - * the status to set - * @see #status - */ - public void setStatus(String status) { - this.status = status; - } - - /** - * @return the modelService - * @see #modelService - */ - public IModelService getModelService() { - return modelService; - } - - /** - * @param modelService - * the modelService to set - * @see #modelService - */ - public void setModelService(IModelService modelService) { - this.modelService = modelService; - } - - /** - * @return the layoutService - * @see #layoutService - */ - public ILayoutService getLayoutService() { - return layoutService; - } - - /** - * @param layoutService - * the layoutService to set - * @see #layoutService - */ - public void setLayoutService(ILayoutService layoutService) { - this.layoutService = layoutService; - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - @Override - public void init() { - } + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(GalaxyBean.class); + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Status of the processed request. + */ + private String status = null; + + /** + * Service that allows to access and manage models. + */ + @ManagedProperty(value = "#{ModelService}") + private transient IModelService modelService; + + /** + * Service that allows to access and manage models. + */ + @ManagedProperty(value = "#{UserService}") + private transient IUserService userService; + + /** + * Service used for managing layouts. + */ + @ManagedProperty(value = "#{LayoutService}") + private transient ILayoutService layoutService; + + @Override + public void clear() { + status = null; + } + + /** + * @return the status + * @see #status + */ + public String getStatus() { + if (status == null) { + try { + Map<String, String> requestParams = FacesContext.getCurrentInstance().getExternalContext() + .getRequestParameterMap(); + String identifier = requestParams.get("identifier"); + String schema = requestParams.get("expression_value"); + String login = requestParams.get("login"); + String password = requestParams.get("password"); + String modelName = requestParams.get("model"); + + String token = userService.login(login, password); + Model model = (Model) modelService.getLastModelByProjectId(modelName, token); + User user = null; + if (token != null) { + user = userService.getUserByToken(token); + } + LayoutView layout = layoutService.getLayoutByName(model, identifier); + if (identifier == null) { + status = "ERROR. Identifier cannot be null"; + } else if (schema == null) { + status = "ERROR. Expression values schema cannot be null"; + } else if (user == null) { + status = "ERROR. Invalid credentials."; + } else if (modelName == null) { + status = "ERROR. Model cannot be null."; + } else if (model == null) { + status = "ERROR. " + modelName + " model doesn't exist."; + } else if (layout != null) { + status = "ERROR. Layout with given identifier (\"" + identifier + "\") already exists."; + } else { + createLayout(identifier, schema, model, user); + } + if (!status.equals("OK")) { + logger.warn("Problem in galaxy connector: " + status); + } + } catch (Exception e) { + logger.error(e, e); + status = "INTERNAL SERVER ERROR"; + } + } else { + logger.debug("Status already set..."); + } + return status; + } + + /** + * Creates layout from coloring data. + * + * @param identifier + * identifier of layout + * @param schema + * coloring schema (in string format) + * @param model + * model for which we create layout + * @param user + * user who will own the layout + */ + protected void createLayout(String identifier, String schema, Model model, User user) { + String directory = getProjectDeployPath() + "../map_images/" + model.getProject().getDirectory() + "/" + + model.getProject().getProjectId() + Math.random(); + + InputStream stream = new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8)); + // the following call will execute asynchronically + try { + CreateLayoutParams params = new CreateLayoutParams().name(identifier).// + directory(directory).// + model(model).// + colorInputStream(stream).// + user(user).// + async(true); + layoutService.createLayout(params); + status = "OK"; + + } catch (InvalidColorSchemaException e) { + status = "Problem with input file: " + e.getMessage(); + } catch (Exception e) { + logger.error(e, e); + status = "Internal server error. More details can be found in log file."; + } + } + + /** + * @param status + * the status to set + * @see #status + */ + public void setStatus(String status) { + this.status = status; + } + + /** + * @return the modelService + * @see #modelService + */ + public IModelService getModelService() { + return modelService; + } + + /** + * @param modelService + * the modelService to set + * @see #modelService + */ + public void setModelService(IModelService modelService) { + this.modelService = modelService; + } + + /** + * @return the layoutService + * @see #layoutService + */ + public ILayoutService getLayoutService() { + return layoutService; + } + + /** + * @param layoutService + * the layoutService to set + * @see #layoutService + */ + public void setLayoutService(ILayoutService layoutService) { + this.layoutService = layoutService; + } + + /** + * @return the userService + * @see #userService + */ + public IUserService getUserService() { + return userService; + } + + /** + * @param userService + * the userService to set + * @see #userService + */ + public void setUserService(IUserService userService) { + this.userService = userService; + } + + @Override + public void init() { + } } diff --git a/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java b/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java index 2c866c388497b506597d22ffce6ceeb5519128c1..89300005b0100ec6299c0e1aa6142cbbfa376fc5 100644 --- a/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java +++ b/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java @@ -55,757 +55,760 @@ import lcsb.mapviewer.services.view.ProjectView; @ViewScoped public class LayoutBean extends AbstractManagedBean implements Serializable { - /** - * String representing {@link #layoutFile} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String LAYOUT_FILE_PROPERTY = "LAYOUT_FILE"; - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(LayoutBean.class); - - /** - * List of custom layouts available for current user. - */ - private List<LayoutView> customLayouts = null; - - /** - * List of general layouts. - */ - private List<LayoutView> generalLayouts = null; - - /** - * Layout selected by user for editing. - */ - private LayoutView selectedLayout = null; - - /** - * Name of currently edited/created layout. - */ - private String layoutName = ""; - - /** - * Description of currently edited/created layout. - */ - private String layoutDescription = ""; - - /** - * Type of uploaded layout. - */ - private ColorSchemaType layoutType = ColorSchemaType.GENERIC; - - /** - * Bool information if any error during parsing layout occurred. - */ - private boolean errorOccurred = false; - - /** - * This param should identifie layout currently visualized. However this is - * not handled properly yet. - */ - private LayoutView visualizedLayout = new LayoutView(); - - /** - * File uploaded by user. - */ - private transient File layoutFile = null; - - /** - * Service used for managing layouts. - */ - @ManagedProperty(value = "#{LayoutService}") - private transient ILayoutService layoutService; - - /** - * Service used for accessing information about maps. - */ - @ManagedProperty(value = "#{ModelService}") - private transient IModelService modelService; - - /** - * Bean used for communication with the client side about the data related to - * users (including information about currently logged user). - * - * @see UserBean - */ - @ManagedProperty(value = "#{userMB}") - private transient UserBean userBean; - - /** - * Bean used for communication with the client side about the map currently - * visualized. - * - * @see MapBean - */ - @ManagedProperty(value = "#{mapMB}") - private transient MapBean mapBean; - - @Override - public void init() { - refreshCustomLayouts(null); - - PropertyChangeListener uploadedFilePropertyChangeListener = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (LAYOUT_FILE_PROPERTY.equals(arg0.getPropertyName())) { - try { - File file = (File) arg0.getNewValue(); - ZipEntryFileFactory zife = new ZipEntryFileFactory(); - LayoutZipEntryFile zif = zife.createLayoutZipEntryFile(layoutName, new FileInputStream(file)); - layoutName = zif.getName(); - layoutDescription = zif.getDescription(); - String typeStr = zif.getHeaderParameter(ZipEntryFileFactory.LAYOUT_HEADER_PARAM_TYPE); - if (typeStr != null) { - try { - layoutType = ColorSchemaType.valueOf(typeStr); - } catch (IllegalArgumentException e) { - layoutType = ColorSchemaType.GENERIC; - sendError("Invalid type of overview: " + typeStr); - } - } - } catch (Exception e) { - sendError("Internal server error.", e); - } - } - } - }; - addPropertyChangeListener(uploadedFilePropertyChangeListener); - - // after object was added, refresh custom layouts list - this.registerListener(new Listener<ObjectAddedEvent>(ObjectAddedEvent.class) { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(ObjectAddedEvent event) { - logger.debug("Refreshing layouts after add: "); - Model model = getCurrentTopModel(); - LayoutView layout = (LayoutView) event.getObject(); - if (model != null && model.getId().equals(layout.getModelId())) { - logger.debug("OK"); - refreshCustomLayouts(null); - mapBean.updateModelView(); - } else { - logger.debug("NOT OK"); - } - } - }); - - // after object was removed, refresh custom layouts list - this.registerListener(new Listener<ObjectRemovedEvent>(ObjectRemovedEvent.class) { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(ObjectRemovedEvent event) { - Model model = getCurrentTopModel(); - LayoutView layout = (LayoutView) event.getObject(); - if (model != null && model.getId().equals(layout.getModelId())) { - refreshCustomLayouts(null); - mapBean.updateModelView(); - } - } - }); - } - - /** - * Check if logged user has privilege to add new layout for current map. - * - * @return true if logged user has privilege to add new layout for current map - */ - public boolean getUserHasAddLayoutPrivilege() { - User user = userBean.getLoggedUser(); - Model model = getCurrentTopModel(); - if (model == null) { - return false; - } - return layoutService.userCanAddLayout(model, user); - } - - /** - * Check if user can remove actually selected layout. - * - * @return <i>true</i> if user can remove actually selected layout,<br/> - * <i>false</i> otherwise - */ - public boolean getUserHasRemoveLayoutPrivilege() { - User user = userBean.getLoggedUser(); - return layoutService.userCanRemoveLayout(selectedLayout, user); - } - - /** - * Refresh list of custom layouts. - * - * @param actionEvent - * event from thefrom the client - */ - public void refreshCustomLayouts(final ActionEvent actionEvent) { - User user = userBean.getLoggedUser(); - Model model = getCurrentTopModel(); - customLayouts = layoutService.getCustomLayouts(model, user, true, user); - generalLayouts = layoutService.getGeneralLayouts(model); - } - - /** - * This method handle upload of a file. - * - * @param event - * event send by the client with a file reference - */ - public void handleFileUpload(final FileUploadEvent event) { - try { - logger.debug(event.getFile().getFileName() + " is uploaded."); - UploadedFile uploadedFile = event.getFile(); - String filename = FilenameUtils.getBaseName(uploadedFile.getFileName()); - String extension = FilenameUtils.getExtension(uploadedFile.getFileName()); - File file = File.createTempFile(filename + "-layout-", "." + extension); - file.delete(); - InputStream input = uploadedFile.getInputstream(); - Files.copy(input, file.toPath()); - input.close(); - this.setLayoutFile(file); - } catch (Exception e) { - sendError("Problem with uploading...", e); - } - } - - /** - * Adds public layout to the project selected in the parameter. - * - * @param project - * where the new layout should be added - */ - public void addAnonymousLayout(ProjectView project) { - errorOccurred = false; - Model model = modelService.getLastModelByProjectId(project.getProjectId(), userBean.getAuthenticationToken()); - addLayout(model, null); - } - - /** - * This method adds new layout to the model given in parameter. - * - * - * @param model - * where the new layout should be added - * @param user - * who should be the owenr of new layout (if <code>null</code> the - * layout will be available to everybody) - */ - private void addLayout(Model model, User user) { - if (model == null) { - errorOccurred = true; - sendError("Unknown model."); - return; - } - try { - String directory = getProjectDeployPath() + "../map_images/" + model.getProject().getDirectory() + "/" + model.getProject().getProjectId() - + Math.random(); - - // the following call will execute asynchronically - CreateLayoutParams params = new CreateLayoutParams().name(layoutName).// - directory(directory).// - model(model).// - description(layoutDescription).// - colorInputStream(new FileInputStream(layoutFile)).// - layoutFileName(layoutFile.getName()).// - user(user).// - colorSchemaType(layoutType).// - async(true); - LayoutView view = layoutService.createLayout(params); - layoutName = ""; - layoutFile = null; - - ObjectAddedEvent event = new ObjectAddedEvent(view); - super.callListeners(event); - - sendInfo("File processed successfully. Generating layout."); - } catch (IOException e) { - errorOccurred = true; - logger.error("Problem with uploading layout", e); - sendError(e.getMessage()); - } catch (InvalidColorSchemaException e) { - errorOccurred = true; - logger.error("Problem with uploading layout", e); - sendError(e.getMessage()); - } catch (Exception e) { - logger.error("Problem with uploading layout", e); - sendError("Unknown problem with uploaded file..."); - } - } - - /** - * This method adds a new custom layout to currently selected map. - * - * @param actionEvent - * event from thefrom the client - */ - public void addLayout(final ActionEvent actionEvent) { - errorOccurred = false; - User user = userBean.getLoggedUser(); - Model model = getCurrentTopModel(); - - if (!getUserHasAddLayoutPrivilege()) { - errorOccurred = true; - sendError("You cannot add new layout"); - return; - } - addLayout(model, user); - } - - /** - * Removes layout selected by the client. - * - * @param actionEvent - * action event from client side - */ - public void removeLayout(final ActionEvent actionEvent) { - removeLayout(selectedLayout); - } - - /** - * Removes layout given in the parameter. - * - * @param layout - * layout that should be removed - */ - public void removeLayout(LayoutView layout) { - errorOccurred = false; - try { - User user = userBean.getLoggedUser(); - if (!layoutService.userCanRemoveLayout(layout, user)) { - errorOccurred = true; - sendError("You cannot remove this layout"); - return; - } - layoutService.removeLayout(layout, getProjectDeployPath()); - - ObjectRemovedEvent event = new ObjectRemovedEvent(layout); - super.callListeners(event); - } catch (Exception e) { - errorOccurred = true; - sendError("Problem with removing layout", e); - } - } - - /** - * Updates selectedLayout in the service layer. - * - * @param actionEvent - * action event from client side - */ - public void updateLayout(final ActionEvent actionEvent) { - errorOccurred = false; - if (!getUserHasRemoveLayoutPrivilege()) { - errorOccurred = true; - sendError("You cannot update this layout"); - return; - } - try { - layoutService.updateLayout(selectedLayout); - refreshCustomLayouts(actionEvent); - } catch (Exception e) { - errorOccurred = true; - sendError("Problem with updating layout", e); - } - } - - /** - * Updates layout in the service layer. - * - * @param layout - * layout for update - */ - public void updateLayout(final LayoutView layout) { - errorOccurred = false; - User user = userBean.getLoggedUser(); - if (!layoutService.userCanRemoveLayout(layout, user)) { - errorOccurred = true; - sendError("You cannot update this layout"); - return; - } - try { - layoutService.updateLayout(layout); - refreshCustomLayouts(null); - } catch (Exception e) { - errorOccurred = true; - sendError("Problem with updating layout", e); - } - } - - /** - * Returns the number of layouts that can be uploaded by the user. - * - * @return number of layouts that can still be uploaded by the user - */ - public int getAvailableCustomLayoutNumber() { - User user = userBean.getLoggedUser(); - return (int) layoutService.getAvailableCustomLayoutsNumber(user); - } - - @Override - public void clear() { - setCustomLayouts(null); - setSelectedLayout(null); - setLayoutFile(null); - setLayoutName(null); - setErrorOccurred(false); - setLayoutType(ColorSchemaType.GENERIC); - } - - /** - * @return the userBean - * @see #userBean - */ - public UserBean getUserBean() { - return userBean; - } - - /** - * @param userBean - * the userBean to set - * @see #userBean - */ - public void setUserBean(UserBean userBean) { - this.userBean = userBean; - } - - /** - * @return the layoutService - * @see #layoutService - */ - public ILayoutService getLayoutService() { - return layoutService; - } - - /** - * @param layoutService - * the layoutService to set - * @see #layoutService - */ - public void setLayoutService(ILayoutService layoutService) { - this.layoutService = layoutService; - } - - /** - * @return the mapBean - * @see #mapBean - */ - public MapBean getMapBean() { - return mapBean; - } - - /** - * @param mapBean - * the mapBean to set - * @see #mapBean - */ - public void setMapBean(MapBean mapBean) { - this.mapBean = mapBean; - } - - /** - * @return the selectedLayout - * @see #selectedLayout - */ - public LayoutView getSelectedLayout() { - return selectedLayout; - } - - /** - * @param selectedLayout - * the selectedLayout to set - * @see #selectedLayout - */ - public void setSelectedLayout(LayoutView selectedLayout) { - this.selectedLayout = selectedLayout; - } - - /** - * @return the customLayouts - * @see #customLayouts - */ - public List<LayoutView> getCustomLayouts() { - return customLayouts; - } - - /** - * @param customLayouts - * the customLayouts to set - * @see #customLayouts - */ - public void setCustomLayouts(List<LayoutView> customLayouts) { - this.customLayouts = customLayouts; - } - - /** - * @return the layoutFile - * @see #layoutFile - */ - public File getLayoutFile() { - return layoutFile; - } - - /** - * @param layoutFile - * the layoutFile to set - * @see #layoutFile - */ - public void setLayoutFile(File layoutFile) { - File oldFile = this.layoutFile; - this.layoutFile = layoutFile; - firePropertyChange(LAYOUT_FILE_PROPERTY, oldFile, layoutFile); - } - - /** - * @return the layoutName - * @see #layoutName - */ - public String getLayoutName() { - return layoutName; - } - - /** - * @param layoutName - * the layoutName to set - * @see #layoutName - */ - public void setLayoutName(String layoutName) { - this.layoutName = layoutName; - } - - /** - * @return the errorOccurred - * @see #errorOccurred - */ - public boolean isErrorOccurred() { - return errorOccurred; - } - - /** - * @param errorOccurred - * the errorOccurred to set - * @see #errorOccurred - */ - public void setErrorOccurred(boolean errorOccurred) { - this.errorOccurred = errorOccurred; - } - - /** - * @return the visualizedLayout - * @see #visualizedLayout - */ - public LayoutView getVisualizedLayout() { - return visualizedLayout; - } - - /** - * @param visualizedLayout - * the visualizedLayout to set - * @see #visualizedLayout - */ - public void setVisualizedLayout(LayoutView visualizedLayout) { - this.visualizedLayout = visualizedLayout; - } - - /** - * Updates information in {@link #visualizedLayout} object. - * - * @param actionEvent - * action event from client side - */ - public void getVisualizedLayoutDetails(final ActionEvent actionEvent) { - if (visualizedLayout.getName() != null && !visualizedLayout.getName().trim().equals("")) { - visualizedLayout = layoutService.getLayoutByName(getCurrentTopModel(), visualizedLayout.getName()); - if (visualizedLayout == null) { - visualizedLayout = new LayoutView(); - } else { - // we have new element to vizualize - ObjectAddedEvent event = new ObjectAddedEvent(visualizedLayout); - super.callListeners(event); - } - } - } - - /** - * @return the generalLayouts - * @see #generalLayouts - */ - public List<LayoutView> getGeneralLayouts() { - return generalLayouts; - } - - /** - * @param generalLayouts - * the generalLayouts to set - * @see #generalLayouts - */ - public void setGeneralLayouts(List<LayoutView> generalLayouts) { - this.generalLayouts = generalLayouts; - } - - /** - * Method that allows to donlwoad input data for given layout. - * - * @param layout - * layout for which input data will be downloaded - * - * @throws IOException - * thrown when there are some problems with sending file - * @throws SecurityException - */ - public void downloadInputData(LayoutView layout) throws IOException, SecurityException { - // get input data from database - byte[] data = layoutService.getInputDataForLayout(layout, userBean.getAuthenticationToken()); - String string = new String(data, StandardCharsets.UTF_8); - - sendFileAsResponse(string, "layout_" + layout.getIdObject() + ".txt", MimeType.TEXT); - } - - /** - * @return the modelService - * @see #modelService - */ - public IModelService getModelService() { - return modelService; - } - - /** - * @param modelService - * the modelService to set - * @see #modelService - */ - public void setModelService(IModelService modelService) { - this.modelService = modelService; - } - - /** - * @return the layoutDescription - * @see #layoutDescription - */ - public String getLayoutDescription() { - return layoutDescription; - } - - /** - * @param layoutDescription - * the layoutDescription to set - * @see #layoutDescription - */ - public void setLayoutDescription(String layoutDescription) { - this.layoutDescription = layoutDescription; - } - - /** - * This method sends list of aliases that should be visualized in a - * {@link lcsb.mapviewer.model.map.layout.Layout} to the browser. - * - * @throws IOException - * thrown when there is a problem with accessing information about - * layout - */ - public void retreiveActiveAliasesForLayout() throws IOException { - int layoutId = Integer.valueOf(getRequestParameter("layoutId").replace("cv", "")); - String string = "[]"; - try { - List<LightLayoutAliasView> list = layoutService.getAliasesForLayout(getCurrentTopModel(), layoutId, userBean.getAuthenticationToken()); - LightLayoutAliasViewFactory factory = new LightLayoutAliasViewFactory(); - string = factory.createGson(list); - } catch (Exception e) { - sendError("Internal server error", e); - } - executeJavascript("ServerConnector.addAliasesForLayout('" + layoutId + "','" + string + "');"); - } - - /** - * This method sends full information about aliases that are visualized in a - * {@link lcsb.mapviewer.model.map.layout.Layout} to the browser and - * identified by list of identifiers. - * - * @throws IOException - * thrown when there is a problem with accessing information about - * layout - */ - public void retreiveFullAliasesForLayout() { - int layoutId = Integer.valueOf(getRequestParameter("layoutId").replace("cv", "")); - String string = "[]"; - try { - List<Pair<Integer, Integer>> identifiers = deserializeJsonIds(getRequestParameter("ids")); - List<FullLayoutAliasView> list = layoutService - .getFullAliasesForLayoutByIds(getCurrentTopModel(), identifiers, layoutId, userBean.getAuthenticationToken()); - string = new FullLayoutAliasViewFactory().createGson(list); - } catch (Exception e) { - sendError("Internal server error", e); - } - executeJavascript("ServerConnector.updateAliasesForLayout('" + layoutId + "','" + string + "');"); - } - - /** - * This method sends list of reactions that should be visualized in a - * {@link lcsb.mapviewer.model.map.layout.Layout} to the browser. - * - * @throws IOException - * thrown when there is a problem with accessing information about - * layout - */ - public void retreiveActiveReactionsForLayout() throws IOException { - int layoutId = Integer.valueOf(getRequestParameter("layoutId").replace("cv", "")); - String string = "[]"; - try { - List<LightLayoutReactionView> list = layoutService.getReactionsForLayout(getCurrentTopModel(), layoutId, userBean.getAuthenticationToken()); - LightLayoutReactionViewFactory factory = new LightLayoutReactionViewFactory(); - string = factory.createGson(list); - } catch (Exception e) { - sendError("Internal server error", e); - } - executeJavascript("ServerConnector.addReactionsForLayout('" + layoutId + "','" + string + "');"); - } - - /** - * @return the layoutType - * @see #layoutType - */ - public ColorSchemaType getLayoutType() { - return layoutType; - } - - /** - * @param layoutType - * the layoutType to set - * @see #layoutType - */ - public void setLayoutType(ColorSchemaType layoutType) { - this.layoutType = layoutType; - } - - /** - * Returns list of available layout types. - * - * @return list of available layout types - */ - public ColorSchemaType[] getColorSchemaTypes() { - return ColorSchemaType.values(); - } - - /** - * Returns currently browsed map. - * - * @return currently browsed map - */ - private Model getCurrentTopModel() { - return mapBean.getCurrentTopModel(); - } + /** + * String representing {@link #layoutFile} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String LAYOUT_FILE_PROPERTY = "LAYOUT_FILE"; + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(LayoutBean.class); + + /** + * List of custom layouts available for current user. + */ + private List<LayoutView> customLayouts = null; + + /** + * List of general layouts. + */ + private List<LayoutView> generalLayouts = null; + + /** + * Layout selected by user for editing. + */ + private LayoutView selectedLayout = null; + + /** + * Name of currently edited/created layout. + */ + private String layoutName = ""; + + /** + * Description of currently edited/created layout. + */ + private String layoutDescription = ""; + + /** + * Type of uploaded layout. + */ + private ColorSchemaType layoutType = ColorSchemaType.GENERIC; + + /** + * Bool information if any error during parsing layout occurred. + */ + private boolean errorOccurred = false; + + /** + * This param should identifie layout currently visualized. However this is not + * handled properly yet. + */ + private LayoutView visualizedLayout = new LayoutView(); + + /** + * File uploaded by user. + */ + private transient File layoutFile = null; + + /** + * Service used for managing layouts. + */ + @ManagedProperty(value = "#{LayoutService}") + private transient ILayoutService layoutService; + + /** + * Service used for accessing information about maps. + */ + @ManagedProperty(value = "#{ModelService}") + private transient IModelService modelService; + + /** + * Bean used for communication with the client side about the data related to + * users (including information about currently logged user). + * + * @see UserBean + */ + @ManagedProperty(value = "#{userMB}") + private transient UserBean userBean; + + /** + * Bean used for communication with the client side about the map currently + * visualized. + * + * @see MapBean + */ + @ManagedProperty(value = "#{mapMB}") + private transient MapBean mapBean; + + @Override + public void init() { + refreshCustomLayouts(null); + + PropertyChangeListener uploadedFilePropertyChangeListener = new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent arg0) { + if (LAYOUT_FILE_PROPERTY.equals(arg0.getPropertyName())) { + try { + File file = (File) arg0.getNewValue(); + ZipEntryFileFactory zife = new ZipEntryFileFactory(); + LayoutZipEntryFile zif = zife.createLayoutZipEntryFile(layoutName, new FileInputStream(file)); + layoutName = zif.getName(); + layoutDescription = zif.getDescription(); + String typeStr = zif.getHeaderParameter(ZipEntryFileFactory.LAYOUT_HEADER_PARAM_TYPE); + if (typeStr != null) { + try { + layoutType = ColorSchemaType.valueOf(typeStr); + } catch (IllegalArgumentException e) { + layoutType = ColorSchemaType.GENERIC; + sendError("Invalid type of overview: " + typeStr); + } + } + } catch (Exception e) { + sendError("Internal server error.", e); + } + } + } + }; + addPropertyChangeListener(uploadedFilePropertyChangeListener); + + // after object was added, refresh custom layouts list + this.registerListener(new Listener<ObjectAddedEvent>(ObjectAddedEvent.class) { + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + protected void handle(ObjectAddedEvent event) { + logger.debug("Refreshing layouts after add: "); + Model model = getCurrentTopModel(); + LayoutView layout = (LayoutView) event.getObject(); + if (model != null && model.getId().equals(layout.getModelId())) { + logger.debug("OK"); + refreshCustomLayouts(null); + mapBean.updateModelView(); + } else { + logger.debug("NOT OK"); + } + } + }); + + // after object was removed, refresh custom layouts list + this.registerListener(new Listener<ObjectRemovedEvent>(ObjectRemovedEvent.class) { + + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + protected void handle(ObjectRemovedEvent event) { + Model model = getCurrentTopModel(); + LayoutView layout = (LayoutView) event.getObject(); + if (model != null && model.getId().equals(layout.getModelId())) { + refreshCustomLayouts(null); + mapBean.updateModelView(); + } + } + }); + } + + /** + * Check if logged user has privilege to add new layout for current map. + * + * @return true if logged user has privilege to add new layout for current map + */ + public boolean getUserHasAddLayoutPrivilege() { + User user = userBean.getLoggedUser(); + Model model = getCurrentTopModel(); + if (model == null) { + return false; + } + return layoutService.userCanAddLayout(model, user); + } + + /** + * Check if user can remove actually selected layout. + * + * @return <i>true</i> if user can remove actually selected layout,<br/> + * <i>false</i> otherwise + */ + public boolean getUserHasRemoveLayoutPrivilege() { + User user = userBean.getLoggedUser(); + return layoutService.userCanRemoveLayout(selectedLayout, user); + } + + /** + * Refresh list of custom layouts. + * + * @param actionEvent + * event from thefrom the client + */ + public void refreshCustomLayouts(final ActionEvent actionEvent) { + User user = userBean.getLoggedUser(); + Model model = getCurrentTopModel(); + customLayouts = layoutService.getCustomLayouts(model, user, true, user); + generalLayouts = layoutService.getGeneralLayouts(model); + } + + /** + * This method handle upload of a file. + * + * @param event + * event send by the client with a file reference + */ + public void handleFileUpload(final FileUploadEvent event) { + try { + logger.debug(event.getFile().getFileName() + " is uploaded."); + UploadedFile uploadedFile = event.getFile(); + String filename = FilenameUtils.getBaseName(uploadedFile.getFileName()); + String extension = FilenameUtils.getExtension(uploadedFile.getFileName()); + File file = File.createTempFile(filename + "-layout-", "." + extension); + file.delete(); + InputStream input = uploadedFile.getInputstream(); + Files.copy(input, file.toPath()); + input.close(); + this.setLayoutFile(file); + } catch (Exception e) { + sendError("Problem with uploading...", e); + } + } + + /** + * Adds public layout to the project selected in the parameter. + * + * @param project + * where the new layout should be added + * @throws SecurityException + */ + public void addAnonymousLayout(ProjectView project) throws SecurityException { + errorOccurred = false; + Model model = modelService.getLastModelByProjectId(project.getProjectId(), userBean.getAuthenticationToken()); + addLayout(model, null); + } + + /** + * This method adds new layout to the model given in parameter. + * + * + * @param model + * where the new layout should be added + * @param user + * who should be the owenr of new layout (if <code>null</code> the + * layout will be available to everybody) + */ + private void addLayout(Model model, User user) { + if (model == null) { + errorOccurred = true; + sendError("Unknown model."); + return; + } + try { + String directory = getProjectDeployPath() + "../map_images/" + model.getProject().getDirectory() + "/" + + model.getProject().getProjectId() + Math.random(); + + // the following call will execute asynchronically + CreateLayoutParams params = new CreateLayoutParams().name(layoutName).// + directory(directory).// + model(model).// + description(layoutDescription).// + colorInputStream(new FileInputStream(layoutFile)).// + layoutFileName(layoutFile.getName()).// + user(user).// + colorSchemaType(layoutType).// + async(true); + LayoutView view = layoutService.createLayout(params); + layoutName = ""; + layoutFile = null; + + ObjectAddedEvent event = new ObjectAddedEvent(view); + super.callListeners(event); + + sendInfo("File processed successfully. Generating layout."); + } catch (IOException e) { + errorOccurred = true; + logger.error("Problem with uploading layout", e); + sendError(e.getMessage()); + } catch (InvalidColorSchemaException e) { + errorOccurred = true; + logger.error("Problem with uploading layout", e); + sendError(e.getMessage()); + } catch (Exception e) { + logger.error("Problem with uploading layout", e); + sendError("Unknown problem with uploaded file..."); + } + } + + /** + * This method adds a new custom layout to currently selected map. + * + * @param actionEvent + * event from thefrom the client + */ + public void addLayout(final ActionEvent actionEvent) { + errorOccurred = false; + User user = userBean.getLoggedUser(); + Model model = getCurrentTopModel(); + + if (!getUserHasAddLayoutPrivilege()) { + errorOccurred = true; + sendError("You cannot add new layout"); + return; + } + addLayout(model, user); + } + + /** + * Removes layout selected by the client. + * + * @param actionEvent + * action event from client side + */ + public void removeLayout(final ActionEvent actionEvent) { + removeLayout(selectedLayout); + } + + /** + * Removes layout given in the parameter. + * + * @param layout + * layout that should be removed + */ + public void removeLayout(LayoutView layout) { + errorOccurred = false; + try { + User user = userBean.getLoggedUser(); + if (!layoutService.userCanRemoveLayout(layout, user)) { + errorOccurred = true; + sendError("You cannot remove this layout"); + return; + } + layoutService.removeLayout(layout, getProjectDeployPath()); + + ObjectRemovedEvent event = new ObjectRemovedEvent(layout); + super.callListeners(event); + } catch (Exception e) { + errorOccurred = true; + sendError("Problem with removing layout", e); + } + } + + /** + * Updates selectedLayout in the service layer. + * + * @param actionEvent + * action event from client side + */ + public void updateLayout(final ActionEvent actionEvent) { + errorOccurred = false; + if (!getUserHasRemoveLayoutPrivilege()) { + errorOccurred = true; + sendError("You cannot update this layout"); + return; + } + try { + layoutService.updateLayout(selectedLayout); + refreshCustomLayouts(actionEvent); + } catch (Exception e) { + errorOccurred = true; + sendError("Problem with updating layout", e); + } + } + + /** + * Updates layout in the service layer. + * + * @param layout + * layout for update + */ + public void updateLayout(final LayoutView layout) { + errorOccurred = false; + User user = userBean.getLoggedUser(); + if (!layoutService.userCanRemoveLayout(layout, user)) { + errorOccurred = true; + sendError("You cannot update this layout"); + return; + } + try { + layoutService.updateLayout(layout); + refreshCustomLayouts(null); + } catch (Exception e) { + errorOccurred = true; + sendError("Problem with updating layout", e); + } + } + + /** + * Returns the number of layouts that can be uploaded by the user. + * + * @return number of layouts that can still be uploaded by the user + */ + public int getAvailableCustomLayoutNumber() { + User user = userBean.getLoggedUser(); + return (int) layoutService.getAvailableCustomLayoutsNumber(user); + } + + @Override + public void clear() { + setCustomLayouts(null); + setSelectedLayout(null); + setLayoutFile(null); + setLayoutName(null); + setErrorOccurred(false); + setLayoutType(ColorSchemaType.GENERIC); + } + + /** + * @return the userBean + * @see #userBean + */ + public UserBean getUserBean() { + return userBean; + } + + /** + * @param userBean + * the userBean to set + * @see #userBean + */ + public void setUserBean(UserBean userBean) { + this.userBean = userBean; + } + + /** + * @return the layoutService + * @see #layoutService + */ + public ILayoutService getLayoutService() { + return layoutService; + } + + /** + * @param layoutService + * the layoutService to set + * @see #layoutService + */ + public void setLayoutService(ILayoutService layoutService) { + this.layoutService = layoutService; + } + + /** + * @return the mapBean + * @see #mapBean + */ + public MapBean getMapBean() { + return mapBean; + } + + /** + * @param mapBean + * the mapBean to set + * @see #mapBean + */ + public void setMapBean(MapBean mapBean) { + this.mapBean = mapBean; + } + + /** + * @return the selectedLayout + * @see #selectedLayout + */ + public LayoutView getSelectedLayout() { + return selectedLayout; + } + + /** + * @param selectedLayout + * the selectedLayout to set + * @see #selectedLayout + */ + public void setSelectedLayout(LayoutView selectedLayout) { + this.selectedLayout = selectedLayout; + } + + /** + * @return the customLayouts + * @see #customLayouts + */ + public List<LayoutView> getCustomLayouts() { + return customLayouts; + } + + /** + * @param customLayouts + * the customLayouts to set + * @see #customLayouts + */ + public void setCustomLayouts(List<LayoutView> customLayouts) { + this.customLayouts = customLayouts; + } + + /** + * @return the layoutFile + * @see #layoutFile + */ + public File getLayoutFile() { + return layoutFile; + } + + /** + * @param layoutFile + * the layoutFile to set + * @see #layoutFile + */ + public void setLayoutFile(File layoutFile) { + File oldFile = this.layoutFile; + this.layoutFile = layoutFile; + firePropertyChange(LAYOUT_FILE_PROPERTY, oldFile, layoutFile); + } + + /** + * @return the layoutName + * @see #layoutName + */ + public String getLayoutName() { + return layoutName; + } + + /** + * @param layoutName + * the layoutName to set + * @see #layoutName + */ + public void setLayoutName(String layoutName) { + this.layoutName = layoutName; + } + + /** + * @return the errorOccurred + * @see #errorOccurred + */ + public boolean isErrorOccurred() { + return errorOccurred; + } + + /** + * @param errorOccurred + * the errorOccurred to set + * @see #errorOccurred + */ + public void setErrorOccurred(boolean errorOccurred) { + this.errorOccurred = errorOccurred; + } + + /** + * @return the visualizedLayout + * @see #visualizedLayout + */ + public LayoutView getVisualizedLayout() { + return visualizedLayout; + } + + /** + * @param visualizedLayout + * the visualizedLayout to set + * @see #visualizedLayout + */ + public void setVisualizedLayout(LayoutView visualizedLayout) { + this.visualizedLayout = visualizedLayout; + } + + /** + * Updates information in {@link #visualizedLayout} object. + * + * @param actionEvent + * action event from client side + */ + public void getVisualizedLayoutDetails(final ActionEvent actionEvent) { + if (visualizedLayout.getName() != null && !visualizedLayout.getName().trim().equals("")) { + visualizedLayout = layoutService.getLayoutByName(getCurrentTopModel(), visualizedLayout.getName()); + if (visualizedLayout == null) { + visualizedLayout = new LayoutView(); + } else { + // we have new element to vizualize + ObjectAddedEvent event = new ObjectAddedEvent(visualizedLayout); + super.callListeners(event); + } + } + } + + /** + * @return the generalLayouts + * @see #generalLayouts + */ + public List<LayoutView> getGeneralLayouts() { + return generalLayouts; + } + + /** + * @param generalLayouts + * the generalLayouts to set + * @see #generalLayouts + */ + public void setGeneralLayouts(List<LayoutView> generalLayouts) { + this.generalLayouts = generalLayouts; + } + + /** + * Method that allows to donlwoad input data for given layout. + * + * @param layout + * layout for which input data will be downloaded + * + * @throws IOException + * thrown when there are some problems with sending file + * @throws SecurityException + */ + public void downloadInputData(LayoutView layout) throws IOException, SecurityException { + // get input data from database + byte[] data = layoutService.getInputDataForLayout(layout, userBean.getAuthenticationToken()); + String string = new String(data, StandardCharsets.UTF_8); + + sendFileAsResponse(string, "layout_" + layout.getIdObject() + ".txt", MimeType.TEXT); + } + + /** + * @return the modelService + * @see #modelService + */ + public IModelService getModelService() { + return modelService; + } + + /** + * @param modelService + * the modelService to set + * @see #modelService + */ + public void setModelService(IModelService modelService) { + this.modelService = modelService; + } + + /** + * @return the layoutDescription + * @see #layoutDescription + */ + public String getLayoutDescription() { + return layoutDescription; + } + + /** + * @param layoutDescription + * the layoutDescription to set + * @see #layoutDescription + */ + public void setLayoutDescription(String layoutDescription) { + this.layoutDescription = layoutDescription; + } + + /** + * This method sends list of aliases that should be visualized in a + * {@link lcsb.mapviewer.model.map.layout.Layout} to the browser. + * + * @throws IOException + * thrown when there is a problem with accessing information about + * layout + */ + public void retreiveActiveAliasesForLayout() throws IOException { + int layoutId = Integer.valueOf(getRequestParameter("layoutId").replace("cv", "")); + String string = "[]"; + try { + List<LightLayoutAliasView> list = layoutService.getAliasesForLayout(getCurrentTopModel(), layoutId, + userBean.getAuthenticationToken()); + LightLayoutAliasViewFactory factory = new LightLayoutAliasViewFactory(); + string = factory.createGson(list); + } catch (Exception e) { + sendError("Internal server error", e); + } + executeJavascript("ServerConnector.addAliasesForLayout('" + layoutId + "','" + string + "');"); + } + + /** + * This method sends full information about aliases that are visualized in a + * {@link lcsb.mapviewer.model.map.layout.Layout} to the browser and identified + * by list of identifiers. + * + * @throws IOException + * thrown when there is a problem with accessing information about + * layout + */ + public void retreiveFullAliasesForLayout() { + int layoutId = Integer.valueOf(getRequestParameter("layoutId").replace("cv", "")); + String string = "[]"; + try { + List<Pair<Integer, Integer>> identifiers = deserializeJsonIds(getRequestParameter("ids")); + List<FullLayoutAliasView> list = layoutService.getFullAliasesForLayoutByIds(getCurrentTopModel(), identifiers, + layoutId, userBean.getAuthenticationToken()); + string = new FullLayoutAliasViewFactory().createGson(list); + } catch (Exception e) { + sendError("Internal server error", e); + } + executeJavascript("ServerConnector.updateAliasesForLayout('" + layoutId + "','" + string + "');"); + } + + /** + * This method sends list of reactions that should be visualized in a + * {@link lcsb.mapviewer.model.map.layout.Layout} to the browser. + * + * @throws IOException + * thrown when there is a problem with accessing information about + * layout + */ + public void retreiveActiveReactionsForLayout() throws IOException { + int layoutId = Integer.valueOf(getRequestParameter("layoutId").replace("cv", "")); + String string = "[]"; + try { + List<LightLayoutReactionView> list = layoutService.getReactionsForLayout(getCurrentTopModel(), layoutId, + userBean.getAuthenticationToken()); + LightLayoutReactionViewFactory factory = new LightLayoutReactionViewFactory(); + string = factory.createGson(list); + } catch (Exception e) { + sendError("Internal server error", e); + } + executeJavascript("ServerConnector.addReactionsForLayout('" + layoutId + "','" + string + "');"); + } + + /** + * @return the layoutType + * @see #layoutType + */ + public ColorSchemaType getLayoutType() { + return layoutType; + } + + /** + * @param layoutType + * the layoutType to set + * @see #layoutType + */ + public void setLayoutType(ColorSchemaType layoutType) { + this.layoutType = layoutType; + } + + /** + * Returns list of available layout types. + * + * @return list of available layout types + */ + public ColorSchemaType[] getColorSchemaTypes() { + return ColorSchemaType.values(); + } + + /** + * Returns currently browsed map. + * + * @return currently browsed map + */ + private Model getCurrentTopModel() { + return mapBean.getCurrentTopModel(); + } } diff --git a/web/src/main/java/lcsb/mapviewer/bean/MapBean.java b/web/src/main/java/lcsb/mapviewer/bean/MapBean.java index d8c6f2d8d8ebf90c7f09148860a4c804f208f192..bf2709f766b291eef1fb78ad4c7170f014474a41 100644 --- a/web/src/main/java/lcsb/mapviewer/bean/MapBean.java +++ b/web/src/main/java/lcsb/mapviewer/bean/MapBean.java @@ -33,6 +33,7 @@ import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; import lcsb.mapviewer.model.user.ConfigurationElementType; import lcsb.mapviewer.model.user.PrivilegeType; import lcsb.mapviewer.model.user.User; +import lcsb.mapviewer.services.SecurityException; import lcsb.mapviewer.services.interfaces.IConfigurationService; import lcsb.mapviewer.services.interfaces.IModelService; import lcsb.mapviewer.services.interfaces.IProjectService; @@ -58,966 +59,979 @@ import lcsb.mapviewer.services.view.ProjectView; @ViewScoped public class MapBean extends AbstractManagedBean implements Serializable { - /** - * String representing {@link #currentMapId} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String CURRENT_MODEL_ID_PROPERTY = "CURRENT_MODEL_ID"; - - /** - * String representing {@link #currentMap} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String CURRENT_MODEL_PROPERTY = "CURRENT_MODEL"; - - /** - * Name of the session field that store {@link ClientMapData#centerCoordinateY - * y coordinate} of the browsable model (this will is used when page is - * refreshed). - */ - public static final String Y_COORD_SESSION_PARAM = "Y_COORD"; - - /** - * Name of the session field that store {@link ClientMapData#centerCoordinateX - * x coordinate} of the browsable model (this will is used when page is - * refreshed). - */ - public static final String X_COORD_SESSION_PARAM = "X_COORD"; - - /** - * Name of the session field that store {@link ClientMapData#zoomLevel zoom - * level} of the browsable model (this will is used when page is refreshed). - */ - public static final String ZOOM_LEVEL_SESSION_PARAM = "LEVEL"; - - /** - * Name of the session field that store {@link ClientMapData#selectedLayout - * selected layout} of the browsable model (this will is used when page is - * refreshed). - */ - public static final String SELECTED_LAYOUT_SESSION_PARAM = "SELECTED_LAYOUT"; - - /** - * Default organism by which results should be filtered (homo sapiens by - * default). - */ - - private static final MiriamData DEFAULT_ORGANISM = TaxonomyBackend.HUMAN_TAXONOMY; - - /** - * Object representing currently visualized project. - */ - private ProjectView currentProjectView = null; - - /** - * Name of the current project. - */ - private String currentMapId = null; - - /** - * Map currently browsed. - */ - private transient Model currentMap = null; - - /** - * This class store information about browsing single map/submap. - * - * @author Piotr Gawron - * - */ - public class ClientMapData implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Configuration of the map used by the javascript frontend. - */ - private ModelView mapConfig = null; - - /** - * Converter of coordinates dedicated to the map (every map must have a - * different converter, because the size and number of layers in the maps - * are different). - */ - private CoordinationConverter cConverter; - - /** - * Type of the model (used only in case of submodels). - */ - private String type = ""; - - /** - * X coordinate of map center. - */ - private String centerCoordinateX = ""; - - /** - * Y coordinate of map center. - */ - private String centerCoordinateY = ""; - - /** - * Level at which map is browsed. - */ - private String zoomLevel = "" + Configuration.MIN_ZOOM_LEVEL; - - /** - * Layout currently visualized. - */ - private String selectedLayout = ""; - - /** - * @return the mapConfig - * @see #mapConfig - */ - public ModelView getMapConfig() { - return mapConfig; - } - - /** - * @param mapConfig - * the mapConfig to set - * @see #mapConfig - */ - public void setMapConfig(ModelView mapConfig) { - this.mapConfig = mapConfig; - // set information about location and zooming (if it's set in the session) - if (getSessionParam(ZOOM_LEVEL_SESSION_PARAM + mapConfig.getIdObject()) != null) { - setZoomLevel((String) getSessionParam(ZOOM_LEVEL_SESSION_PARAM + mapConfig.getIdObject())); - // when we refresh map and have defined coordinates then tell the client - // side that it shouldn't fit it into the bounds - mapConfig.setFitMapBounds(false); - } else { - setZoomLevel(""); - } - if (getSessionParam(X_COORD_SESSION_PARAM + mapConfig.getIdObject()) != null) { - setCenterCoordinateX((String) getSessionParam(X_COORD_SESSION_PARAM + mapConfig.getIdObject())); - // when we refresh map and have defined coordinates then tell the client - // side that it shouldn't fit it into the bounds - mapConfig.setFitMapBounds(false); - } else { - setCenterCoordinateX(""); - } - if (getSessionParam(Y_COORD_SESSION_PARAM + mapConfig.getIdObject()) != null) { - setCenterCoordinateY((String) getSessionParam(Y_COORD_SESSION_PARAM + mapConfig.getIdObject())); - } else { - setCenterCoordinateY(""); - } - setSelectedLayout(""); - if (getSessionParam(SELECTED_LAYOUT_SESSION_PARAM + mapConfig.getIdObject()) != null) { - setSelectedLayout((String) getSessionParam(SELECTED_LAYOUT_SESSION_PARAM + mapConfig.getIdObject())); - } else { - if (mapConfig.getLayouts().size() > 0) { - setSelectedLayout("cv" + mapConfig.getLayouts().get(0).getIdObject()); - } else { - logger.warn("No layouts for model: " + mapConfig.getIdObject()); - - } - } - } - - /** - * @return the cConverter - * @see #cConverter - */ - public CoordinationConverter getcConverter() { - return cConverter; - } - - /** - * @param cConverter - * the cConverter to set - * @see #cConverter - */ - public void setcConverter(CoordinationConverter cConverter) { - this.cConverter = cConverter; - } - - /** - * @return the centerCoordinateX - * @see #centerCoordinateX - */ - public String getCenterCoordinateX() { - return centerCoordinateX; - } - - /** - * @param centerCoordinateX - * the centerCoordinateX to set - * @see #centerCoordinateX - */ - public void setCenterCoordinateX(String centerCoordinateX) { - if (centerCoordinateX != null && !centerCoordinateX.isEmpty()) { - addSessionParam(X_COORD_SESSION_PARAM + mapConfig.getIdObject(), centerCoordinateX); - } - this.centerCoordinateX = centerCoordinateX; - } - - /** - * @return the centerCoordinateY - * @see #centerCoordinateY - */ - public String getCenterCoordinateY() { - return centerCoordinateY; - } - - /** - * @param centerCoordinateY - * the centerCoordinateY to set - * @see #centerCoordinateY - */ - public void setCenterCoordinateY(String centerCoordinateY) { - if (centerCoordinateY != null && !centerCoordinateY.isEmpty()) { - addSessionParam(Y_COORD_SESSION_PARAM + mapConfig.getIdObject(), centerCoordinateY); - } - this.centerCoordinateY = centerCoordinateY; - } - - /** - * @return the zoomLevel - * @see #zoomLevel - */ - public String getZoomLevel() { - return zoomLevel; - } - - /** - * @param zoomLevel - * the zoomLevel to set - * @see #zoomLevel - */ - public void setZoomLevel(String zoomLevel) { - if (zoomLevel != null && !zoomLevel.isEmpty()) { - addSessionParam(ZOOM_LEVEL_SESSION_PARAM + mapConfig.getIdObject(), zoomLevel); - } - this.zoomLevel = zoomLevel; - } - - /** - * @return the selectedLayout - * @see #selectedLayout - */ - public String getSelectedLayout() { - return selectedLayout; - } - - /** - * @param selectedLayout - * the selectedLayout to set - * @see #selectedLayout - */ - public void setSelectedLayout(String selectedLayout) { - if (selectedLayout != null && !selectedLayout.isEmpty()) { - addSessionParam(SELECTED_LAYOUT_SESSION_PARAM + mapConfig.getIdObject(), selectedLayout); - } - this.selectedLayout = selectedLayout; - } - - /** - * @return the type - * @see #type - */ - public String getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(String type) { - this.type = type; - } - - } - - /** - * Top map of currently browsed model. - */ - private ClientMapData topModelMapData = null; - - /** - * List of all model/submodels that are browsed in the current window. - */ - private List<ClientMapData> mapDataList = new ArrayList<>(); - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Service used to access information about users. - * - * @see IUserService - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * Service that allows to access and manage models. - */ - @ManagedProperty(value = "#{ModelService}") - private transient IModelService modelService; - - /** - * Service that allows to access and manage models. - */ - @ManagedProperty(value = "#{ProjectService}") - private transient IProjectService projectService; - - /** - * Service used to access configuration parameters. - * - * @see IConfigurationService - */ - @ManagedProperty(value = "#{ConfigurationService}") - private transient IConfigurationService confService; - - /** - * Bean used for communication with the client side about the data related to - * users (including information about currently logged user). - * - * @see UserBean - */ - @ManagedProperty(value = "#{userMB}") - private transient UserBean userBean; - - /** - * Factory used to create {@link FullAliasView} elements. - */ - @ManagedProperty(value = "#{FullAliasViewFactory}") - private transient FullAliasViewFactory fullAliasViewFactory; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(MapBean.class); - - /** - * Service used to access configuration parameters. - * - * @see IConfigurationService - */ - @ManagedProperty(value = "#{ConfigurationService}") - private transient IConfigurationService configurationService; - - @Override - public void init() { - // when model is changed we have to change few parameters as well - PropertyChangeListener modelChanged = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (CURRENT_MODEL_PROPERTY.equals(arg0.getPropertyName())) { - updateModelView(); - } - } - - }; - addPropertyChangeListener(modelChanged); - - // when we change id we should propagate the change to model - PropertyChangeListener mapIdChangeListener = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (CURRENT_MODEL_ID_PROPERTY.equals(arg0.getPropertyName())) { - try { - setCurrentTopModel(getModelService().getLastModelByProjectId((String) arg0.getNewValue(), userBean.getAuthenticationToken())); - setCurrentProjectView(getProjectService().getProjectViewByProjectId(currentMap.getProject().getProjectId(), userBean.getAuthenticationToken())); - } catch (Exception e) { - setCurrentTopModel(getModelService().getLastModelByProjectId((String) arg0.getOldValue(), userBean.getAuthenticationToken())); - logger.error(e, e); - } - } - } - - }; - addPropertyChangeListener(mapIdChangeListener); - - // when we change id we should propagate the change to model - VetoableChangeListener vetoMapIdChangeListener = new VetoableChangeListener() { - @Override - public void vetoableChange(PropertyChangeEvent arg0) throws PropertyVetoException { - if (!getProjectService().projectExists((String) arg0.getNewValue())) { - throw new PropertyVetoException("Project with id \"" + arg0.getNewValue() + "\" doesn't exist.", arg0); - } - } - - }; - addVetoablePropertyChangeListener(vetoMapIdChangeListener); - - // set id from request parameters (id is the url GET parameter) - setCurrentMapId(getRequestParameter("id")); - - } - - /** - * Refresh information about models. - */ - protected void updateModelView() { - - Model model = getCurrentTopModel(); - // configuration - ModelView topView = modelService.getModelView(model, userBean.getLoggedUser()); - - mapDataList = new ArrayList<>(); - - ClientMapData cmd = new ClientMapData(); - cmd.setMapConfig(topView); - cmd.setType("N/A"); - // coordinates converter - cmd.setcConverter(new CoordinationConverter(model)); - - mapDataList.add(cmd); - topModelMapData = cmd; - - for (ModelView view : topView.getSubmodels()) { - cmd = new ClientMapData(); - cmd.setMapConfig(view); - // coordinates converter - cmd.setcConverter(new CoordinationConverter(model.getSubmodelById(view.getIdObject()))); - cmd.setType(model.getSubmodelConnectionById(view.getIdObject()).getType().getCommonName()); - mapDataList.add(cmd); - } - } - - /** - * This method center map in the client using coordinates from client. - * - * @param actionEvent - * event from thefrom the client - */ - public void centerMap(final ActionEvent actionEvent) { - createSubmodelDialog(actionEvent); - - // we have plain coordinates (not lat lng) - String xCoord = getRequestParameter("xCoord"); - String yCoord = getRequestParameter("yCoord"); - String modelIdentifier = getRequestParameter("submodelId"); - if (modelIdentifier == null) { - sendError("submodelId param wasn't set"); - return; - } - Integer modelId = Integer.valueOf(modelIdentifier); - - ClientMapData selectedMapData = null; - for (ClientMapData mapData : getMapDataList()) { - if (mapData.getMapConfig().getIdObject().equals(modelId)) { - selectedMapData = mapData; - } - } - if (selectedMapData == null) { - sendError("Cannot find map with the identifier: " + modelId); - return; - } - - LatLng latLng; - if (xCoord != null && yCoord != null) { - double x = Double.parseDouble(xCoord); - double y = Double.parseDouble(yCoord); - latLng = selectedMapData.getcConverter().toLatLng(new Point2D.Double(x, y)); - } else { - String latCoord = getRequestParameter("latCoord"); - String lngCoord = getRequestParameter("lngCoord"); - double lat = Double.parseDouble(latCoord); - double lng = Double.parseDouble(lngCoord); - latLng = new LatLng(lat, lng); - } - centerMapInJavascript(latLng, selectedMapData); - } - - /** - * Method responsible for centering map in client using coordinates given as a - * parameter. - * - * @param mapData - * defines which map we want to center. If the value is not set then - * default one is selected - * - * @param latLng - * - coordinates - */ - private void centerMapInJavascript(final LatLng latLng, ClientMapData mapData) { - double lat = latLng.getLat(); - double lng = latLng.getLng(); - logger.debug("Center map in js (" + lat + "," + lng + ")"); - executeJavascript("customMap.setCenter(" + mapData.getMapConfig().getIdObject() + ", new google.maps.LatLng(" + lat + "," + lng + "));"); - } - - /** - * Check if user can see the map. - * - * @return <i>true</i> if user can see the map,<br/> - * <i> false otherwise</i> - */ - public boolean getUserHasViewPrivilege() { - Project project = getCurrentProject(); - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, project); - if (!result) { - logger.debug("User doesn't have privilege"); - } - return result; - } - - /** - * This is artifitial method called by the client side to pass some parameters - * to the bean: - * <ul> - * <li>{@link #centerCoordinateX},</li> - * <li>{@link #centerCoordinateY},</li> - * <li>{@link #selectedLayout},</li> - * <li>{@link #zoomLevel}.</li> - * </ul> - */ - public void actualizeParams() { - - } - - /** - * Returns the index of layout that is currently visualized. - * - * @return index of layout that is currently visualized. - */ - public Integer getSelectedLayoutIdentifier() { - if (topModelMapData.getSelectedLayout() == null) { - return null; - } else { - String str = topModelMapData.getSelectedLayout().replaceAll("[^0-9]", ""); - Integer id = null; - try { - id = Integer.parseInt(str); - } catch (NumberFormatException e) { - logger.warn("Problem with layout identifier: " + topModelMapData.getSelectedLayout()); - } - return id; - } - } - - /** - * Returns level on which the map is currently browsed. It's not equal to the - * zoom level, becuse zoom level is shifted by - * {@link lcsb.mapviewer.common.Configuration.MIN_ZOOM_LEVEL} value. - * - * @param mapData - * defines on which map we are looking for zoom level. If the value - * is not set then default one is selected - * @return level on which the map is currently browsed - */ - public Integer getLevel(ClientMapData mapData) { - String zoomLevel = mapData.getZoomLevel(); - if (zoomLevel == null) { - return null; - } - Integer res = null; - try { - res = Integer.valueOf(zoomLevel) - Configuration.MIN_ZOOM_LEVEL; - } catch (NumberFormatException e) { - logger.warn("Problem with zoomLevel: " + zoomLevel); - } - return res; - } - - @Override - public void clear() { - throw new NotImplementedException(); - } - - /** - * @return the modelService - * @see #modelService - */ - public IModelService getModelService() { - return modelService; - } - - /** - * @param modelService - * the modelService to set - * @see #modelService - */ - public void setModelService(IModelService modelService) { - this.modelService = modelService; - } - - /** - * @return the userBean - * @see #userBean - */ - public UserBean getUserBean() { - return userBean; - } - - /** - * @param userBean - * the userBean to set - * @see #userBean - */ - public void setUserBean(UserBean userBean) { - this.userBean = userBean; - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - /** - * @return the mapDataList - * @see #mapDataList - */ - public List<ClientMapData> getMapDataList() { - return mapDataList; - } - - /** - * Creates dialog on client side for submodel. - * - * @param actionEvent - * event from the client - */ - public void createSubmodelDialog(final ActionEvent actionEvent) { - try { - String dialogGroup = "_gmapForm:submodelDialogGroup"; - String idParamName = "submodelId"; - String dialogIdPrefix = "submodelDialog"; - - UIComponent panelGroup = findComponent(dialogGroup); - if (panelGroup == null) { - sendError("Cannot find " + dialogGroup + " component."); - return; - } - String id = getRequestParameter(idParamName); - if (id == null) { - sendError(idParamName + " request param cannot be null."); - return; - } - if (id.equals(getCurrentTopModel().getId() + "")) { - logger.debug("TopModel doesn't require window"); - return; - } - id = dialogIdPrefix + id; - for (UIComponent child : panelGroup.getChildren()) { - if (child instanceof Dialog) { - if (child.getId().equals(id)) { - logger.debug("Dialog " + id + " found"); - return; - } - } - } - for (ModelSubmodelConnection model : getCurrentTopModel().getSubmodelConnections()) { - Integer modelId = model.getSubmodel().getId(); - id = dialogIdPrefix + modelId; - Dialog dialog = new Dialog(); - dialog.setId(id); - dialog.setWidgetVar(id); - dialog.setHeader("Submodel: " + model.getSubmodel().getName()); - dialog.setMinimizable(true); - panelGroup.getChildren().add(dialog); - } - - RequestContext requestContext = RequestContext.getCurrentInstance(); - requestContext.update(dialogGroup); - - } catch (Exception e) { - logger.error(e, e); - sendError(e.getMessage()); - } - } - - /** - * Returns map configuration in Gson format. - * - * @return map configuration in Gson format - */ - public String getGsonConfiguration() { - return new Gson().toJson(getMapDataList().get(0).getMapConfig()); - } - - /** - * @return the topModelMapData - * @see #topModelMapData - */ - public ClientMapData getTopModelMapData() { - if (topModelMapData == null) { - updateModelView(); - } - return topModelMapData; - } - - /** - * @param topModelMapData - * the topModelMapData to set - * @see #topModelMapData - */ - public void setTopModelMapData(ClientMapData topModelMapData) { - this.topModelMapData = topModelMapData; - } - - /** - * Returns {@link ClientMapData} for (sub)model identified by identifier. - * - * @param identifier - * identifier of the model - * @return {@link ClientMapData} - */ - public ClientMapData getMapDataByMapIdentifier(String identifier) { - Integer id = Integer.parseInt(identifier); - return getMapDataByMapIdentifier(id); - } - - /** - * Returns {@link ClientMapData} for (sub)model identified by identifier. - * - * @param identifier - * identifier of the model - * @return {@link ClientMapData} - */ - public ClientMapData getMapDataByMapIdentifier(Integer identifier) { - // in case we haven't initialized mapdata we need to do it here (it's a - // workaround...) - if (getMapDataList().size() == 0) { - updateModelView(); - } - for (ClientMapData md : getMapDataList()) { - if (md.getMapConfig().getIdObject().equals(identifier)) { - return md; - } - } - return null; - } - - /** - * @return the configurationService - * @see #configurationService - */ - public IConfigurationService getConfigurationService() { - return configurationService; - } - - /** - * @param configurationService - * the configurationService to set - * @see #configurationService - */ - public void setConfigurationService(IConfigurationService configurationService) { - this.configurationService = configurationService; - } - - /** - * Sets zoom level for submodel. Parameters are passed using http request - * mechainsm/ - */ - public void setModelZoomLevel() { - String mapId = getRequestParameter("mapId"); - String zoomLevel = getRequestParameter("zoomLevel"); - - Integer id = Integer.valueOf(mapId); - - for (ClientMapData cmd : getMapDataList()) { - if (cmd.getMapConfig().getIdObject().equals(id)) { - cmd.setZoomLevel(zoomLevel); - return; - } - } - sendError("Cannot find model with id: " + id); - - } - - /** - * Sends list of aliases (with given identifiers) to the browser. Identifiers - * are passed as a json string in request parameter <i>ids</i>. Each - * identifier is a pair containing information about {@link Model#getId() - * model id} and {@link lcsb.mapviewer.model.map.species.Element#id alias id}. - * Data is very light - contains only information about the location on the - * model. - * - */ - public void retreiveLightAliases() { - List<Pair<Integer, Integer>> identifiers = deserializeJsonIds(getRequestParameter("ids")); - List<LightAliasView> list = modelService.getLightAliasesByIds(getCurrentTopModel(), identifiers); - LightAliasViewFactory factory = new LightAliasViewFactory(); - String string = factory.createGson(list); - executeJavascript("ServerConnector.addAliases(" + string + ");"); - } - - /** - * Sends list of reactions (with given identifiers) to the browser. - * Identifiers are passed as a json string in request parameter <i>ids</i>. - * Each identifier is a pair containing information about {@link Model#getId() - * model id} and {@link lcsb.mapviewer.model.map.reaction.Reaction#id reaction - * id}. - * - */ - public void retreiveLightReactions() { - List<Pair<Integer, Integer>> identifiers = deserializeJsonIds(getRequestParameter("ids")); - List<LightReactionView> list = modelService.getLightReactionsByIds(getCurrentTopModel(), identifiers); - LightReactionViewFactory factory = new LightReactionViewFactory(); - String string = factory.createGson(list); - executeJavascript("ServerConnector.addReactions('" + string + "');"); - } - - /** - * @return the fullAliasViewFactory - * @see #fullAliasViewFactory - */ - public FullAliasViewFactory getFullAliasViewFactory() { - if (fullAliasViewFactory == null) { - fullAliasViewFactory = findBean(FullAliasViewFactory.class); - } - return fullAliasViewFactory; - } - - /** - * @param fullAliasViewFactory - * the fullAliasViewFactory to set - * @see #fullAliasViewFactory - */ - public void setFullAliasViewFactory(FullAliasViewFactory fullAliasViewFactory) { - this.fullAliasViewFactory = fullAliasViewFactory; - } - - /** - * @return the currentMapId - * @see #currentMapId - */ - public final String getCurrentMapId() { - // if user didn't provide id then use default one - if (currentMapId == null) { - String tmp = confService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); - if (tmp == null) { - logger.warn("Cannot find default map in the system."); - } - setCurrentMapId(tmp); - } - return currentMapId; - } - - /** - * @param currentMapId - * the currentMapId to set - * @see #currentMapId - */ - public final void setCurrentMapId(String currentMapId) { - try { - fireVetoableChange(CURRENT_MODEL_ID_PROPERTY, this.currentMapId, currentMapId); - String oldValue = this.currentMapId; - this.currentMapId = currentMapId; - firePropertyChange(CURRENT_MODEL_ID_PROPERTY, oldValue, currentMapId); - } catch (PropertyVetoException e) { - logger.warn("Cannot change property: " + CURRENT_MODEL_ID_PROPERTY + ". Form: \"" + this.currentMapId + "\" into: \"" + currentMapId + "\""); - } - } - - /** - * Return {@link #currentMap currently browsed map}. - * - * @return currently browsed map - */ - protected final Model getCurrentTopModel() { - if (currentMap == null) { - setCurrentTopModel(this.getModelService().getLastModelByProjectId(getCurrentMapId(), userBean.getAuthenticationToken())); - } - return currentMap; - } - - /** - * @return the currentProject - * @see #currentProject - */ - public Project getCurrentProject() { - return getCurrentTopModel().getProject(); - } - - /** - * @param topModel - * the topModel to set - * @see #currentMap - */ - private void setCurrentTopModel(Model topModel) { - Model oldValue = this.currentMap; - this.currentMap = topModel; - firePropertyChange(CURRENT_MODEL_PROPERTY, oldValue, topModel); - } - - /** - * @return the currentProjectView - * @see #currentProjectView - */ - public ProjectView getCurrentProjectView() { - return currentProjectView; - } - - /** - * @param currentProjectView - * the currentProjectView to set - * @see #currentProjectView - */ - public void setCurrentProjectView(ProjectView currentProjectView) { - this.currentProjectView = currentProjectView; - } - - /** - * @return the projectService - * @see #projectService - */ - public IProjectService getProjectService() { - return projectService; - } - - /** - * @param projectService - * the projectService to set - * @see #projectService - */ - public void setProjectService(IProjectService projectService) { - this.projectService = projectService; - } - - /** - * @return the confService - * @see #confService - */ - public IConfigurationService getConfService() { - return confService; - } - - /** - * @param confService - * the confService to set - * @see #confService - */ - public void setConfService(IConfigurationService confService) { - this.confService = confService; - } - - /** - * Returns organism associated with currently viewed project. If organism is - * not set then {@link #DEFAULT_ORGANISM} is returned. - * - * @return organism associated with currently viewed project - */ - public MiriamData getOrganism() { - MiriamData organism = getCurrentProject().getOrganism(); - if (organism == null || organism.getResource().isEmpty()) { - organism = DEFAULT_ORGANISM; - } - return organism; - } + /** + * String representing {@link #currentMapId} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String CURRENT_MODEL_ID_PROPERTY = "CURRENT_MODEL_ID"; + + /** + * String representing {@link #currentMap} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String CURRENT_MODEL_PROPERTY = "CURRENT_MODEL"; + + /** + * Name of the session field that store {@link ClientMapData#centerCoordinateY y + * coordinate} of the browsable model (this will is used when page is + * refreshed). + */ + public static final String Y_COORD_SESSION_PARAM = "Y_COORD"; + + /** + * Name of the session field that store {@link ClientMapData#centerCoordinateX x + * coordinate} of the browsable model (this will is used when page is + * refreshed). + */ + public static final String X_COORD_SESSION_PARAM = "X_COORD"; + + /** + * Name of the session field that store {@link ClientMapData#zoomLevel zoom + * level} of the browsable model (this will is used when page is refreshed). + */ + public static final String ZOOM_LEVEL_SESSION_PARAM = "LEVEL"; + + /** + * Name of the session field that store {@link ClientMapData#selectedLayout + * selected layout} of the browsable model (this will is used when page is + * refreshed). + */ + public static final String SELECTED_LAYOUT_SESSION_PARAM = "SELECTED_LAYOUT"; + + /** + * Default organism by which results should be filtered (homo sapiens by + * default). + */ + + private static final MiriamData DEFAULT_ORGANISM = TaxonomyBackend.HUMAN_TAXONOMY; + + /** + * Object representing currently visualized project. + */ + private ProjectView currentProjectView = null; + + /** + * Name of the current project. + */ + private String currentMapId = null; + + /** + * Map currently browsed. + */ + private transient Model currentMap = null; + + /** + * This class store information about browsing single map/submap. + * + * @author Piotr Gawron + * + */ + public class ClientMapData implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Configuration of the map used by the javascript frontend. + */ + private ModelView mapConfig = null; + + /** + * Converter of coordinates dedicated to the map (every map must have a + * different converter, because the size and number of layers in the maps are + * different). + */ + private CoordinationConverter cConverter; + + /** + * Type of the model (used only in case of submodels). + */ + private String type = ""; + + /** + * X coordinate of map center. + */ + private String centerCoordinateX = ""; + + /** + * Y coordinate of map center. + */ + private String centerCoordinateY = ""; + + /** + * Level at which map is browsed. + */ + private String zoomLevel = "" + Configuration.MIN_ZOOM_LEVEL; + + /** + * Layout currently visualized. + */ + private String selectedLayout = ""; + + /** + * @return the mapConfig + * @see #mapConfig + */ + public ModelView getMapConfig() { + return mapConfig; + } + + /** + * @param mapConfig + * the mapConfig to set + * @see #mapConfig + */ + public void setMapConfig(ModelView mapConfig) { + this.mapConfig = mapConfig; + // set information about location and zooming (if it's set in the session) + if (getSessionParam(ZOOM_LEVEL_SESSION_PARAM + mapConfig.getIdObject()) != null) { + setZoomLevel((String) getSessionParam(ZOOM_LEVEL_SESSION_PARAM + mapConfig.getIdObject())); + // when we refresh map and have defined coordinates then tell the client + // side that it shouldn't fit it into the bounds + mapConfig.setFitMapBounds(false); + } else { + setZoomLevel(""); + } + if (getSessionParam(X_COORD_SESSION_PARAM + mapConfig.getIdObject()) != null) { + setCenterCoordinateX((String) getSessionParam(X_COORD_SESSION_PARAM + mapConfig.getIdObject())); + // when we refresh map and have defined coordinates then tell the client + // side that it shouldn't fit it into the bounds + mapConfig.setFitMapBounds(false); + } else { + setCenterCoordinateX(""); + } + if (getSessionParam(Y_COORD_SESSION_PARAM + mapConfig.getIdObject()) != null) { + setCenterCoordinateY((String) getSessionParam(Y_COORD_SESSION_PARAM + mapConfig.getIdObject())); + } else { + setCenterCoordinateY(""); + } + setSelectedLayout(""); + if (getSessionParam(SELECTED_LAYOUT_SESSION_PARAM + mapConfig.getIdObject()) != null) { + setSelectedLayout((String) getSessionParam(SELECTED_LAYOUT_SESSION_PARAM + mapConfig.getIdObject())); + } else { + if (mapConfig.getLayouts().size() > 0) { + setSelectedLayout("cv" + mapConfig.getLayouts().get(0).getIdObject()); + } else { + logger.warn("No layouts for model: " + mapConfig.getIdObject()); + + } + } + } + + /** + * @return the cConverter + * @see #cConverter + */ + public CoordinationConverter getcConverter() { + return cConverter; + } + + /** + * @param cConverter + * the cConverter to set + * @see #cConverter + */ + public void setcConverter(CoordinationConverter cConverter) { + this.cConverter = cConverter; + } + + /** + * @return the centerCoordinateX + * @see #centerCoordinateX + */ + public String getCenterCoordinateX() { + return centerCoordinateX; + } + + /** + * @param centerCoordinateX + * the centerCoordinateX to set + * @see #centerCoordinateX + */ + public void setCenterCoordinateX(String centerCoordinateX) { + if (centerCoordinateX != null && !centerCoordinateX.isEmpty()) { + addSessionParam(X_COORD_SESSION_PARAM + mapConfig.getIdObject(), centerCoordinateX); + } + this.centerCoordinateX = centerCoordinateX; + } + + /** + * @return the centerCoordinateY + * @see #centerCoordinateY + */ + public String getCenterCoordinateY() { + return centerCoordinateY; + } + + /** + * @param centerCoordinateY + * the centerCoordinateY to set + * @see #centerCoordinateY + */ + public void setCenterCoordinateY(String centerCoordinateY) { + if (centerCoordinateY != null && !centerCoordinateY.isEmpty()) { + addSessionParam(Y_COORD_SESSION_PARAM + mapConfig.getIdObject(), centerCoordinateY); + } + this.centerCoordinateY = centerCoordinateY; + } + + /** + * @return the zoomLevel + * @see #zoomLevel + */ + public String getZoomLevel() { + return zoomLevel; + } + + /** + * @param zoomLevel + * the zoomLevel to set + * @see #zoomLevel + */ + public void setZoomLevel(String zoomLevel) { + if (zoomLevel != null && !zoomLevel.isEmpty()) { + addSessionParam(ZOOM_LEVEL_SESSION_PARAM + mapConfig.getIdObject(), zoomLevel); + } + this.zoomLevel = zoomLevel; + } + + /** + * @return the selectedLayout + * @see #selectedLayout + */ + public String getSelectedLayout() { + return selectedLayout; + } + + /** + * @param selectedLayout + * the selectedLayout to set + * @see #selectedLayout + */ + public void setSelectedLayout(String selectedLayout) { + if (selectedLayout != null && !selectedLayout.isEmpty()) { + addSessionParam(SELECTED_LAYOUT_SESSION_PARAM + mapConfig.getIdObject(), selectedLayout); + } + this.selectedLayout = selectedLayout; + } + + /** + * @return the type + * @see #type + */ + public String getType() { + return type; + } + + /** + * @param type + * the type to set + * @see #type + */ + public void setType(String type) { + this.type = type; + } + + } + + /** + * Top map of currently browsed model. + */ + private ClientMapData topModelMapData = null; + + /** + * List of all model/submodels that are browsed in the current window. + */ + private List<ClientMapData> mapDataList = new ArrayList<>(); + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Service used to access information about users. + * + * @see IUserService + */ + @ManagedProperty(value = "#{UserService}") + private transient IUserService userService; + + /** + * Service that allows to access and manage models. + */ + @ManagedProperty(value = "#{ModelService}") + private transient IModelService modelService; + + /** + * Service that allows to access and manage models. + */ + @ManagedProperty(value = "#{ProjectService}") + private transient IProjectService projectService; + + /** + * Service used to access configuration parameters. + * + * @see IConfigurationService + */ + @ManagedProperty(value = "#{ConfigurationService}") + private transient IConfigurationService confService; + + /** + * Bean used for communication with the client side about the data related to + * users (including information about currently logged user). + * + * @see UserBean + */ + @ManagedProperty(value = "#{userMB}") + private transient UserBean userBean; + + /** + * Factory used to create {@link FullAliasView} elements. + */ + @ManagedProperty(value = "#{FullAliasViewFactory}") + private transient FullAliasViewFactory fullAliasViewFactory; + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(MapBean.class); + + /** + * Service used to access configuration parameters. + * + * @see IConfigurationService + */ + @ManagedProperty(value = "#{ConfigurationService}") + private transient IConfigurationService configurationService; + + @Override + public void init() { + // when model is changed we have to change few parameters as well + PropertyChangeListener modelChanged = new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent arg0) { + if (CURRENT_MODEL_PROPERTY.equals(arg0.getPropertyName())) { + updateModelView(); + } + } + + }; + addPropertyChangeListener(modelChanged); + + // when we change id we should propagate the change to model + PropertyChangeListener mapIdChangeListener = new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent arg0) { + if (CURRENT_MODEL_ID_PROPERTY.equals(arg0.getPropertyName())) { + try { + setCurrentTopModel(getModelService().getLastModelByProjectId((String) arg0.getNewValue(), + userBean.getAuthenticationToken())); + setCurrentProjectView(getProjectService().getProjectViewByProjectId(currentMap.getProject().getProjectId(), + userBean.getAuthenticationToken())); + } catch (Exception e) { + try { + setCurrentTopModel(getModelService().getLastModelByProjectId((String) arg0.getOldValue(), + userBean.getAuthenticationToken())); + } catch (SecurityException e1) { + logger.error(e1, e1); + } + logger.error(e, e); + } + } + } + + }; + addPropertyChangeListener(mapIdChangeListener); + + // when we change id we should propagate the change to model + VetoableChangeListener vetoMapIdChangeListener = new VetoableChangeListener() { + @Override + public void vetoableChange(PropertyChangeEvent arg0) throws PropertyVetoException { + if (!getProjectService().projectExists((String) arg0.getNewValue())) { + throw new PropertyVetoException("Project with id \"" + arg0.getNewValue() + "\" doesn't exist.", arg0); + } + } + + }; + addVetoablePropertyChangeListener(vetoMapIdChangeListener); + + // set id from request parameters (id is the url GET parameter) + setCurrentMapId(getRequestParameter("id")); + + } + + /** + * Refresh information about models. + */ + protected void updateModelView() { + + Model model = getCurrentTopModel(); + // configuration + ModelView topView = modelService.getModelView(model, userBean.getLoggedUser()); + + mapDataList = new ArrayList<>(); + + ClientMapData cmd = new ClientMapData(); + cmd.setMapConfig(topView); + cmd.setType("N/A"); + // coordinates converter + cmd.setcConverter(new CoordinationConverter(model)); + + mapDataList.add(cmd); + topModelMapData = cmd; + + for (ModelView view : topView.getSubmodels()) { + cmd = new ClientMapData(); + cmd.setMapConfig(view); + // coordinates converter + cmd.setcConverter(new CoordinationConverter(model.getSubmodelById(view.getIdObject()))); + cmd.setType(model.getSubmodelConnectionById(view.getIdObject()).getType().getCommonName()); + mapDataList.add(cmd); + } + } + + /** + * This method center map in the client using coordinates from client. + * + * @param actionEvent + * event from thefrom the client + */ + public void centerMap(final ActionEvent actionEvent) { + createSubmodelDialog(actionEvent); + + // we have plain coordinates (not lat lng) + String xCoord = getRequestParameter("xCoord"); + String yCoord = getRequestParameter("yCoord"); + String modelIdentifier = getRequestParameter("submodelId"); + if (modelIdentifier == null) { + sendError("submodelId param wasn't set"); + return; + } + Integer modelId = Integer.valueOf(modelIdentifier); + + ClientMapData selectedMapData = null; + for (ClientMapData mapData : getMapDataList()) { + if (mapData.getMapConfig().getIdObject().equals(modelId)) { + selectedMapData = mapData; + } + } + if (selectedMapData == null) { + sendError("Cannot find map with the identifier: " + modelId); + return; + } + + LatLng latLng; + if (xCoord != null && yCoord != null) { + double x = Double.parseDouble(xCoord); + double y = Double.parseDouble(yCoord); + latLng = selectedMapData.getcConverter().toLatLng(new Point2D.Double(x, y)); + } else { + String latCoord = getRequestParameter("latCoord"); + String lngCoord = getRequestParameter("lngCoord"); + double lat = Double.parseDouble(latCoord); + double lng = Double.parseDouble(lngCoord); + latLng = new LatLng(lat, lng); + } + centerMapInJavascript(latLng, selectedMapData); + } + + /** + * Method responsible for centering map in client using coordinates given as a + * parameter. + * + * @param mapData + * defines which map we want to center. If the value is not set then + * default one is selected + * + * @param latLng + * - coordinates + */ + private void centerMapInJavascript(final LatLng latLng, ClientMapData mapData) { + double lat = latLng.getLat(); + double lng = latLng.getLng(); + logger.debug("Center map in js (" + lat + "," + lng + ")"); + executeJavascript("customMap.setCenter(" + mapData.getMapConfig().getIdObject() + ", new google.maps.LatLng(" + lat + + "," + lng + "));"); + } + + /** + * Check if user can see the map. + * + * @return <i>true</i> if user can see the map,<br/> + * <i> false otherwise</i> + */ + public boolean getUserHasViewPrivilege() { + Project project = getCurrentProject(); + User user = userBean.getLoggedUser(); + boolean result = userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, project); + if (!result) { + logger.debug("User doesn't have privilege"); + } + return result; + } + + /** + * This is artifitial method called by the client side to pass some parameters + * to the bean: + * <ul> + * <li>{@link #centerCoordinateX},</li> + * <li>{@link #centerCoordinateY},</li> + * <li>{@link #selectedLayout},</li> + * <li>{@link #zoomLevel}.</li> + * </ul> + */ + public void actualizeParams() { + + } + + /** + * Returns the index of layout that is currently visualized. + * + * @return index of layout that is currently visualized. + */ + public Integer getSelectedLayoutIdentifier() { + if (topModelMapData.getSelectedLayout() == null) { + return null; + } else { + String str = topModelMapData.getSelectedLayout().replaceAll("[^0-9]", ""); + Integer id = null; + try { + id = Integer.parseInt(str); + } catch (NumberFormatException e) { + logger.warn("Problem with layout identifier: " + topModelMapData.getSelectedLayout()); + } + return id; + } + } + + /** + * Returns level on which the map is currently browsed. It's not equal to the + * zoom level, becuse zoom level is shifted by + * {@link lcsb.mapviewer.common.Configuration.MIN_ZOOM_LEVEL} value. + * + * @param mapData + * defines on which map we are looking for zoom level. If the value is + * not set then default one is selected + * @return level on which the map is currently browsed + */ + public Integer getLevel(ClientMapData mapData) { + String zoomLevel = mapData.getZoomLevel(); + if (zoomLevel == null) { + return null; + } + Integer res = null; + try { + res = Integer.valueOf(zoomLevel) - Configuration.MIN_ZOOM_LEVEL; + } catch (NumberFormatException e) { + logger.warn("Problem with zoomLevel: " + zoomLevel); + } + return res; + } + + @Override + public void clear() { + throw new NotImplementedException(); + } + + /** + * @return the modelService + * @see #modelService + */ + public IModelService getModelService() { + return modelService; + } + + /** + * @param modelService + * the modelService to set + * @see #modelService + */ + public void setModelService(IModelService modelService) { + this.modelService = modelService; + } + + /** + * @return the userBean + * @see #userBean + */ + public UserBean getUserBean() { + return userBean; + } + + /** + * @param userBean + * the userBean to set + * @see #userBean + */ + public void setUserBean(UserBean userBean) { + this.userBean = userBean; + } + + /** + * @return the userService + * @see #userService + */ + public IUserService getUserService() { + return userService; + } + + /** + * @param userService + * the userService to set + * @see #userService + */ + public void setUserService(IUserService userService) { + this.userService = userService; + } + + /** + * @return the mapDataList + * @see #mapDataList + */ + public List<ClientMapData> getMapDataList() { + return mapDataList; + } + + /** + * Creates dialog on client side for submodel. + * + * @param actionEvent + * event from the client + */ + public void createSubmodelDialog(final ActionEvent actionEvent) { + try { + String dialogGroup = "_gmapForm:submodelDialogGroup"; + String idParamName = "submodelId"; + String dialogIdPrefix = "submodelDialog"; + + UIComponent panelGroup = findComponent(dialogGroup); + if (panelGroup == null) { + sendError("Cannot find " + dialogGroup + " component."); + return; + } + String id = getRequestParameter(idParamName); + if (id == null) { + sendError(idParamName + " request param cannot be null."); + return; + } + if (id.equals(getCurrentTopModel().getId() + "")) { + logger.debug("TopModel doesn't require window"); + return; + } + id = dialogIdPrefix + id; + for (UIComponent child : panelGroup.getChildren()) { + if (child instanceof Dialog) { + if (child.getId().equals(id)) { + logger.debug("Dialog " + id + " found"); + return; + } + } + } + for (ModelSubmodelConnection model : getCurrentTopModel().getSubmodelConnections()) { + Integer modelId = model.getSubmodel().getId(); + id = dialogIdPrefix + modelId; + Dialog dialog = new Dialog(); + dialog.setId(id); + dialog.setWidgetVar(id); + dialog.setHeader("Submodel: " + model.getSubmodel().getName()); + dialog.setMinimizable(true); + panelGroup.getChildren().add(dialog); + } + + RequestContext requestContext = RequestContext.getCurrentInstance(); + requestContext.update(dialogGroup); + + } catch (Exception e) { + logger.error(e, e); + sendError(e.getMessage()); + } + } + + /** + * Returns map configuration in Gson format. + * + * @return map configuration in Gson format + */ + public String getGsonConfiguration() { + return new Gson().toJson(getMapDataList().get(0).getMapConfig()); + } + + /** + * @return the topModelMapData + * @see #topModelMapData + */ + public ClientMapData getTopModelMapData() { + if (topModelMapData == null) { + updateModelView(); + } + return topModelMapData; + } + + /** + * @param topModelMapData + * the topModelMapData to set + * @see #topModelMapData + */ + public void setTopModelMapData(ClientMapData topModelMapData) { + this.topModelMapData = topModelMapData; + } + + /** + * Returns {@link ClientMapData} for (sub)model identified by identifier. + * + * @param identifier + * identifier of the model + * @return {@link ClientMapData} + */ + public ClientMapData getMapDataByMapIdentifier(String identifier) { + Integer id = Integer.parseInt(identifier); + return getMapDataByMapIdentifier(id); + } + + /** + * Returns {@link ClientMapData} for (sub)model identified by identifier. + * + * @param identifier + * identifier of the model + * @return {@link ClientMapData} + */ + public ClientMapData getMapDataByMapIdentifier(Integer identifier) { + // in case we haven't initialized mapdata we need to do it here (it's a + // workaround...) + if (getMapDataList().size() == 0) { + updateModelView(); + } + for (ClientMapData md : getMapDataList()) { + if (md.getMapConfig().getIdObject().equals(identifier)) { + return md; + } + } + return null; + } + + /** + * @return the configurationService + * @see #configurationService + */ + public IConfigurationService getConfigurationService() { + return configurationService; + } + + /** + * @param configurationService + * the configurationService to set + * @see #configurationService + */ + public void setConfigurationService(IConfigurationService configurationService) { + this.configurationService = configurationService; + } + + /** + * Sets zoom level for submodel. Parameters are passed using http request + * mechainsm/ + */ + public void setModelZoomLevel() { + String mapId = getRequestParameter("mapId"); + String zoomLevel = getRequestParameter("zoomLevel"); + + Integer id = Integer.valueOf(mapId); + + for (ClientMapData cmd : getMapDataList()) { + if (cmd.getMapConfig().getIdObject().equals(id)) { + cmd.setZoomLevel(zoomLevel); + return; + } + } + sendError("Cannot find model with id: " + id); + + } + + /** + * Sends list of aliases (with given identifiers) to the browser. Identifiers + * are passed as a json string in request parameter <i>ids</i>. Each identifier + * is a pair containing information about {@link Model#getId() model id} and + * {@link lcsb.mapviewer.model.map.species.Element#id alias id}. Data is very + * light - contains only information about the location on the model. + * + */ + public void retreiveLightAliases() { + List<Pair<Integer, Integer>> identifiers = deserializeJsonIds(getRequestParameter("ids")); + List<LightAliasView> list = modelService.getLightAliasesByIds(getCurrentTopModel(), identifiers); + LightAliasViewFactory factory = new LightAliasViewFactory(); + String string = factory.createGson(list); + executeJavascript("ServerConnector.addAliases(" + string + ");"); + } + + /** + * Sends list of reactions (with given identifiers) to the browser. Identifiers + * are passed as a json string in request parameter <i>ids</i>. Each identifier + * is a pair containing information about {@link Model#getId() model id} and + * {@link lcsb.mapviewer.model.map.reaction.Reaction#id reaction id}. + * + */ + public void retreiveLightReactions() { + List<Pair<Integer, Integer>> identifiers = deserializeJsonIds(getRequestParameter("ids")); + List<LightReactionView> list = modelService.getLightReactionsByIds(getCurrentTopModel(), identifiers); + LightReactionViewFactory factory = new LightReactionViewFactory(); + String string = factory.createGson(list); + executeJavascript("ServerConnector.addReactions('" + string + "');"); + } + + /** + * @return the fullAliasViewFactory + * @see #fullAliasViewFactory + */ + public FullAliasViewFactory getFullAliasViewFactory() { + if (fullAliasViewFactory == null) { + fullAliasViewFactory = findBean(FullAliasViewFactory.class); + } + return fullAliasViewFactory; + } + + /** + * @param fullAliasViewFactory + * the fullAliasViewFactory to set + * @see #fullAliasViewFactory + */ + public void setFullAliasViewFactory(FullAliasViewFactory fullAliasViewFactory) { + this.fullAliasViewFactory = fullAliasViewFactory; + } + + /** + * @return the currentMapId + * @see #currentMapId + */ + public final String getCurrentMapId() { + // if user didn't provide id then use default one + if (currentMapId == null) { + String tmp = confService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); + if (tmp == null) { + logger.warn("Cannot find default map in the system."); + } + setCurrentMapId(tmp); + } + return currentMapId; + } + + /** + * @param currentMapId + * the currentMapId to set + * @see #currentMapId + */ + public final void setCurrentMapId(String currentMapId) { + try { + fireVetoableChange(CURRENT_MODEL_ID_PROPERTY, this.currentMapId, currentMapId); + String oldValue = this.currentMapId; + this.currentMapId = currentMapId; + firePropertyChange(CURRENT_MODEL_ID_PROPERTY, oldValue, currentMapId); + } catch (PropertyVetoException e) { + logger.warn("Cannot change property: " + CURRENT_MODEL_ID_PROPERTY + ". Form: \"" + this.currentMapId + + "\" into: \"" + currentMapId + "\""); + } + } + + /** + * Return {@link #currentMap currently browsed map}. + * + * @return currently browsed map + */ + protected final Model getCurrentTopModel() { + if (currentMap == null) { + try { + setCurrentTopModel( + this.getModelService().getLastModelByProjectId(getCurrentMapId(), userBean.getAuthenticationToken())); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + return currentMap; + } + + /** + * @return the currentProject + * @see #currentProject + */ + public Project getCurrentProject() { + return getCurrentTopModel().getProject(); + } + + /** + * @param topModel + * the topModel to set + * @see #currentMap + */ + private void setCurrentTopModel(Model topModel) { + Model oldValue = this.currentMap; + this.currentMap = topModel; + firePropertyChange(CURRENT_MODEL_PROPERTY, oldValue, topModel); + } + + /** + * @return the currentProjectView + * @see #currentProjectView + */ + public ProjectView getCurrentProjectView() { + return currentProjectView; + } + + /** + * @param currentProjectView + * the currentProjectView to set + * @see #currentProjectView + */ + public void setCurrentProjectView(ProjectView currentProjectView) { + this.currentProjectView = currentProjectView; + } + + /** + * @return the projectService + * @see #projectService + */ + public IProjectService getProjectService() { + return projectService; + } + + /** + * @param projectService + * the projectService to set + * @see #projectService + */ + public void setProjectService(IProjectService projectService) { + this.projectService = projectService; + } + + /** + * @return the confService + * @see #confService + */ + public IConfigurationService getConfService() { + return confService; + } + + /** + * @param confService + * the confService to set + * @see #confService + */ + public void setConfService(IConfigurationService confService) { + this.confService = confService; + } + + /** + * Returns organism associated with currently viewed project. If organism is not + * set then {@link #DEFAULT_ORGANISM} is returned. + * + * @return organism associated with currently viewed project + */ + public MiriamData getOrganism() { + MiriamData organism = getCurrentProject().getOrganism(); + if (organism == null || organism.getResource().isEmpty()) { + organism = DEFAULT_ORGANISM; + } + return organism; + } } diff --git a/web/src/main/java/lcsb/mapviewer/bean/ProjectBean.java b/web/src/main/java/lcsb/mapviewer/bean/ProjectBean.java index 2dc3e22ad04d8d13be320d3621936042a2e1fa8f..6a6c30a73b45ce4dc5f82c14421deb226c664252 100644 --- a/web/src/main/java/lcsb/mapviewer/bean/ProjectBean.java +++ b/web/src/main/java/lcsb/mapviewer/bean/ProjectBean.java @@ -76,1434 +76,1448 @@ import lcsb.mapviewer.services.view.ProjectView; @ViewScoped public class ProjectBean extends AbstractManagedBean implements Serializable { - /** - * String representing {@link #selectedProject} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String SELECTED_PROJECT_PROPERTY = "SELECTED_PROJECT"; - - /** - * String representing {@link #mapFile} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String MAP_FILE_PROPERTY = "MAP_FILE"; - - /** - * String representing {@link #newMapAutoResize} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String AUTO_RESIZE_MAP_PROPERTY = "AUTO_RESIZE_MAP"; - - /** - * String representing {@link #newProjectId} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String PROJECT_ID_PROPERTY = "PROJECT_ID"; - - /** - * String representing {@link #newMapVersion} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String MAP_VERSION_PROPERTY = "MAP_VERSION"; - - /** - * String representing {@link #selectedAnnotatorTreeNodeData} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String SELECTED_ANNOTATOR_TREE_NODE_DATA_PROPERTY = "SELECTED_ANNOTATOR_TREE_NODE_DATA"; - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(ProjectBean.class); - - /** - * List of projects visible on client side. It's lazy loaded. - */ - private List<ProjectView> projects = null; - - /** - * Project selected for editing (or new project to create). - */ - private ProjectView selectedProject; - - /** - * Identifier of the project. - */ - private String newProjectId = "auto_name"; - - /** - * Name of the project. - */ - private String newProjectName = "UNKNOWN DISEASE MAP"; - - /** - * Disease of the project. - */ - private String newProjectDisease; - - /** - * Organism of the project. - */ - private String newProjectOrganism; - - /** - * Version of the project. - */ - private String newMapVersion = "0"; - - /** - * Should we annotate model automatically. - */ - private String annotateModel = "false"; - - /** - * Should we cache data from external resources connected to this map. - */ - private String cacheModel = "false"; - - /** - * Should the maunal annotations of the model be verified. - */ - private String verifyAnnotationsModel = "false"; - - /** - * Should we resize the model (to normalize margins). - */ - private String newMapAutoResize = "true"; - - /** - * Is the uploaded model a complex multi-files project or not. - */ - private String complexModel = "false"; - - /** - * Is the {@link lcsb.mapviewer.services.utils.data.BuildInLayout#NORMAL} - * default layout when generating new project. - */ - private String networkLayoutAsDefault = "false"; - - /** - * List of zip entries corresponding to model (and submodels) in the complex - * project thas is to be uploaded. - */ - private List<ModelZipEntryFile> modelZipEntries = new ArrayList<ModelZipEntryFile>(); - - /** - * List of zip entries corresponding to data mining files in the complex - * project. - */ - private List<DataMiningZipEntryFile> dataMiningZipEntries = new ArrayList<DataMiningZipEntryFile>(); - - /** - * List of zip entries corresponding to layout files in the complex project. - */ - private List<LayoutZipEntryFile> layoutZipEntries = new ArrayList<LayoutZipEntryFile>(); - - /** - * Should the map be displayed in SBGN format. - */ - private String sbgnFormat = "false"; - - private String semanticOverlay = "false"; - - /** - * List of zip entries corresponding to - * {@link lcsb.mapviewer.model.map.OverviewImage OverviewImage} files in the - * complex project. - */ - private List<ImageZipEntryFile> imageZipEntries = new ArrayList<ImageZipEntryFile>(); - - /** - * Uploaded file with the data in CellDesigner format. - */ - private File mapFile = null; - - /** - * Service used to access information about projects. - * - * @see IProjectService - */ - @ManagedProperty(value = "#{ProjectService}") - private transient IProjectService projectService; - - /** - * Bean used for communication with the client side about the data related to - * users (including information about currently logged user). - * - * @see UserBean - */ - @ManagedProperty(value = "#{userMB}") - private transient UserBean userBean; - - /** - * Bean used for communication with the client side about the data related to - * layouts. - * - * @see UserBean - */ - @ManagedProperty(value = "#{layoutMB}") - private transient LayoutBean layoutBean; - - /** - * Service used to access configuration parameters. - * - * @see IConfigurationService - */ - @ManagedProperty(value = "#{ConfigurationService}") - private transient IConfigurationService configurationService; - - /** - * Service used to access information about users. - * - * @see IUserService - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * Service that allows to access and manage models. - */ - @ManagedProperty(value = "#{ModelService}") - private transient IModelService modelService; - - /** - * Tree with information about classes that can be annotated and which - * annotators should be used for these classes. - */ - private TreeNode annotatorsTree; - - /** - * Element of {@link #annotatorsTree} that is currently edited. - */ - private AnnotatedObjectTreeRow selectedAnnotatorTreeNodeData; - - /** - * List of annotators for {@link #selectedAnnotatorTreeNodeData} that is - * currently edited. - */ - private DualListModel<String> annotators = new DualListModel<String>(); - - /** - * List of valid {@link MiriamType} for {@link #selectedAnnotatorTreeNodeData} - * that is currently edited. - */ - private DualListModel<MiriamType> validMiriam = new DualListModel<MiriamType>(); - - /** - * List of required {@link MiriamType} for - * {@link #selectedAnnotatorTreeNodeData} that is currently edited. - */ - private DualListModel<MiriamType> requiredMiriam = new DualListModel<MiriamType>(); - - /** - * List of all {@link DataMiningType}. - */ - private List<DataMiningType> dataMiningTypes = new ArrayList<DataMiningType>(); - - /** - * Listener used to verify the modification of the project. - */ - private transient VetoableChangeListener selectedProjectVetoChanged; - - { - selectedProjectVetoChanged = new VetoableChangeListener() { - @Override - public void vetoableChange(final PropertyChangeEvent arg0) throws PropertyVetoException { - try { - if (SELECTED_PROJECT_PROPERTY.equals(arg0.getPropertyName())) { - - ProjectView oldVal = (ProjectView) arg0.getOldValue(); - ProjectView newVal = (ProjectView) arg0.getNewValue(); - - // if we change to null then it's ok - if (newVal == null) { - return; - } - - ProjectView fromDb = projectService.getProjectViewByProjectId(newVal.getProjectId(), userBean.getAuthenticationToken()); - String defaultMap = configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); - - // check if we change the name properly - if (oldVal != null && oldVal.getIdObject() != null && oldVal.getIdObject().equals(newVal.getIdObject())) { - if (oldVal.getProjectId().equals(newVal.getProjectId())) { - // name hasn't changed - return; - } else if (oldVal.getProjectId().equals(defaultMap)) { - // we try to change the name of default map - throw new PropertyVetoException("Cannot change the name of default project.", arg0); - } else if (fromDb == null || fromDb.getIdObject() == null) { - // there is no project with the new name - return; - } else if (fromDb.getIdObject().equals(newVal.getIdObject())) { - // project with the same id is the same project - return; - } else { - throw new PropertyVetoException("Cannot change the name of project. Project with this name already exists.", arg0); - } - - } - - if (fromDb != null && fromDb.getIdObject() != null) { - if (fromDb.getIdObject().equals(newVal.getIdObject())) { - return; - } else { - throw new PropertyVetoException("Project with this name already exists.", arg0); - } - } - - } - } catch (Exception e) { - throw new PropertyVetoException("Unexpected problem: " + e.getMessage(), arg0); - } - } - }; - } - - @Override - public void init() { - - addVetoablePropertyChangeListener(selectedProjectVetoChanged); - - // uploaded file chagnge listener - PropertyChangeListener mapFileChangeListener = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (MAP_FILE_PROPERTY.equals(arg0.getPropertyName())) { - File file = (File) arg0.getNewValue(); - clearZipEntriesData(); - complexModel = "false"; - if (file != null) { - if (file.getName().toLowerCase().endsWith("zip")) { - // when zip file is uploaded preprocess it to retrieve entries in - // zip file - ZipEntryFileFactory zefFactory = new ZipEntryFileFactory(); - complexModel = "true"; - try { - ZipFile zipFile = new ZipFile(file); - Enumeration<? extends ZipEntry> entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - ZipEntryFile zef = zefFactory.createZipEntryFile(entry, zipFile); - if (zef != null) { - // assign zip entries to proper lists - if (zef instanceof ModelZipEntryFile) { - modelZipEntries.add((ModelZipEntryFile) zef); - } else if (zef instanceof ImageZipEntryFile) { - imageZipEntries.add((ImageZipEntryFile) zef); - } else if (zef instanceof LayoutZipEntryFile) { - layoutZipEntries.add((LayoutZipEntryFile) zef); - } else if (zef instanceof DataMiningZipEntryFile) { - dataMiningZipEntries.add((DataMiningZipEntryFile) zef); - } else { - logger.warn("Unknown class type: " + zef.getClass()); - sendError("Internal server error"); - } - } - } - zipFile.close(); - } catch (IOException e) { - logger.error(e, e); - } - } - } - String name = FilenameUtils.getName(file.getName()).replaceAll(" ", "_"); - if (name.indexOf("-cd-") > 0) { - name = name.substring(0, name.indexOf("-cd-")); - } - setNewProjectId(name); - } - } - - }; - addPropertyChangeListener(mapFileChangeListener); - - annotatorsTree = projectService.createClassAnnotatorTree(userBean.getLoggedUser()); - - // this listener will be called when user start to edit list of - // ElementAnnotator for a given class type - PropertyChangeListener selectedAnnotatorTreeNodeChangeListener = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (SELECTED_ANNOTATOR_TREE_NODE_DATA_PROPERTY.equals(arg0.getPropertyName())) { - AnnotatedObjectTreeRow data = (AnnotatedObjectTreeRow) arg0.getNewValue(); - annotators = new DualListModel<String>(data.getValidAnnotators(), data.getUsedAnnotators()); - validMiriam = new DualListModel<MiriamType>(data.getMissingValidAnnotations(), data.getValidAnnotations()); - requiredMiriam = new DualListModel<MiriamType>(data.getMissingRequiredAnnotations(), data.getRequiredAnnotations()); - } - } - - }; - - addPropertyChangeListener(selectedAnnotatorTreeNodeChangeListener); - - Listener<ObjectAddedEvent> layoutAddedListener = new Listener<ObjectAddedEvent>(ObjectAddedEvent.class) { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(ObjectAddedEvent event) { - boolean projectFound = false; - LayoutView layout = (LayoutView) event.getObject(); - - for (ProjectView project : getProjects()) { - if (project.getModelId() != null && project.getModelId().equals(layout.getModelId())) { - projectFound = true; - project.addLayout(layout); - } - } - - if (!projectFound) { - logger.warn("After adding layout cannot find project for the layout. LayoutId: " + layout.getIdObject() + "; ModelId: " + layout.getModelId()); - } - } - }; - layoutBean.registerListener(layoutAddedListener); - - layoutBean.registerListener(createLayoutRemovedListener()); - - setSelectedAnnotatorTreeNodeData((AnnotatedObjectTreeRow) annotatorsTree.getData()); - - for (DataMiningType dm : DataMiningType.values()) { - dataMiningTypes.add(dm); - } - - // when new project is added refresh list of projects - registerListener(new Listener<ObjectAddedEvent>(ObjectAddedEvent.class) { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(ObjectAddedEvent event) { - refreshProjectList(null); - } - }); - - customizeUserParameters(); - - } - - /** - * Sets default values for some checkboxes specific for a user. (The values - * are stored in databsae) - */ - public void customizeUserParameters() { - if (userBean.getLoggedUser() != null) { - User user = userBean.getLoggedUser(); - if (user.getAnnotationSchema() != null) { - setSbgnFormat(user.getAnnotationSchema().getSbgnFormat()); - setNetworkLayoutAsDefault(user.getAnnotationSchema().getNetworkLayoutAsDefault()); - } - } - } - - /** - * Sets {@link #networkLayoutAsDefault}. - * - * @param value - * new value - */ - private void setNetworkLayoutAsDefault(Boolean value) { - if (value) { - setNetworkLayoutAsDefault("true"); - } else { - setNetworkLayoutAsDefault("false"); - } - } - - /** - * Sets {@link #sbgnFormat}. - * - * @param value - * new value - */ - private void setSbgnFormat(boolean value) { - if (value) { - setSbgnFormat("true"); - } else { - setSbgnFormat("false"); - } - } - - /** - * Creates listener that should be called when layout is removed. - * - * @return listener that should be called when layout is removed - */ - public Listener<ObjectRemovedEvent> createLayoutRemovedListener() { - return new Listener<ObjectRemovedEvent>(ObjectRemovedEvent.class) { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(ObjectRemovedEvent event) { - boolean projectFound = false; - LayoutView layout = (LayoutView) event.getObject(); - for (ProjectView project : getProjects()) { - if (project.getModelId().equals(layout.getModelId())) { - projectFound = true; - LayoutView layoutToRemove = null; - for (LayoutView oldLayout : project.getLayouts()) { - if (oldLayout.getIdObject().equals(layout.getIdObject())) { - layoutToRemove = oldLayout; - } - } - if (layoutToRemove == null) { - logger.warn( - "After removing layout from db cannot find layout in the project to remove. LayoutId: " + layout.getIdObject() + "; ModelId: " - + layout.getModelId()); - } else { - project.getLayouts().remove(layoutToRemove); - } - } - } - - if (!projectFound) { - logger.warn("After removing layout cannot find project for the layout. LayoutId: " + layout.getIdObject() + "; ModelId: " + layout.getModelId()); - } - } - }; - } - - /** - * Refresh list of projects. - * - * @param actionEvent - * event from thefrom the client - */ - public void refreshProjectList(final ActionEvent actionEvent) { - if (projects == null) { - logger.warn("Strange behaviour: refreshing project list withouth accessing..."); - projects = new ArrayList<>(); - } - projects.clear(); - List<ProjectView> localProjectList = projectService.getAllProjectViews(userBean.getAuthenticationToken()); - for (ProjectView projectRow : localProjectList) { - projects.add(projectRow); - } - Collections.sort(projects); - } - - /** - * This method handle upload of a file. - * - * @param event - * event send by the client with a file reference - */ - public void handleFileUpload(final FileUploadEvent event) { - try { - logger.debug(event.getFile().getFileName() + " is uploaded."); - UploadedFile uploadedFile = event.getFile(); - String filename = FilenameUtils.getBaseName(uploadedFile.getFileName()); - String extension = FilenameUtils.getExtension(uploadedFile.getFileName()); - File file = File.createTempFile(filename + "-cd-", "." + extension); - file.delete(); - InputStream input = uploadedFile.getInputstream(); - Files.copy(input, file.toPath()); - input.close(); - - this.setMapFile(file); - } catch (Exception e) { - sendError("Problem with uploading...", e); - } - } - - /** - * Generates project based on the information provided by the client. - * - * @param file - * file with the model in CellDesigner format - * @throws SecurityException - */ - protected void generateProject(final File file) throws SecurityException { - // if project with this name already exists then add random suffix - String projectId = getNewProjectId(); - if (projectService.projectExists(getNewProjectId())) { - sendError("Project with identifier: \"" + getNewProjectId() + "\" already exists."); - return; - } - - // get proper paths: - // to directory with images - String imagePath = getProjectDeployPath() + "/../map_images/" + md5(projectId) + "/"; - String version = getNewMapVersion(); - - boolean autoResize = newMapAutoResize.equalsIgnoreCase("true"); - - CreateProjectParams params = new CreateProjectParams(); - - params.complex("true".equalsIgnoreCase(complexModel)); - params.projectId(projectId); - params.projectName(newProjectName); - params.projectDisease(newProjectDisease); - params.projectOrganism(newProjectOrganism); - params.version(version); - params.projectFile(file); - params.autoResize(autoResize); - params.images(true); - params.async(true); - params.notifyEmail(userBean.getLoggedUser().getEmail()); - params.projectDir(imagePath); - params.annotatorsMap(annotatorsTree); - params.addUser(userBean.getLogin(), null); - params.annotations("true".equalsIgnoreCase(annotateModel)); - params.analyzeAnnotations("true".equalsIgnoreCase(verifyAnnotationsModel)); - params.cacheModel("true".equalsIgnoreCase(cacheModel)); - params.validAnnotations(annotatorsTree); - params.requiredAnnotations(annotatorsTree); - params.authenticationToken(userBean.getAuthenticationToken()); - for (ZipEntryFile submodel : getZipEntries()) { - params.addZipEntry(submodel); - } - params.sbgnFormat("true".equalsIgnoreCase(sbgnFormat)); - params.semanticZoom("true".equalsIgnoreCase(semanticOverlay)); - params.networkLayoutAsDefault("true".equalsIgnoreCase(networkLayoutAsDefault)); - projectService.createProject(params); - projectService.updateClassAnnotatorTreeForUser( - userBean.getLoggedUser(), annotatorsTree, sbgnFormat.equalsIgnoreCase("true"), networkLayoutAsDefault.equalsIgnoreCase("true")); - - ObjectAddedEvent event = new ObjectAddedEvent(projectService.getProjectByProjectId(projectId, userBean.getAuthenticationToken())); - callListeners(event); - } - - /** - * Returns list of all zip entries in the currently processed file. - * - * @return list of all zip entries in the currently processed file - */ - private Collection<ZipEntryFile> getZipEntries() { - List<ZipEntryFile> result = new ArrayList<ZipEntryFile>(); - result.addAll(modelZipEntries); - result.addAll(imageZipEntries); - result.addAll(layoutZipEntries); - result.addAll(dataMiningZipEntries); - return result; - } - - /** - * Method that computes md5 hash for a given {@link String}. - * - * @param data - * input string - * @return md5 hash for input string - */ - private String md5(String data) { - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - byte[] mdbytes = md.digest(data.getBytes()); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < mdbytes.length; i++) { - // CHECKSTYLE:OFF - // this magic formula transforms int into hex value - sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); - // CHECKSTYLE:ON - } - return sb.toString(); - } catch (NoSuchAlgorithmException e) { - logger.fatal("Problem with instance of MD5 encoder", e); - } - - return null; - } - - /** - * Returns project currently selected and edited by the client side. - * - * @return project view currently selected and edited by the client side - */ - public ProjectView getSelectedProject() { - if (selectedProject == null) { - selectedProject = projectService.createEmpty(); - } - return selectedProject; - } - - /** - * Set new currently selected and edited project. - * - * @param selectedProject - * view of the new currently selected and edited project - */ - public void setSelectedProject(final ProjectView selectedProject) { - ProjectView oldValue = this.selectedProject; - this.selectedProject = selectedProject; - try { - fireVetoableChange(SELECTED_PROJECT_PROPERTY, oldValue, selectedProject); - firePropertyChange(SELECTED_PROJECT_PROPERTY, oldValue, selectedProject); - logger.debug("Selected project was set to: " + this.selectedProject.getProjectId()); - } catch (PropertyVetoException e) { - this.selectedProject = oldValue; - sendError(e.getMessage(), e); - } - } - - /** - * Method which update a project. - * - * @param actionEvent - * event from thefrom the client - * @throws UserAccessException - */ - public void updateSelectedProject(final ActionEvent actionEvent) throws UserAccessException { - - // first we need small trick (maybe this should be improved) - - ProjectView newProject = selectedProject; - // get old version of the project from db - ProjectView oldProject = projectService.getProjectViewById(newProject.getIdObject(), userBean.getAuthenticationToken()); - - // set old version - setSelectedProject(oldProject); - // now, change to the new one (property change listener will ensure that - // everything is fine) - setSelectedProject(newProject); - - // if everything is ok then update in db - if (selectedProject != null) { - projectService.updateProject(selectedProject); - } else { - logger.warn("Problem during updating project..."); - } - refreshProjectList(actionEvent); - - callListeners(new ObjectModifiedEvent(newProject)); - } - - /** - * Removes project selected by client. - * - * @param actionEvent - * client side action - */ - public void removeSelectedProject(final ActionEvent actionEvent) { - try { - logger.debug("Removing project: " + selectedProject); - String defaultMap = configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); - String projectId = selectedProject.getProjectId(); - - // find out what is the name of the project in db - ProjectView project = projectService.getProjectViewById(selectedProject.getIdObject(), userBean.getAuthenticationToken()); - if (project != null) { - projectId = project.getProjectId(); - } - - logger.debug("Removing project: " + projectId); - - // if the project name is a default one then don't remove it - if (defaultMap.equals(projectId)) { - sendError("Cannot remove default map. To remove this map change the default map in configuration tab first."); - } else { - projectService.removeProject(selectedProject, getProjectDeployPath(), true, userBean.getAuthenticationToken()); - callListeners(new ObjectRemovedEvent(selectedProject)); - refreshProjectList(actionEvent); - } - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Checks if user can manage projects. - * - * @return <code>true</code> if user can amange projects, <code>false</code> - * otherwise - */ - public boolean getUserHasManagePrivileges() { - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.PROJECT_MANAGEMENT); - return result; - } - - /** - * Checks if user can add project. - * - * @return <code>true</code> if user can add projects, <code>false</code> - * otherwise - */ - public boolean getUserHasAddMapPrivileges() { - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.ADD_MAP); - return result; - } - - /** - * Gets project identifier for newly created project. - * - * @return name of the new project - */ - public String getNewProjectId() { - return newProjectId; - } - - /** - * Sets project identifier for the newly created project. - * - * @param newProjectId - * new name for the new project - */ - public void setNewProjectId(final String newProjectId) { - String oldValue = this.newProjectId; - this.newProjectId = newProjectId; - firePropertyChange(PROJECT_ID_PROPERTY, oldValue, newProjectId); - } - - /** - * @return {@link #newMapVersion} - */ - public String getNewMapVersion() { - return newMapVersion; - } - - /** - * Sets new value for {@link #newMapVersion}. Property change listeners will - * be thrown for "newMapVersion" property. - * - * @param newMapVersion - * {@link #newMapVersion} - */ - public void setNewMapVersion(final String newMapVersion) { - String oldValue = this.newMapVersion; - this.newMapVersion = newMapVersion; - firePropertyChange(MAP_VERSION_PROPERTY, oldValue, newMapVersion); - } - - /** - * - * @return {@link #mapFile} - */ - public File getMapFile() { - return mapFile; - } - - /** - * Sets new value for {@link #mapFile}. Property change listeners will be - * thrown for "mapFile" property. - * - * @param mapFile - * {@link #mapFile} - */ - public void setMapFile(final File mapFile) { - File oldValue = this.mapFile; - this.mapFile = mapFile; - firePropertyChange(MAP_FILE_PROPERTY, oldValue, mapFile); - } - - /** - * Method that creates a project. - */ - public void createProject() { - try { - if (getMapFile() == null) { - sendError("File cannot be null"); - } else { - generateProject(getMapFile()); - } - } catch (Exception e) { - sendError("Internal server error.", e); - } - } - - /** - * - * @return {@link #newMapAutoResize} - */ - public String getNewMapAutoResize() { - return newMapAutoResize; - } - - /** - * Sets new value for {@link #newMapAutoResize}. Property change listeners - * will be thrown for "newMapAutoResize" property. - * - * @param newMapAutoResize - * {@link #newMapAutoResize} - */ - public void setNewMapAutoResize(final String newMapAutoResize) { - String oldValue = this.newMapAutoResize; - this.newMapAutoResize = newMapAutoResize; - firePropertyChange(AUTO_RESIZE_MAP_PROPERTY, oldValue, newMapAutoResize); - } - - @Override - public void clear() { - throw new NotImplementedException(); - } - - /** - * @return the projectService - * @see #projectService - */ - public IProjectService getProjectService() { - return projectService; - } - - /** - * @param projectService - * the projectService to set - * @see #projectService - */ - public void setProjectService(IProjectService projectService) { - this.projectService = projectService; - } - - /** - * @return the projects - * @see #projects - */ - public List<ProjectView> getProjects() { - if (projects == null) { - projects = new ArrayList<>(); - refreshProjectList(null); - } - return projects; - } - - /** - * @param projects - * the projects to set - * @see #projects - */ - public void setProjects(List<ProjectView> projects) { - this.projects = projects; - } - - /** - * @return the userBean - * @see #userBean - */ - public UserBean getUserBean() { - return userBean; - } - - /** - * @param userBean - * the userBean to set - * @see #userBean - */ - public void setUserBean(UserBean userBean) { - this.userBean = userBean; - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - /** - * @return the modelService - * @see #modelService - */ - public IModelService getModelService() { - return modelService; - } - - /** - * @param modelService - * the modelService to set - * @see #modelService - */ - public void setModelService(IModelService modelService) { - this.modelService = modelService; - } - - /** - * @return the configurationService - * @see #configurationService - */ - public IConfigurationService getConfigurationService() { - return configurationService; - } - - /** - * @param configurationService - * the configurationService to set - * @see #configurationService - */ - public void setConfigurationService(IConfigurationService configurationService) { - this.configurationService = configurationService; - } - - /** - * @return the annotateModel - * @see #annotateModel - */ - public String getAnnotateModel() { - return annotateModel; - } - - /** - * @param annotateModel - * the annotateModel to set - * @see #annotateModel - */ - public void setAnnotateModel(String annotateModel) { - this.annotateModel = annotateModel; - } - - /** - * @return the cacheModel - * @see #cacheModel - */ - public String getCacheModel() { - return cacheModel; - } - - /** - * @param cacheModel - * the cacheModel to set - * @see #cacheModel - */ - public void setCacheModel(String cacheModel) { - this.cacheModel = cacheModel; - } - - /** - * @return the verifyAnnotationsModel - * @see #verifyAnnotationsModel - */ - public String getVerifyAnnotationsModel() { - return verifyAnnotationsModel; - } - - /** - * @param verifyAnnotationsModel - * the verifyAnnotationsModel to set - * @see #verifyAnnotationsModel - */ - public void setVerifyAnnotationsModel(String verifyAnnotationsModel) { - this.verifyAnnotationsModel = verifyAnnotationsModel; - } - - /** - * Method that exports selected project warnings. - * - * @throws IOException - * thrown when there are some problems with sending file - */ - public void downloadWarnings() throws IOException { - // and send it as response - sendFileAsResponse(StringUtils.join(selectedProject.getWarnings(), "\n"), "warnings.txt", MimeType.TEXT); - } - - /** - * @return the complexModel - * @see #complexModel - */ - public String getComplexModel() { - return complexModel; - } - - /** - * @param complexModel - * the complexModel to set - * @see #complexModel - */ - public void setComplexModel(String complexModel) { - this.complexModel = complexModel; - } - - /** - * Returns list of all available submodel types. - * - * @return list of all available submodel types - */ - public SubmodelType[] getSubmodelTypes() { - return SubmodelType.values(); - } - - /** - * Returns list of all possible {@link InputFileType}. - * - * @return array with all possible values of {@link InputFileType} enum - */ - public InputFileType[] getFileTypes() { - return InputFileType.values(); - } - - /** - * @return the annotatorsTree - * @see #annotatorsTree - */ - public TreeNode getAnnotatorsTree() { - return annotatorsTree; - } - - /** - * @param annotatorsTree - * the annotatorsTree to set - * @see #annotatorsTree - */ - public void setAnnotatorsTree(TreeNode annotatorsTree) { - this.annotatorsTree = annotatorsTree; - } - - /** - * @return the annotators - * @see #annotators - */ - public DualListModel<String> getAnnotators() { - return annotators; - } - - /** - * @param annotators - * the annotators to set - * @see #annotators - */ - public void setAnnotators(DualListModel<String> annotators) { - this.annotators = annotators; - } - - /** - * @return the selectedAnnotatorTreeNodeData - * @see #selectedAnnotatorTreeNodeData - */ - public AnnotatedObjectTreeRow getSelectedAnnotatorTreeNodeData() { - return selectedAnnotatorTreeNodeData; - } - - /** - * @param selectedAnnotatorTreeNodeData - * the selectedAnnotatorTreeNodeData to set - * @see #selectedAnnotatorTreeNodeData - */ - public void setSelectedAnnotatorTreeNodeData(AnnotatedObjectTreeRow selectedAnnotatorTreeNodeData) { - AnnotatedObjectTreeRow oldValue = this.selectedAnnotatorTreeNodeData; - this.selectedAnnotatorTreeNodeData = selectedAnnotatorTreeNodeData; - - firePropertyChange(SELECTED_ANNOTATOR_TREE_NODE_DATA_PROPERTY, oldValue, selectedAnnotatorTreeNodeData); - } - - /** - * Method called when list of annotators in {@link #annotators} changed. - * - * @param event - * primefaces event - */ - public void onTransfer(TransferEvent event) { - updateAnnotatorTreeNodeData(); - } - - /** - * This method updates data in {@link #selectedAnnotatorTreeNodeData}. - */ - private void updateAnnotatorTreeNodeData() { - this.selectedAnnotatorTreeNodeData.setValidAnnotators(annotators.getSource()); - this.selectedAnnotatorTreeNodeData.setUsedAnnotators(annotators.getTarget()); - this.selectedAnnotatorTreeNodeData.setMissingValidAnnotations(validMiriam.getSource()); - this.selectedAnnotatorTreeNodeData.setValidAnnotations(validMiriam.getTarget()); - this.selectedAnnotatorTreeNodeData.setMissingRequiredAnnotations(requiredMiriam.getSource()); - this.selectedAnnotatorTreeNodeData.setRequiredAnnotations(requiredMiriam.getTarget()); - } - - /** - * Method called when list of annotators in {@link #annotators} changed order. - */ - public void onReorder() { - updateAnnotatorTreeNodeData(); - } - - /** - * @return the validMiriam - * @see #validMiriam - */ - public DualListModel<MiriamType> getValidMiriam() { - return validMiriam; - } - - /** - * @param validMiriam - * the validMiriam to set - * @see #validMiriam - */ - public void setValidMiriam(DualListModel<MiriamType> validMiriam) { - this.validMiriam = validMiriam; - } - - /** - * @return the requiredMiriam - * @see #requiredMiriam - */ - public DualListModel<MiriamType> getRequiredMiriam() { - return requiredMiriam; - } - - /** - * @param requiredMiriam - * the requiredMiriam to set - * @see #requiredMiriam - */ - public void setRequiredMiriam(DualListModel<MiriamType> requiredMiriam) { - this.requiredMiriam = requiredMiriam; - } - - /** - * @return the dataMiningTypes - * @see #dataMiningTypes - */ - public List<DataMiningType> getDataMiningTypes() { - return dataMiningTypes; - } - - /** - * @param dataMiningTypes - * the dataMiningTypes to set - * @see #dataMiningTypes - */ - public void setDataMiningTypes(List<DataMiningType> dataMiningTypes) { - this.dataMiningTypes = dataMiningTypes; - } - - /** - * @return the layoutBean - * @see #layoutBean - */ - public LayoutBean getLayoutBean() { - return layoutBean; - } - - /** - * @param layoutBean - * the layoutBean to set - * @see #layoutBean - */ - public void setLayoutBean(LayoutBean layoutBean) { - this.layoutBean = layoutBean; - } - - /** - * Clears list with information about zip entries in currently processed zip - * file. - */ - private void clearZipEntriesData() { - dataMiningZipEntries.clear(); - imageZipEntries.clear(); - layoutZipEntries.clear(); - modelZipEntries.clear(); - - } - - /** - * @return the dataMiningZipEntries - * @see #dataMiningZipEntries - */ - public List<DataMiningZipEntryFile> getDataMiningZipEntries() { - return dataMiningZipEntries; - } - - /** - * @param dataMiningZipEntries - * the dataMiningZipEntries to set - * @see #dataMiningZipEntries - */ - public void setDataMiningZipEntries(List<DataMiningZipEntryFile> dataMiningZipEntries) { - this.dataMiningZipEntries = dataMiningZipEntries; - } - - /** - * @return the modelZipEntries - * @see #modelZipEntries - */ - public List<ModelZipEntryFile> getModelZipEntries() { - return modelZipEntries; - } - - /** - * @param modelZipEntries - * the modelZipEntries to set - * @see #modelZipEntries - */ - public void setModelZipEntries(List<ModelZipEntryFile> modelZipEntries) { - this.modelZipEntries = modelZipEntries; - } - - /** - * @return the layoutZipEntries - * @see #layoutZipEntries - */ - public List<LayoutZipEntryFile> getLayoutZipEntries() { - return layoutZipEntries; - } - - /** - * @param layoutZipEntries - * the layoutZipEntries to set - * @see #layoutZipEntries - */ - public void setLayoutZipEntries(List<LayoutZipEntryFile> layoutZipEntries) { - this.layoutZipEntries = layoutZipEntries; - } - - /** - * @return the imageZipEntries - * @see #imageZipEntries - */ - public List<ImageZipEntryFile> getImageZipEntries() { - return imageZipEntries; - } - - /** - * @param imageZipEntries - * the imageZipEntries to set - * @see #imageZipEntries - */ - public void setImageZipEntries(List<ImageZipEntryFile> imageZipEntries) { - this.imageZipEntries = imageZipEntries; - } - - /** - * @return the newProjectName - * @see #newProjectName - */ - public String getNewProjectName() { - return newProjectName; - } - - /** - * @param newProjectName - * the newProjectName to set - * @see #newProjectName - */ - public void setNewProjectName(String newProjectName) { - this.newProjectName = newProjectName; - } - - /** - * @return the sbgnFormat - * @see #sbgnFormat - */ - public String getSbgnFormat() { - return sbgnFormat; - } - - /** - * @param sbgnFormat - * the sbgnFormat to set - * @see #sbgnFormat - */ - public void setSbgnFormat(String sbgnFormat) { - this.sbgnFormat = sbgnFormat; - } - - /** - * @return the networkLayoutAsDefault - * @see #networkLayoutAsDefault - */ - public String getNetworkLayoutAsDefault() { - return networkLayoutAsDefault; - } - - /** - * @param networkLayoutAsDefault - * the networkLayoutAsDefault to set - * @see #networkLayoutAsDefault - */ - public void setNetworkLayoutAsDefault(String networkLayoutAsDefault) { - this.networkLayoutAsDefault = networkLayoutAsDefault; - } - - /** - * @return new project disease. - */ - public String getNewProjectDisease() { - return newProjectDisease; - } - - /** - * @param newProjectDisease - * sets the disease - */ - public void setNewProjectDisease(String newProjectDisease) { - this.newProjectDisease = newProjectDisease; - } - - /** - * Method that trigger download of a file in jsf. The file is the source file - * used to create project given in the parameter. - * - * @param projectView - * view of the {@link Project} for which we are looking for an - * original source file - * @throws IOException - * thrown when there is a problem with sending file - * @throws UserAccessException - */ - public void downloadInputData(ProjectView projectView) throws IOException, UserAccessException { - // get input data from database - byte[] data = projectService.getInputDataForProject(projectView); - Project project = projectService.getProjectByProjectId(projectView.getProjectId(), userBean.getAuthenticationToken()); - String string = new String(data, StandardCharsets.UTF_8); - - String fileName = project.getInputData().getOriginalFileName(); - MimeType respMimeType = null; - if (fileName.endsWith("xml")) { - respMimeType = MimeType.XML; - } else if (fileName.endsWith("zip")) { - respMimeType = MimeType.ZIP; - } else if (fileName.endsWith("sbgn")) { - respMimeType = MimeType.XML; - } else { - logger.warn("Cannot determine mime type of file: " + fileName); - respMimeType = MimeType.TEXT; - } - sendFileAsResponse(string, fileName, respMimeType); - } - - /** - * @return the newProjectOrganism - * @see #newProjectOrganism - */ - public String getNewProjectOrganism() { - return newProjectOrganism; - } - - /** - * @param newProjectOrganism - * the newProjectOrganism to set - * @see #newProjectOrganism - */ - public void setNewProjectOrganism(String newProjectOrganism) { - this.newProjectOrganism = newProjectOrganism; - } - - /** - * @return the semanticOverlay - * @see #semanticOverlay - */ - public String getSemanticOverlay() { - return semanticOverlay; - } - - /** - * @param semanticOverlay - * the semanticOverlay to set - * @see #semanticOverlay - */ - public void setSemanticOverlay(String semanticOverlay) { - this.semanticOverlay = semanticOverlay; - } + /** + * String representing {@link #selectedProject} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String SELECTED_PROJECT_PROPERTY = "SELECTED_PROJECT"; + + /** + * String representing {@link #mapFile} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String MAP_FILE_PROPERTY = "MAP_FILE"; + + /** + * String representing {@link #newMapAutoResize} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String AUTO_RESIZE_MAP_PROPERTY = "AUTO_RESIZE_MAP"; + + /** + * String representing {@link #newProjectId} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String PROJECT_ID_PROPERTY = "PROJECT_ID"; + + /** + * String representing {@link #newMapVersion} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String MAP_VERSION_PROPERTY = "MAP_VERSION"; + + /** + * String representing {@link #selectedAnnotatorTreeNodeData} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String SELECTED_ANNOTATOR_TREE_NODE_DATA_PROPERTY = "SELECTED_ANNOTATOR_TREE_NODE_DATA"; + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(ProjectBean.class); + + /** + * List of projects visible on client side. It's lazy loaded. + */ + private List<ProjectView> projects = null; + + /** + * Project selected for editing (or new project to create). + */ + private ProjectView selectedProject; + + /** + * Identifier of the project. + */ + private String newProjectId = "auto_name"; + + /** + * Name of the project. + */ + private String newProjectName = "UNKNOWN DISEASE MAP"; + + /** + * Disease of the project. + */ + private String newProjectDisease; + + /** + * Organism of the project. + */ + private String newProjectOrganism; + + /** + * Version of the project. + */ + private String newMapVersion = "0"; + + /** + * Should we annotate model automatically. + */ + private String annotateModel = "false"; + + /** + * Should we cache data from external resources connected to this map. + */ + private String cacheModel = "false"; + + /** + * Should the maunal annotations of the model be verified. + */ + private String verifyAnnotationsModel = "false"; + + /** + * Should we resize the model (to normalize margins). + */ + private String newMapAutoResize = "true"; + + /** + * Is the uploaded model a complex multi-files project or not. + */ + private String complexModel = "false"; + + /** + * Is the {@link lcsb.mapviewer.services.utils.data.BuildInLayout#NORMAL} + * default layout when generating new project. + */ + private String networkLayoutAsDefault = "false"; + + /** + * List of zip entries corresponding to model (and submodels) in the complex + * project thas is to be uploaded. + */ + private List<ModelZipEntryFile> modelZipEntries = new ArrayList<ModelZipEntryFile>(); + + /** + * List of zip entries corresponding to data mining files in the complex + * project. + */ + private List<DataMiningZipEntryFile> dataMiningZipEntries = new ArrayList<DataMiningZipEntryFile>(); + + /** + * List of zip entries corresponding to layout files in the complex project. + */ + private List<LayoutZipEntryFile> layoutZipEntries = new ArrayList<LayoutZipEntryFile>(); + + /** + * Should the map be displayed in SBGN format. + */ + private String sbgnFormat = "false"; + + private String semanticOverlay = "false"; + + /** + * List of zip entries corresponding to + * {@link lcsb.mapviewer.model.map.OverviewImage OverviewImage} files in the + * complex project. + */ + private List<ImageZipEntryFile> imageZipEntries = new ArrayList<ImageZipEntryFile>(); + + /** + * Uploaded file with the data in CellDesigner format. + */ + private File mapFile = null; + + /** + * Service used to access information about projects. + * + * @see IProjectService + */ + @ManagedProperty(value = "#{ProjectService}") + private transient IProjectService projectService; + + /** + * Bean used for communication with the client side about the data related to + * users (including information about currently logged user). + * + * @see UserBean + */ + @ManagedProperty(value = "#{userMB}") + private transient UserBean userBean; + + /** + * Bean used for communication with the client side about the data related to + * layouts. + * + * @see UserBean + */ + @ManagedProperty(value = "#{layoutMB}") + private transient LayoutBean layoutBean; + + /** + * Service used to access configuration parameters. + * + * @see IConfigurationService + */ + @ManagedProperty(value = "#{ConfigurationService}") + private transient IConfigurationService configurationService; + + /** + * Service used to access information about users. + * + * @see IUserService + */ + @ManagedProperty(value = "#{UserService}") + private transient IUserService userService; + + /** + * Service that allows to access and manage models. + */ + @ManagedProperty(value = "#{ModelService}") + private transient IModelService modelService; + + /** + * Tree with information about classes that can be annotated and which + * annotators should be used for these classes. + */ + private TreeNode annotatorsTree; + + /** + * Element of {@link #annotatorsTree} that is currently edited. + */ + private AnnotatedObjectTreeRow selectedAnnotatorTreeNodeData; + + /** + * List of annotators for {@link #selectedAnnotatorTreeNodeData} that is + * currently edited. + */ + private DualListModel<String> annotators = new DualListModel<String>(); + + /** + * List of valid {@link MiriamType} for {@link #selectedAnnotatorTreeNodeData} + * that is currently edited. + */ + private DualListModel<MiriamType> validMiriam = new DualListModel<MiriamType>(); + + /** + * List of required {@link MiriamType} for + * {@link #selectedAnnotatorTreeNodeData} that is currently edited. + */ + private DualListModel<MiriamType> requiredMiriam = new DualListModel<MiriamType>(); + + /** + * List of all {@link DataMiningType}. + */ + private List<DataMiningType> dataMiningTypes = new ArrayList<DataMiningType>(); + + /** + * Listener used to verify the modification of the project. + */ + private transient VetoableChangeListener selectedProjectVetoChanged; + + { + selectedProjectVetoChanged = new VetoableChangeListener() { + @Override + public void vetoableChange(final PropertyChangeEvent arg0) throws PropertyVetoException { + try { + if (SELECTED_PROJECT_PROPERTY.equals(arg0.getPropertyName())) { + + ProjectView oldVal = (ProjectView) arg0.getOldValue(); + ProjectView newVal = (ProjectView) arg0.getNewValue(); + + // if we change to null then it's ok + if (newVal == null) { + return; + } + + ProjectView fromDb = projectService.getProjectViewByProjectId(newVal.getProjectId(), + userBean.getAuthenticationToken()); + String defaultMap = configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); + + // check if we change the name properly + if (oldVal != null && oldVal.getIdObject() != null && oldVal.getIdObject().equals(newVal.getIdObject())) { + if (oldVal.getProjectId().equals(newVal.getProjectId())) { + // name hasn't changed + return; + } else if (oldVal.getProjectId().equals(defaultMap)) { + // we try to change the name of default map + throw new PropertyVetoException("Cannot change the name of default project.", arg0); + } else if (fromDb == null || fromDb.getIdObject() == null) { + // there is no project with the new name + return; + } else if (fromDb.getIdObject().equals(newVal.getIdObject())) { + // project with the same id is the same project + return; + } else { + throw new PropertyVetoException( + "Cannot change the name of project. Project with this name already exists.", arg0); + } + + } + + if (fromDb != null && fromDb.getIdObject() != null) { + if (fromDb.getIdObject().equals(newVal.getIdObject())) { + return; + } else { + throw new PropertyVetoException("Project with this name already exists.", arg0); + } + } + + } + } catch (Exception e) { + throw new PropertyVetoException("Unexpected problem: " + e.getMessage(), arg0); + } + } + }; + } + + @Override + public void init() { + + addVetoablePropertyChangeListener(selectedProjectVetoChanged); + + // uploaded file chagnge listener + PropertyChangeListener mapFileChangeListener = new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent arg0) { + if (MAP_FILE_PROPERTY.equals(arg0.getPropertyName())) { + File file = (File) arg0.getNewValue(); + clearZipEntriesData(); + complexModel = "false"; + if (file != null) { + if (file.getName().toLowerCase().endsWith("zip")) { + // when zip file is uploaded preprocess it to retrieve entries in + // zip file + ZipEntryFileFactory zefFactory = new ZipEntryFileFactory(); + complexModel = "true"; + try { + ZipFile zipFile = new ZipFile(file); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + ZipEntryFile zef = zefFactory.createZipEntryFile(entry, zipFile); + if (zef != null) { + // assign zip entries to proper lists + if (zef instanceof ModelZipEntryFile) { + modelZipEntries.add((ModelZipEntryFile) zef); + } else if (zef instanceof ImageZipEntryFile) { + imageZipEntries.add((ImageZipEntryFile) zef); + } else if (zef instanceof LayoutZipEntryFile) { + layoutZipEntries.add((LayoutZipEntryFile) zef); + } else if (zef instanceof DataMiningZipEntryFile) { + dataMiningZipEntries.add((DataMiningZipEntryFile) zef); + } else { + logger.warn("Unknown class type: " + zef.getClass()); + sendError("Internal server error"); + } + } + } + zipFile.close(); + } catch (IOException e) { + logger.error(e, e); + } + } + } + String name = FilenameUtils.getName(file.getName()).replaceAll(" ", "_"); + if (name.indexOf("-cd-") > 0) { + name = name.substring(0, name.indexOf("-cd-")); + } + setNewProjectId(name); + } + } + + }; + addPropertyChangeListener(mapFileChangeListener); + + annotatorsTree = projectService.createClassAnnotatorTree(userBean.getLoggedUser()); + + // this listener will be called when user start to edit list of + // ElementAnnotator for a given class type + PropertyChangeListener selectedAnnotatorTreeNodeChangeListener = new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent arg0) { + if (SELECTED_ANNOTATOR_TREE_NODE_DATA_PROPERTY.equals(arg0.getPropertyName())) { + AnnotatedObjectTreeRow data = (AnnotatedObjectTreeRow) arg0.getNewValue(); + annotators = new DualListModel<String>(data.getValidAnnotators(), data.getUsedAnnotators()); + validMiriam = new DualListModel<MiriamType>(data.getMissingValidAnnotations(), data.getValidAnnotations()); + requiredMiriam = new DualListModel<MiriamType>(data.getMissingRequiredAnnotations(), + data.getRequiredAnnotations()); + } + } + + }; + + addPropertyChangeListener(selectedAnnotatorTreeNodeChangeListener); + + Listener<ObjectAddedEvent> layoutAddedListener = new Listener<ObjectAddedEvent>(ObjectAddedEvent.class) { + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + protected void handle(ObjectAddedEvent event) { + boolean projectFound = false; + LayoutView layout = (LayoutView) event.getObject(); + + for (ProjectView project : getProjects()) { + if (project.getModelId() != null && project.getModelId().equals(layout.getModelId())) { + projectFound = true; + project.addLayout(layout); + } + } + + if (!projectFound) { + logger.warn("After adding layout cannot find project for the layout. LayoutId: " + layout.getIdObject() + + "; ModelId: " + layout.getModelId()); + } + } + }; + layoutBean.registerListener(layoutAddedListener); + + layoutBean.registerListener(createLayoutRemovedListener()); + + setSelectedAnnotatorTreeNodeData((AnnotatedObjectTreeRow) annotatorsTree.getData()); + + for (DataMiningType dm : DataMiningType.values()) { + dataMiningTypes.add(dm); + } + + // when new project is added refresh list of projects + registerListener(new Listener<ObjectAddedEvent>(ObjectAddedEvent.class) { + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + protected void handle(ObjectAddedEvent event) { + refreshProjectList(null); + } + }); + + customizeUserParameters(); + + } + + /** + * Sets default values for some checkboxes specific for a user. (The values are + * stored in databsae) + */ + public void customizeUserParameters() { + if (userBean.getLoggedUser() != null) { + User user = userBean.getLoggedUser(); + if (user.getAnnotationSchema() != null) { + setSbgnFormat(user.getAnnotationSchema().getSbgnFormat()); + setNetworkLayoutAsDefault(user.getAnnotationSchema().getNetworkLayoutAsDefault()); + } + } + } + + /** + * Sets {@link #networkLayoutAsDefault}. + * + * @param value + * new value + */ + private void setNetworkLayoutAsDefault(Boolean value) { + if (value) { + setNetworkLayoutAsDefault("true"); + } else { + setNetworkLayoutAsDefault("false"); + } + } + + /** + * Sets {@link #sbgnFormat}. + * + * @param value + * new value + */ + private void setSbgnFormat(boolean value) { + if (value) { + setSbgnFormat("true"); + } else { + setSbgnFormat("false"); + } + } + + /** + * Creates listener that should be called when layout is removed. + * + * @return listener that should be called when layout is removed + */ + public Listener<ObjectRemovedEvent> createLayoutRemovedListener() { + return new Listener<ObjectRemovedEvent>(ObjectRemovedEvent.class) { + /** + * + */ + private static final long serialVersionUID = 1L; + + @Override + protected void handle(ObjectRemovedEvent event) { + boolean projectFound = false; + LayoutView layout = (LayoutView) event.getObject(); + for (ProjectView project : getProjects()) { + if (project.getModelId().equals(layout.getModelId())) { + projectFound = true; + LayoutView layoutToRemove = null; + for (LayoutView oldLayout : project.getLayouts()) { + if (oldLayout.getIdObject().equals(layout.getIdObject())) { + layoutToRemove = oldLayout; + } + } + if (layoutToRemove == null) { + logger.warn("After removing layout from db cannot find layout in the project to remove. LayoutId: " + + layout.getIdObject() + "; ModelId: " + layout.getModelId()); + } else { + project.getLayouts().remove(layoutToRemove); + } + } + } + + if (!projectFound) { + logger.warn("After removing layout cannot find project for the layout. LayoutId: " + layout.getIdObject() + + "; ModelId: " + layout.getModelId()); + } + } + }; + } + + /** + * Refresh list of projects. + * + * @param actionEvent + * event from thefrom the client + */ + public void refreshProjectList(final ActionEvent actionEvent) { + if (projects == null) { + logger.warn("Strange behaviour: refreshing project list withouth accessing..."); + projects = new ArrayList<>(); + } + projects.clear(); + List<ProjectView> localProjectList; + try { + localProjectList = projectService.getAllProjectViews(userBean.getAuthenticationToken()); + for (ProjectView projectRow : localProjectList) { + projects.add(projectRow); + } + Collections.sort(projects); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * This method handle upload of a file. + * + * @param event + * event send by the client with a file reference + */ + public void handleFileUpload(final FileUploadEvent event) { + try { + logger.debug(event.getFile().getFileName() + " is uploaded."); + UploadedFile uploadedFile = event.getFile(); + String filename = FilenameUtils.getBaseName(uploadedFile.getFileName()); + String extension = FilenameUtils.getExtension(uploadedFile.getFileName()); + File file = File.createTempFile(filename + "-cd-", "." + extension); + file.delete(); + InputStream input = uploadedFile.getInputstream(); + Files.copy(input, file.toPath()); + input.close(); + + this.setMapFile(file); + } catch (Exception e) { + sendError("Problem with uploading...", e); + } + } + + /** + * Generates project based on the information provided by the client. + * + * @param file + * file with the model in CellDesigner format + * @throws SecurityException + */ + protected void generateProject(final File file) throws SecurityException { + // if project with this name already exists then add random suffix + String projectId = getNewProjectId(); + if (projectService.projectExists(getNewProjectId())) { + sendError("Project with identifier: \"" + getNewProjectId() + "\" already exists."); + return; + } + + // get proper paths: + // to directory with images + String imagePath = getProjectDeployPath() + "/../map_images/" + md5(projectId) + "/"; + String version = getNewMapVersion(); + + boolean autoResize = newMapAutoResize.equalsIgnoreCase("true"); + + CreateProjectParams params = new CreateProjectParams(); + + params.complex("true".equalsIgnoreCase(complexModel)); + params.projectId(projectId); + params.projectName(newProjectName); + params.projectDisease(newProjectDisease); + params.projectOrganism(newProjectOrganism); + params.version(version); + params.projectFile(file); + params.autoResize(autoResize); + params.images(true); + params.async(true); + params.notifyEmail(userBean.getLoggedUser().getEmail()); + params.projectDir(imagePath); + params.annotatorsMap(annotatorsTree); + params.addUser(userBean.getLogin(), null); + params.annotations("true".equalsIgnoreCase(annotateModel)); + params.analyzeAnnotations("true".equalsIgnoreCase(verifyAnnotationsModel)); + params.cacheModel("true".equalsIgnoreCase(cacheModel)); + params.validAnnotations(annotatorsTree); + params.requiredAnnotations(annotatorsTree); + params.authenticationToken(userBean.getAuthenticationToken()); + for (ZipEntryFile submodel : getZipEntries()) { + params.addZipEntry(submodel); + } + params.sbgnFormat("true".equalsIgnoreCase(sbgnFormat)); + params.semanticZoom("true".equalsIgnoreCase(semanticOverlay)); + params.networkLayoutAsDefault("true".equalsIgnoreCase(networkLayoutAsDefault)); + projectService.createProject(params); + projectService.updateClassAnnotatorTreeForUser(userBean.getLoggedUser(), annotatorsTree, + sbgnFormat.equalsIgnoreCase("true"), networkLayoutAsDefault.equalsIgnoreCase("true")); + + ObjectAddedEvent event = new ObjectAddedEvent( + projectService.getProjectByProjectId(projectId, userBean.getAuthenticationToken())); + callListeners(event); + } + + /** + * Returns list of all zip entries in the currently processed file. + * + * @return list of all zip entries in the currently processed file + */ + private Collection<ZipEntryFile> getZipEntries() { + List<ZipEntryFile> result = new ArrayList<ZipEntryFile>(); + result.addAll(modelZipEntries); + result.addAll(imageZipEntries); + result.addAll(layoutZipEntries); + result.addAll(dataMiningZipEntries); + return result; + } + + /** + * Method that computes md5 hash for a given {@link String}. + * + * @param data + * input string + * @return md5 hash for input string + */ + private String md5(String data) { + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + byte[] mdbytes = md.digest(data.getBytes()); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < mdbytes.length; i++) { + // CHECKSTYLE:OFF + // this magic formula transforms int into hex value + sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); + // CHECKSTYLE:ON + } + return sb.toString(); + } catch (NoSuchAlgorithmException e) { + logger.fatal("Problem with instance of MD5 encoder", e); + } + + return null; + } + + /** + * Returns project currently selected and edited by the client side. + * + * @return project view currently selected and edited by the client side + */ + public ProjectView getSelectedProject() { + if (selectedProject == null) { + selectedProject = projectService.createEmpty(); + } + return selectedProject; + } + + /** + * Set new currently selected and edited project. + * + * @param selectedProject + * view of the new currently selected and edited project + */ + public void setSelectedProject(final ProjectView selectedProject) { + ProjectView oldValue = this.selectedProject; + this.selectedProject = selectedProject; + try { + fireVetoableChange(SELECTED_PROJECT_PROPERTY, oldValue, selectedProject); + firePropertyChange(SELECTED_PROJECT_PROPERTY, oldValue, selectedProject); + logger.debug("Selected project was set to: " + this.selectedProject.getProjectId()); + } catch (PropertyVetoException e) { + this.selectedProject = oldValue; + sendError(e.getMessage(), e); + } + } + + /** + * Method which update a project. + * + * @param actionEvent + * event from thefrom the client + * @throws SecurityException + */ + public void updateSelectedProject(final ActionEvent actionEvent) throws SecurityException { + + // first we need small trick (maybe this should be improved) + + ProjectView newProject = selectedProject; + // get old version of the project from db + ProjectView oldProject = projectService.getProjectViewById(newProject.getIdObject(), + userBean.getAuthenticationToken()); + + // set old version + setSelectedProject(oldProject); + // now, change to the new one (property change listener will ensure that + // everything is fine) + setSelectedProject(newProject); + + // if everything is ok then update in db + if (selectedProject != null) { + projectService.updateProject(selectedProject); + } else { + logger.warn("Problem during updating project..."); + } + refreshProjectList(actionEvent); + + callListeners(new ObjectModifiedEvent(newProject)); + } + + /** + * Removes project selected by client. + * + * @param actionEvent + * client side action + */ + public void removeSelectedProject(final ActionEvent actionEvent) { + try { + logger.debug("Removing project: " + selectedProject); + String defaultMap = configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); + String projectId = selectedProject.getProjectId(); + + // find out what is the name of the project in db + ProjectView project = projectService.getProjectViewById(selectedProject.getIdObject(), + userBean.getAuthenticationToken()); + if (project != null) { + projectId = project.getProjectId(); + } + + logger.debug("Removing project: " + projectId); + + // if the project name is a default one then don't remove it + if (defaultMap.equals(projectId)) { + sendError("Cannot remove default map. To remove this map change the default map in configuration tab first."); + } else { + projectService.removeProject(selectedProject, getProjectDeployPath(), true, userBean.getAuthenticationToken()); + callListeners(new ObjectRemovedEvent(selectedProject)); + refreshProjectList(actionEvent); + } + } catch (Exception e) { + sendError("Internal server error", e); + } + } + + /** + * Checks if user can manage projects. + * + * @return <code>true</code> if user can amange projects, <code>false</code> + * otherwise + */ + public boolean getUserHasManagePrivileges() { + User user = userBean.getLoggedUser(); + boolean result = userService.userHasPrivilege(user, PrivilegeType.PROJECT_MANAGEMENT); + return result; + } + + /** + * Checks if user can add project. + * + * @return <code>true</code> if user can add projects, <code>false</code> + * otherwise + */ + public boolean getUserHasAddMapPrivileges() { + User user = userBean.getLoggedUser(); + boolean result = userService.userHasPrivilege(user, PrivilegeType.ADD_MAP); + return result; + } + + /** + * Gets project identifier for newly created project. + * + * @return name of the new project + */ + public String getNewProjectId() { + return newProjectId; + } + + /** + * Sets project identifier for the newly created project. + * + * @param newProjectId + * new name for the new project + */ + public void setNewProjectId(final String newProjectId) { + String oldValue = this.newProjectId; + this.newProjectId = newProjectId; + firePropertyChange(PROJECT_ID_PROPERTY, oldValue, newProjectId); + } + + /** + * @return {@link #newMapVersion} + */ + public String getNewMapVersion() { + return newMapVersion; + } + + /** + * Sets new value for {@link #newMapVersion}. Property change listeners will be + * thrown for "newMapVersion" property. + * + * @param newMapVersion + * {@link #newMapVersion} + */ + public void setNewMapVersion(final String newMapVersion) { + String oldValue = this.newMapVersion; + this.newMapVersion = newMapVersion; + firePropertyChange(MAP_VERSION_PROPERTY, oldValue, newMapVersion); + } + + /** + * + * @return {@link #mapFile} + */ + public File getMapFile() { + return mapFile; + } + + /** + * Sets new value for {@link #mapFile}. Property change listeners will be thrown + * for "mapFile" property. + * + * @param mapFile + * {@link #mapFile} + */ + public void setMapFile(final File mapFile) { + File oldValue = this.mapFile; + this.mapFile = mapFile; + firePropertyChange(MAP_FILE_PROPERTY, oldValue, mapFile); + } + + /** + * Method that creates a project. + */ + public void createProject() { + try { + if (getMapFile() == null) { + sendError("File cannot be null"); + } else { + generateProject(getMapFile()); + } + } catch (Exception e) { + sendError("Internal server error.", e); + } + } + + /** + * + * @return {@link #newMapAutoResize} + */ + public String getNewMapAutoResize() { + return newMapAutoResize; + } + + /** + * Sets new value for {@link #newMapAutoResize}. Property change listeners will + * be thrown for "newMapAutoResize" property. + * + * @param newMapAutoResize + * {@link #newMapAutoResize} + */ + public void setNewMapAutoResize(final String newMapAutoResize) { + String oldValue = this.newMapAutoResize; + this.newMapAutoResize = newMapAutoResize; + firePropertyChange(AUTO_RESIZE_MAP_PROPERTY, oldValue, newMapAutoResize); + } + + @Override + public void clear() { + throw new NotImplementedException(); + } + + /** + * @return the projectService + * @see #projectService + */ + public IProjectService getProjectService() { + return projectService; + } + + /** + * @param projectService + * the projectService to set + * @see #projectService + */ + public void setProjectService(IProjectService projectService) { + this.projectService = projectService; + } + + /** + * @return the projects + * @see #projects + */ + public List<ProjectView> getProjects() { + if (projects == null) { + projects = new ArrayList<>(); + refreshProjectList(null); + } + return projects; + } + + /** + * @param projects + * the projects to set + * @see #projects + */ + public void setProjects(List<ProjectView> projects) { + this.projects = projects; + } + + /** + * @return the userBean + * @see #userBean + */ + public UserBean getUserBean() { + return userBean; + } + + /** + * @param userBean + * the userBean to set + * @see #userBean + */ + public void setUserBean(UserBean userBean) { + this.userBean = userBean; + } + + /** + * @return the userService + * @see #userService + */ + public IUserService getUserService() { + return userService; + } + + /** + * @param userService + * the userService to set + * @see #userService + */ + public void setUserService(IUserService userService) { + this.userService = userService; + } + + /** + * @return the modelService + * @see #modelService + */ + public IModelService getModelService() { + return modelService; + } + + /** + * @param modelService + * the modelService to set + * @see #modelService + */ + public void setModelService(IModelService modelService) { + this.modelService = modelService; + } + + /** + * @return the configurationService + * @see #configurationService + */ + public IConfigurationService getConfigurationService() { + return configurationService; + } + + /** + * @param configurationService + * the configurationService to set + * @see #configurationService + */ + public void setConfigurationService(IConfigurationService configurationService) { + this.configurationService = configurationService; + } + + /** + * @return the annotateModel + * @see #annotateModel + */ + public String getAnnotateModel() { + return annotateModel; + } + + /** + * @param annotateModel + * the annotateModel to set + * @see #annotateModel + */ + public void setAnnotateModel(String annotateModel) { + this.annotateModel = annotateModel; + } + + /** + * @return the cacheModel + * @see #cacheModel + */ + public String getCacheModel() { + return cacheModel; + } + + /** + * @param cacheModel + * the cacheModel to set + * @see #cacheModel + */ + public void setCacheModel(String cacheModel) { + this.cacheModel = cacheModel; + } + + /** + * @return the verifyAnnotationsModel + * @see #verifyAnnotationsModel + */ + public String getVerifyAnnotationsModel() { + return verifyAnnotationsModel; + } + + /** + * @param verifyAnnotationsModel + * the verifyAnnotationsModel to set + * @see #verifyAnnotationsModel + */ + public void setVerifyAnnotationsModel(String verifyAnnotationsModel) { + this.verifyAnnotationsModel = verifyAnnotationsModel; + } + + /** + * Method that exports selected project warnings. + * + * @throws IOException + * thrown when there are some problems with sending file + */ + public void downloadWarnings() throws IOException { + // and send it as response + sendFileAsResponse(StringUtils.join(selectedProject.getWarnings(), "\n"), "warnings.txt", MimeType.TEXT); + } + + /** + * @return the complexModel + * @see #complexModel + */ + public String getComplexModel() { + return complexModel; + } + + /** + * @param complexModel + * the complexModel to set + * @see #complexModel + */ + public void setComplexModel(String complexModel) { + this.complexModel = complexModel; + } + + /** + * Returns list of all available submodel types. + * + * @return list of all available submodel types + */ + public SubmodelType[] getSubmodelTypes() { + return SubmodelType.values(); + } + + /** + * Returns list of all possible {@link InputFileType}. + * + * @return array with all possible values of {@link InputFileType} enum + */ + public InputFileType[] getFileTypes() { + return InputFileType.values(); + } + + /** + * @return the annotatorsTree + * @see #annotatorsTree + */ + public TreeNode getAnnotatorsTree() { + return annotatorsTree; + } + + /** + * @param annotatorsTree + * the annotatorsTree to set + * @see #annotatorsTree + */ + public void setAnnotatorsTree(TreeNode annotatorsTree) { + this.annotatorsTree = annotatorsTree; + } + + /** + * @return the annotators + * @see #annotators + */ + public DualListModel<String> getAnnotators() { + return annotators; + } + + /** + * @param annotators + * the annotators to set + * @see #annotators + */ + public void setAnnotators(DualListModel<String> annotators) { + this.annotators = annotators; + } + + /** + * @return the selectedAnnotatorTreeNodeData + * @see #selectedAnnotatorTreeNodeData + */ + public AnnotatedObjectTreeRow getSelectedAnnotatorTreeNodeData() { + return selectedAnnotatorTreeNodeData; + } + + /** + * @param selectedAnnotatorTreeNodeData + * the selectedAnnotatorTreeNodeData to set + * @see #selectedAnnotatorTreeNodeData + */ + public void setSelectedAnnotatorTreeNodeData(AnnotatedObjectTreeRow selectedAnnotatorTreeNodeData) { + AnnotatedObjectTreeRow oldValue = this.selectedAnnotatorTreeNodeData; + this.selectedAnnotatorTreeNodeData = selectedAnnotatorTreeNodeData; + + firePropertyChange(SELECTED_ANNOTATOR_TREE_NODE_DATA_PROPERTY, oldValue, selectedAnnotatorTreeNodeData); + } + + /** + * Method called when list of annotators in {@link #annotators} changed. + * + * @param event + * primefaces event + */ + public void onTransfer(TransferEvent event) { + updateAnnotatorTreeNodeData(); + } + + /** + * This method updates data in {@link #selectedAnnotatorTreeNodeData}. + */ + private void updateAnnotatorTreeNodeData() { + this.selectedAnnotatorTreeNodeData.setValidAnnotators(annotators.getSource()); + this.selectedAnnotatorTreeNodeData.setUsedAnnotators(annotators.getTarget()); + this.selectedAnnotatorTreeNodeData.setMissingValidAnnotations(validMiriam.getSource()); + this.selectedAnnotatorTreeNodeData.setValidAnnotations(validMiriam.getTarget()); + this.selectedAnnotatorTreeNodeData.setMissingRequiredAnnotations(requiredMiriam.getSource()); + this.selectedAnnotatorTreeNodeData.setRequiredAnnotations(requiredMiriam.getTarget()); + } + + /** + * Method called when list of annotators in {@link #annotators} changed order. + */ + public void onReorder() { + updateAnnotatorTreeNodeData(); + } + + /** + * @return the validMiriam + * @see #validMiriam + */ + public DualListModel<MiriamType> getValidMiriam() { + return validMiriam; + } + + /** + * @param validMiriam + * the validMiriam to set + * @see #validMiriam + */ + public void setValidMiriam(DualListModel<MiriamType> validMiriam) { + this.validMiriam = validMiriam; + } + + /** + * @return the requiredMiriam + * @see #requiredMiriam + */ + public DualListModel<MiriamType> getRequiredMiriam() { + return requiredMiriam; + } + + /** + * @param requiredMiriam + * the requiredMiriam to set + * @see #requiredMiriam + */ + public void setRequiredMiriam(DualListModel<MiriamType> requiredMiriam) { + this.requiredMiriam = requiredMiriam; + } + + /** + * @return the dataMiningTypes + * @see #dataMiningTypes + */ + public List<DataMiningType> getDataMiningTypes() { + return dataMiningTypes; + } + + /** + * @param dataMiningTypes + * the dataMiningTypes to set + * @see #dataMiningTypes + */ + public void setDataMiningTypes(List<DataMiningType> dataMiningTypes) { + this.dataMiningTypes = dataMiningTypes; + } + + /** + * @return the layoutBean + * @see #layoutBean + */ + public LayoutBean getLayoutBean() { + return layoutBean; + } + + /** + * @param layoutBean + * the layoutBean to set + * @see #layoutBean + */ + public void setLayoutBean(LayoutBean layoutBean) { + this.layoutBean = layoutBean; + } + + /** + * Clears list with information about zip entries in currently processed zip + * file. + */ + private void clearZipEntriesData() { + dataMiningZipEntries.clear(); + imageZipEntries.clear(); + layoutZipEntries.clear(); + modelZipEntries.clear(); + + } + + /** + * @return the dataMiningZipEntries + * @see #dataMiningZipEntries + */ + public List<DataMiningZipEntryFile> getDataMiningZipEntries() { + return dataMiningZipEntries; + } + + /** + * @param dataMiningZipEntries + * the dataMiningZipEntries to set + * @see #dataMiningZipEntries + */ + public void setDataMiningZipEntries(List<DataMiningZipEntryFile> dataMiningZipEntries) { + this.dataMiningZipEntries = dataMiningZipEntries; + } + + /** + * @return the modelZipEntries + * @see #modelZipEntries + */ + public List<ModelZipEntryFile> getModelZipEntries() { + return modelZipEntries; + } + + /** + * @param modelZipEntries + * the modelZipEntries to set + * @see #modelZipEntries + */ + public void setModelZipEntries(List<ModelZipEntryFile> modelZipEntries) { + this.modelZipEntries = modelZipEntries; + } + + /** + * @return the layoutZipEntries + * @see #layoutZipEntries + */ + public List<LayoutZipEntryFile> getLayoutZipEntries() { + return layoutZipEntries; + } + + /** + * @param layoutZipEntries + * the layoutZipEntries to set + * @see #layoutZipEntries + */ + public void setLayoutZipEntries(List<LayoutZipEntryFile> layoutZipEntries) { + this.layoutZipEntries = layoutZipEntries; + } + + /** + * @return the imageZipEntries + * @see #imageZipEntries + */ + public List<ImageZipEntryFile> getImageZipEntries() { + return imageZipEntries; + } + + /** + * @param imageZipEntries + * the imageZipEntries to set + * @see #imageZipEntries + */ + public void setImageZipEntries(List<ImageZipEntryFile> imageZipEntries) { + this.imageZipEntries = imageZipEntries; + } + + /** + * @return the newProjectName + * @see #newProjectName + */ + public String getNewProjectName() { + return newProjectName; + } + + /** + * @param newProjectName + * the newProjectName to set + * @see #newProjectName + */ + public void setNewProjectName(String newProjectName) { + this.newProjectName = newProjectName; + } + + /** + * @return the sbgnFormat + * @see #sbgnFormat + */ + public String getSbgnFormat() { + return sbgnFormat; + } + + /** + * @param sbgnFormat + * the sbgnFormat to set + * @see #sbgnFormat + */ + public void setSbgnFormat(String sbgnFormat) { + this.sbgnFormat = sbgnFormat; + } + + /** + * @return the networkLayoutAsDefault + * @see #networkLayoutAsDefault + */ + public String getNetworkLayoutAsDefault() { + return networkLayoutAsDefault; + } + + /** + * @param networkLayoutAsDefault + * the networkLayoutAsDefault to set + * @see #networkLayoutAsDefault + */ + public void setNetworkLayoutAsDefault(String networkLayoutAsDefault) { + this.networkLayoutAsDefault = networkLayoutAsDefault; + } + + /** + * @return new project disease. + */ + public String getNewProjectDisease() { + return newProjectDisease; + } + + /** + * @param newProjectDisease + * sets the disease + */ + public void setNewProjectDisease(String newProjectDisease) { + this.newProjectDisease = newProjectDisease; + } + + /** + * Method that trigger download of a file in jsf. The file is the source file + * used to create project given in the parameter. + * + * @param projectView + * view of the {@link Project} for which we are looking for an original + * source file + * @throws IOException + * thrown when there is a problem with sending file + * @throws SecurityException + */ + public void downloadInputData(ProjectView projectView) throws IOException, SecurityException { + // get input data from database + byte[] data = projectService.getInputDataForProject(projectView); + Project project = projectService.getProjectByProjectId(projectView.getProjectId(), + userBean.getAuthenticationToken()); + String string = new String(data, StandardCharsets.UTF_8); + + String fileName = project.getInputData().getOriginalFileName(); + MimeType respMimeType = null; + if (fileName.endsWith("xml")) { + respMimeType = MimeType.XML; + } else if (fileName.endsWith("zip")) { + respMimeType = MimeType.ZIP; + } else if (fileName.endsWith("sbgn")) { + respMimeType = MimeType.XML; + } else { + logger.warn("Cannot determine mime type of file: " + fileName); + respMimeType = MimeType.TEXT; + } + sendFileAsResponse(string, fileName, respMimeType); + } + + /** + * @return the newProjectOrganism + * @see #newProjectOrganism + */ + public String getNewProjectOrganism() { + return newProjectOrganism; + } + + /** + * @param newProjectOrganism + * the newProjectOrganism to set + * @see #newProjectOrganism + */ + public void setNewProjectOrganism(String newProjectOrganism) { + this.newProjectOrganism = newProjectOrganism; + } + + /** + * @return the semanticOverlay + * @see #semanticOverlay + */ + public String getSemanticOverlay() { + return semanticOverlay; + } + + /** + * @param semanticOverlay + * the semanticOverlay to set + * @see #semanticOverlay + */ + public void setSemanticOverlay(String semanticOverlay) { + this.semanticOverlay = semanticOverlay; + } } diff --git a/web/src/main/java/lcsb/mapviewer/bean/UserBean.java b/web/src/main/java/lcsb/mapviewer/bean/UserBean.java index 39c957b9171225f1b259f2d27f4de6e149056393..ad57da482f7c29d33617020b9ad8c47d93131ad0 100644 --- a/web/src/main/java/lcsb/mapviewer/bean/UserBean.java +++ b/web/src/main/java/lcsb/mapviewer/bean/UserBean.java @@ -3,7 +3,6 @@ package lcsb.mapviewer.bean; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; -import java.util.Calendar; import java.util.Map; import javax.faces.application.FacesMessage; @@ -35,7 +34,6 @@ import lcsb.mapviewer.services.interfaces.IConfigurationService; import lcsb.mapviewer.services.interfaces.ILogService; import lcsb.mapviewer.services.interfaces.ILogService.LogParams; import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.UserView; /** @@ -48,551 +46,560 @@ import lcsb.mapviewer.services.view.UserView; @SessionScoped public class UserBean extends AbstractManagedBean { - /** - * String representing {@link #login} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String LOGIN_PROPERTY = "LOGIN"; - - /** - * String representing {@link #password} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String PASSWORD_PROPERTY = "PASSWORD"; - - /** - * String representing {@link #loggedUser} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String LOGGED_USER_PROPERTY = "USER"; - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(UserBean.class); - - /** - * Login of currently logged user. - */ - private String login = ""; - - private AuthenticationToken authenticationToken; - - /** - * Password of currently logged user. - */ - private String password = ""; - - /** - * Email address that should be used when requesting an account. - */ - private String requestAccountEmail = ""; - - /** - * Currently logged user. The user is transient because it contains - * information from db and to serialize it properly we should provide - * apropriate converter. - */ - private User loggedUser = null; - - /** - * Object to use to edit user's profile. - */ - private UserView editUser = null; - - /** - * Service used to access information about users. - * - * @see IUserService - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * Service used to access logs. - * - * @see ILogService - */ - @ManagedProperty(value = "#{LogService}") - private transient ILogService logService; - - /** - * Service used to access configuration parameters. - * - * @see IConfigurationService - */ - @ManagedProperty(value = "#{ConfigurationService}") - private transient IConfigurationService configurationService; - - /** - * Default constructor. - */ - public UserBean() { - super(); - // we have to clear default list of property change listeners (we don't - // want - // to put passwords in the log file ;-)) - for (PropertyChangeListener listener : getPropertyChangeListeners()) { - removePropertyChangeListener(listener); - } - - // and now add custom logger property listener - PropertyChangeListener propertyChangeLogger = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (PASSWORD_PROPERTY.equals(arg0.getPropertyName())) { - logger.debug("Property changed: " + arg0.getPropertyName() + ". Old: *** New: ***"); - } else { - logger.debug("Property changed: " + arg0.getPropertyName() + ". Old: " + arg0.getOldValue() + " New: " + arg0.getNewValue()); - } - } - - }; - addPropertyChangeListener(propertyChangeLogger); - } - - @Override - public void init() { - PropertyChangeListener loginPasswordChanged = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (LOGIN_PROPERTY.equals(arg0.getPropertyName()) || PASSWORD_PROPERTY.equals(arg0.getPropertyName())) { - authenticationToken = getUserService().login(login, password); - if (authenticationToken != null) { - setLoggedUser(getUserService().getUserByLogin(login)); - } else { - authenticationToken = getUserService().login(Configuration.ANONYMOUS_LOGIN, ""); - setLoggedUser(getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN)); - } - } - } - }; - addPropertyChangeListener(loginPasswordChanged); - - PropertyChangeListener loggedUserChanged = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (LOGGED_USER_PROPERTY.equals(arg0.getPropertyName())) { - getLogService().setLoggedUser(getLoggedUser()); - } - } - }; - addPropertyChangeListener(loggedUserChanged); - - PropertyChangeListener logServiceLoggedUserChanged = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (LOGGED_USER_PROPERTY.equals(arg0.getPropertyName())) { - if (!getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN).equals(arg0.getOldValue())) { - LogParams params = new LogParams().type(LogType.USER_LOGOUT).object(arg0.getOldValue()); - getLogService().log(params); - } - - if (!getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN).equals(arg0.getNewValue())) { - LogParams params = new LogParams().type(LogType.USER_LOGIN).object(arg0.getNewValue()); - getLogService().log(params); - } - } - } - }; - addPropertyChangeListener(logServiceLoggedUserChanged); - - setLoggedUser(getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN)); - setRequestAccountEmail(getConfigurationService().getConfigurationValue(ConfigurationElementType.REQUEST_ACCOUNT_EMAIL)); - - } - - /** - * - * @return {@link #login} - */ - public String getLogin() { - return login; - } - - /** - * Sets new login value. Property change listeners for "login" property will - * be thrown after setting this value. - * - * @param login - * new {@link #login} value - */ - public void setLogin(final String login) { - String oldLogin = this.login; - this.login = login; - firePropertyChange(LOGIN_PROPERTY, oldLogin, login); - } - - /** - * Perform spring login operation. - * - * @throws IOException - * thrown when underlaying layer throws this exception - * @throws ServletException - * thrown when underlaying layer will throw this exception - */ - public void doLogin() throws IOException, ServletException { - doLogin(null); - } - - /** - * Perform spring login operation. - * - * @param id - * name of the map which should be used after authentication - * - * @throws IOException - * thrown when underlaying layer throws this exception - * @throws ServletException - * thrown when underlaying layer will throw this exception - */ - public void doLogin(String id) throws IOException, ServletException { - FacesContext context = FacesContext.getCurrentInstance(); - ExternalContext externalContext = context.getExternalContext(); - - ServletRequest request = (ServletRequest) externalContext.getRequest(); - Map<?, ?> map = request.getParameterMap(); - for (Object obj : map.keySet()) { - try { - String[] arr = (String[]) map.get(obj); - if (obj.equals("username")) { - setLogin(arr[0]); - } - if (obj.equals("password")) { - setPassword(arr[0]); - } - } catch (ClassCastException e) { - logger.error("WTF", e); - } - } - - // now perform spring authentication - String requestDispatcher = Configuration.SPRING_SECURITY_ACTION; - logger.debug(id); - if (id != null) { - requestDispatcher += "?id=" + id; - } - logger.debug(requestDispatcher); - - RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest()).getRequestDispatcher(requestDispatcher); - - dispatcher.forward((ServletRequest) externalContext.getRequest(), (ServletResponse) externalContext.getResponse()); - - context.responseComplete(); - } - - /** - * Performs spring login as anonymous. - * - * @throws IOException - * thrown when underlaying layer throws this exception - * @throws ServletException - * thrown when underlaying layer will throw this exception - */ - public void anonymousLogin() throws IOException, ServletException { - setLogin(Configuration.ANONYMOUS_LOGIN); - setPassword(""); - FacesContext context = FacesContext.getCurrentInstance(); - ExternalContext externalContext = context.getExternalContext(); - ServletRequest request = (ServletRequest) externalContext.getRequest(); - Map<?, ?> map = request.getParameterMap(); - for (Object obj : map.keySet()) { - try { - String[] arr = (String[]) map.get(obj); - if (obj.equals("username")) { - arr[0] = Configuration.ANONYMOUS_LOGIN; - } - if (obj.equals("password")) { - arr[0] = ""; - } - } catch (ClassCastException e) { - logger.error("WTF", e); - } - } - - RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest()).getRequestDispatcher(Configuration.SPRING_SECURITY_ACTION); - - dispatcher.forward((ServletRequest) externalContext.getRequest(), (ServletResponse) externalContext.getResponse()); - - context.responseComplete(); - } - - /** - * Perform spring logout operation. - * - * @param actionEvent - * event from thefrom the client - */ - public void doLogout(final ActionEvent actionEvent) { - try { - FacesContext context = FacesContext.getCurrentInstance(); - ExternalContext externalContext = context.getExternalContext(); - - RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest()).getRequestDispatcher(Configuration.SPRING_SECURITY_LOGOUT); - - dispatcher.forward((ServletRequest) externalContext.getRequest(), (ServletResponse) externalContext.getResponse()); - - context.responseComplete(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - - } - } - - /** - * - * @return {@link #password} - */ - public String getPassword() { - return password; - } - - /** - * Sets new password value. Property change listeners for "password" property - * will be thrown after setting this value. - * - * @param password - * new {@link #password} value - */ - public void setPassword(final String password) { - String oldPassword = this.password; - this.password = password; - firePropertyChange(PASSWORD_PROPERTY, oldPassword, password); - } - - /** - * - * @return {@link #loggedUser} - */ - public User getLoggedUser() { - if (loggedUser == null) { - loggedUser = getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN); - } - return loggedUser; - // return userService.getUserById(loggedUser.getIdObject()); - } - - /** - * Sets new loggedUser value. Property change listeners for "loggedUser" - * property will be thrown after setting this value. - * - * @param user - * new {@link #loggedUser} value - */ - public void setLoggedUser(final User user) { - User oldUser = this.loggedUser; - // loggedUser = getUserService().getUserView(user); - loggedUser = user; - firePropertyChange(LOGGED_USER_PROPERTY, oldUser, loggedUser); - } - - /** - * Check if user has privileges to manage the users. - * - * @return <i>true</i> if user has privileges to manage the users,<br/> - * <i>false</i> otherwise - */ - public boolean getUserHasManagePrivileges() { - User user = getLoggedUser(); - if (user == null) { - return false; - } - boolean result = getUserService().userHasPrivilege(user, PrivilegeType.USER_MANAGEMENT); - return result; - } - - @Override - public void clear() { - throw new NotImplementedException(); - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - if (userService == null) { - userService = findBean(IUserService.class); - } - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - /** - * @return the configurationService - * @see #configurationService - */ - public IConfigurationService getConfigurationService() { - if (configurationService == null) { - configurationService = findBean(IConfigurationService.class); - } - return configurationService; - } - - /** - * @param configurationService - * the configurationService to set - * @see #configurationService - */ - public void setConfigurationService(IConfigurationService configurationService) { - this.configurationService = configurationService; - } - - /** - * @return the requestAccountEmail - * @see #requestAccountEmail - */ - public String getRequestAccountEmail() { - return requestAccountEmail; - } - - /** - * @param requestAccountEmail - * the requestAccountEmail to set - * @see #requestAccountEmail - */ - public void setRequestAccountEmail(String requestAccountEmail) { - this.requestAccountEmail = requestAccountEmail; - } - - /** - * @return the logService - * @see #logService - */ - public ILogService getLogService() { - if (logService == null) { - logService = findBean(ILogService.class); - } - return logService; - } - - /** - * @param logService - * the logService to set - * @see #logService - */ - public void setLogService(ILogService logService) { - this.logService = logService; - } - - /** - * Refresh edit user. - */ - public void refreshEditUser() { - if (!loggedUser.getLogin().equals(Configuration.ANONYMOUS_LOGIN)) { - this.setEditUser(getUserService().getUserRow(loggedUser)); - RequestContext.getCurrentInstance().reset(":tabView:userForm2:panel"); - } - } - - /** - * @param ctx - * context - * @param component - * ui component - * @param value - * the new value - * @throws ValidatorException - * if validation fails - */ - public void checkOldPassword(FacesContext ctx, UIComponent component, Object value) throws ValidatorException { - UIInput passwordComp = (UIInput) component.getAttributes().get("passwordComp"); - if (passwordComp != null) { - String password = null; - password = (String) passwordComp.getValue(); - if (password != null && !password.isEmpty()) { - String oldPassword = (String) value; - if (oldPassword == null || oldPassword.isEmpty() || !this.getUserService().encodePassword(oldPassword).equals(editUser.getCryptedPassword())) { - ((UIInput) component).setValid(false); - FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Typed old password does not match stored one.", null); - throw new ValidatorException(message); - } - } - } - } - - /** - * @param ctx - * context - * @param component - * ui component - * @param value - * the new value - * @throws ValidatorException - * if validation fails - */ - public void checkNewPassword(FacesContext ctx, UIComponent component, Object value) throws ValidatorException { - UIInput passwordComp = (UIInput) component.getAttributes().get("passwordComp"); - if (passwordComp != null) { - String password = null; - password = (String) passwordComp.getValue(); - if (password != null && !password.isEmpty()) { - String oldPassword = (String) value; - if (oldPassword == null || oldPassword.isEmpty() || !this.getUserService().encodePassword(oldPassword).equals(editUser.getCryptedPassword())) { - ((UIInput) component).setValid(false); - FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Typed old password does not match stored one.", null); - throw new ValidatorException(message); - } - } - } - } - - /** - * Update selected user. - */ - public void updateUser() { - getUserService().updateUser(editUser); - setLoggedUser(getUserService().getUserByLogin(login)); - ObjectModifiedEvent event = new ObjectModifiedEvent(editUser); - callListeners(event); - } - - /** - * @return editable instance of the object. - */ - public UserView getEditUser() { - return editUser; - } - - /** - * @param editUser - * instance to be edited. - */ - public void setEditUser(UserView editUser) { - this.editUser = editUser; - } - - /** - * @return the authenticationToken - * @see #authenticationToken - */ - public AuthenticationToken getAuthenticationToken() { - if (authenticationToken == null) { - authenticationToken = getUserService().login(Configuration.ANONYMOUS_LOGIN, ""); - } - return authenticationToken; - } - - /** - * @param authenticationToken - * the authenticationToken to set - * @see #authenticationToken - */ - public void setAuthenticationToken(AuthenticationToken authenticationToken) { - this.authenticationToken = authenticationToken; - } + /** + * String representing {@link #login} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String LOGIN_PROPERTY = "LOGIN"; + + /** + * String representing {@link #password} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String PASSWORD_PROPERTY = "PASSWORD"; + + /** + * String representing {@link #loggedUser} property used by + * {@link #firePropertyChange(String, Object, Object)}. + */ + public static final String LOGGED_USER_PROPERTY = "USER"; + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(UserBean.class); + + /** + * Login of currently logged user. + */ + private String login = ""; + + private String authenticationToken; + + /** + * Password of currently logged user. + */ + private String password = ""; + + /** + * Email address that should be used when requesting an account. + */ + private String requestAccountEmail = ""; + + /** + * Currently logged user. The user is transient because it contains information + * from db and to serialize it properly we should provide apropriate converter. + */ + private User loggedUser = null; + + /** + * Object to use to edit user's profile. + */ + private UserView editUser = null; + + /** + * Service used to access information about users. + * + * @see IUserService + */ + @ManagedProperty(value = "#{UserService}") + private transient IUserService userService; + + /** + * Service used to access logs. + * + * @see ILogService + */ + @ManagedProperty(value = "#{LogService}") + private transient ILogService logService; + + /** + * Service used to access configuration parameters. + * + * @see IConfigurationService + */ + @ManagedProperty(value = "#{ConfigurationService}") + private transient IConfigurationService configurationService; + + /** + * Default constructor. + */ + public UserBean() { + super(); + // we have to clear default list of property change listeners (we don't + // want + // to put passwords in the log file ;-)) + for (PropertyChangeListener listener : getPropertyChangeListeners()) { + removePropertyChangeListener(listener); + } + + // and now add custom logger property listener + PropertyChangeListener propertyChangeLogger = new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent arg0) { + if (PASSWORD_PROPERTY.equals(arg0.getPropertyName())) { + logger.debug("Property changed: " + arg0.getPropertyName() + ". Old: *** New: ***"); + } else { + logger.debug("Property changed: " + arg0.getPropertyName() + ". Old: " + arg0.getOldValue() + " New: " + + arg0.getNewValue()); + } + } + + }; + addPropertyChangeListener(propertyChangeLogger); + } + + @Override + public void init() { + PropertyChangeListener loginPasswordChanged = new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent arg0) { + if (LOGIN_PROPERTY.equals(arg0.getPropertyName()) || PASSWORD_PROPERTY.equals(arg0.getPropertyName())) { + authenticationToken = getUserService().login(login, password); + if (authenticationToken != null) { + setLoggedUser(getUserService().getUserByLogin(login)); + } else { + authenticationToken = getUserService().login(Configuration.ANONYMOUS_LOGIN, ""); + setLoggedUser(getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN)); + } + } + } + }; + addPropertyChangeListener(loginPasswordChanged); + + PropertyChangeListener loggedUserChanged = new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent arg0) { + if (LOGGED_USER_PROPERTY.equals(arg0.getPropertyName())) { + getLogService().setLoggedUser(getLoggedUser()); + } + } + }; + addPropertyChangeListener(loggedUserChanged); + + PropertyChangeListener logServiceLoggedUserChanged = new PropertyChangeListener() { + @Override + public void propertyChange(final PropertyChangeEvent arg0) { + if (LOGGED_USER_PROPERTY.equals(arg0.getPropertyName())) { + if (!getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN).equals(arg0.getOldValue())) { + LogParams params = new LogParams().type(LogType.USER_LOGOUT).object(arg0.getOldValue()); + getLogService().log(params); + } + + if (!getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN).equals(arg0.getNewValue())) { + LogParams params = new LogParams().type(LogType.USER_LOGIN).object(arg0.getNewValue()); + getLogService().log(params); + } + } + } + }; + addPropertyChangeListener(logServiceLoggedUserChanged); + + setLoggedUser(getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN)); + setRequestAccountEmail( + getConfigurationService().getConfigurationValue(ConfigurationElementType.REQUEST_ACCOUNT_EMAIL)); + + } + + /** + * + * @return {@link #login} + */ + public String getLogin() { + return login; + } + + /** + * Sets new login value. Property change listeners for "login" property will be + * thrown after setting this value. + * + * @param login + * new {@link #login} value + */ + public void setLogin(final String login) { + String oldLogin = this.login; + this.login = login; + firePropertyChange(LOGIN_PROPERTY, oldLogin, login); + } + + /** + * Perform spring login operation. + * + * @throws IOException + * thrown when underlaying layer throws this exception + * @throws ServletException + * thrown when underlaying layer will throw this exception + */ + public void doLogin() throws IOException, ServletException { + doLogin(null); + } + + /** + * Perform spring login operation. + * + * @param id + * name of the map which should be used after authentication + * + * @throws IOException + * thrown when underlaying layer throws this exception + * @throws ServletException + * thrown when underlaying layer will throw this exception + */ + public void doLogin(String id) throws IOException, ServletException { + FacesContext context = FacesContext.getCurrentInstance(); + ExternalContext externalContext = context.getExternalContext(); + + ServletRequest request = (ServletRequest) externalContext.getRequest(); + Map<?, ?> map = request.getParameterMap(); + for (Object obj : map.keySet()) { + try { + String[] arr = (String[]) map.get(obj); + if (obj.equals("username")) { + setLogin(arr[0]); + } + if (obj.equals("password")) { + setPassword(arr[0]); + } + } catch (ClassCastException e) { + logger.error("WTF", e); + } + } + + // now perform spring authentication + String requestDispatcher = Configuration.SPRING_SECURITY_ACTION; + logger.debug(id); + if (id != null) { + requestDispatcher += "?id=" + id; + } + logger.debug(requestDispatcher); + + RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest()) + .getRequestDispatcher(requestDispatcher); + + dispatcher.forward((ServletRequest) externalContext.getRequest(), (ServletResponse) externalContext.getResponse()); + + context.responseComplete(); + } + + /** + * Performs spring login as anonymous. + * + * @throws IOException + * thrown when underlaying layer throws this exception + * @throws ServletException + * thrown when underlaying layer will throw this exception + */ + public void anonymousLogin() throws IOException, ServletException { + setLogin(Configuration.ANONYMOUS_LOGIN); + setPassword(""); + FacesContext context = FacesContext.getCurrentInstance(); + ExternalContext externalContext = context.getExternalContext(); + ServletRequest request = (ServletRequest) externalContext.getRequest(); + Map<?, ?> map = request.getParameterMap(); + for (Object obj : map.keySet()) { + try { + String[] arr = (String[]) map.get(obj); + if (obj.equals("username")) { + arr[0] = Configuration.ANONYMOUS_LOGIN; + } + if (obj.equals("password")) { + arr[0] = ""; + } + } catch (ClassCastException e) { + logger.error("WTF", e); + } + } + + RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest()) + .getRequestDispatcher(Configuration.SPRING_SECURITY_ACTION); + + dispatcher.forward((ServletRequest) externalContext.getRequest(), (ServletResponse) externalContext.getResponse()); + + context.responseComplete(); + } + + /** + * Perform spring logout operation. + * + * @param actionEvent + * event from thefrom the client + */ + public void doLogout(final ActionEvent actionEvent) { + try { + FacesContext context = FacesContext.getCurrentInstance(); + ExternalContext externalContext = context.getExternalContext(); + + RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest()) + .getRequestDispatcher(Configuration.SPRING_SECURITY_LOGOUT); + + dispatcher.forward((ServletRequest) externalContext.getRequest(), + (ServletResponse) externalContext.getResponse()); + + context.responseComplete(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + + } + } + + /** + * + * @return {@link #password} + */ + public String getPassword() { + return password; + } + + /** + * Sets new password value. Property change listeners for "password" property + * will be thrown after setting this value. + * + * @param password + * new {@link #password} value + */ + public void setPassword(final String password) { + String oldPassword = this.password; + this.password = password; + firePropertyChange(PASSWORD_PROPERTY, oldPassword, password); + } + + /** + * + * @return {@link #loggedUser} + */ + public User getLoggedUser() { + if (loggedUser == null) { + loggedUser = getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN); + } + return loggedUser; + // return userService.getUserById(loggedUser.getIdObject()); + } + + /** + * Sets new loggedUser value. Property change listeners for "loggedUser" + * property will be thrown after setting this value. + * + * @param user + * new {@link #loggedUser} value + */ + public void setLoggedUser(final User user) { + User oldUser = this.loggedUser; + // loggedUser = getUserService().getUserView(user); + loggedUser = user; + firePropertyChange(LOGGED_USER_PROPERTY, oldUser, loggedUser); + } + + /** + * Check if user has privileges to manage the users. + * + * @return <i>true</i> if user has privileges to manage the users,<br/> + * <i>false</i> otherwise + */ + public boolean getUserHasManagePrivileges() { + User user = getLoggedUser(); + if (user == null) { + return false; + } + boolean result = getUserService().userHasPrivilege(user, PrivilegeType.USER_MANAGEMENT); + return result; + } + + @Override + public void clear() { + throw new NotImplementedException(); + } + + /** + * @return the userService + * @see #userService + */ + public IUserService getUserService() { + if (userService == null) { + userService = findBean(IUserService.class); + } + return userService; + } + + /** + * @param userService + * the userService to set + * @see #userService + */ + public void setUserService(IUserService userService) { + this.userService = userService; + } + + /** + * @return the configurationService + * @see #configurationService + */ + public IConfigurationService getConfigurationService() { + if (configurationService == null) { + configurationService = findBean(IConfigurationService.class); + } + return configurationService; + } + + /** + * @param configurationService + * the configurationService to set + * @see #configurationService + */ + public void setConfigurationService(IConfigurationService configurationService) { + this.configurationService = configurationService; + } + + /** + * @return the requestAccountEmail + * @see #requestAccountEmail + */ + public String getRequestAccountEmail() { + return requestAccountEmail; + } + + /** + * @param requestAccountEmail + * the requestAccountEmail to set + * @see #requestAccountEmail + */ + public void setRequestAccountEmail(String requestAccountEmail) { + this.requestAccountEmail = requestAccountEmail; + } + + /** + * @return the logService + * @see #logService + */ + public ILogService getLogService() { + if (logService == null) { + logService = findBean(ILogService.class); + } + return logService; + } + + /** + * @param logService + * the logService to set + * @see #logService + */ + public void setLogService(ILogService logService) { + this.logService = logService; + } + + /** + * Refresh edit user. + */ + public void refreshEditUser() { + if (!loggedUser.getLogin().equals(Configuration.ANONYMOUS_LOGIN)) { + this.setEditUser(getUserService().getUserRow(loggedUser)); + RequestContext.getCurrentInstance().reset(":tabView:userForm2:panel"); + } + } + + /** + * @param ctx + * context + * @param component + * ui component + * @param value + * the new value + * @throws ValidatorException + * if validation fails + */ + public void checkOldPassword(FacesContext ctx, UIComponent component, Object value) throws ValidatorException { + UIInput passwordComp = (UIInput) component.getAttributes().get("passwordComp"); + if (passwordComp != null) { + String password = null; + password = (String) passwordComp.getValue(); + if (password != null && !password.isEmpty()) { + String oldPassword = (String) value; + if (oldPassword == null || oldPassword.isEmpty() + || !this.getUserService().encodePassword(oldPassword).equals(editUser.getCryptedPassword())) { + ((UIInput) component).setValid(false); + FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, + "Typed old password does not match stored one.", null); + throw new ValidatorException(message); + } + } + } + } + + /** + * @param ctx + * context + * @param component + * ui component + * @param value + * the new value + * @throws ValidatorException + * if validation fails + */ + public void checkNewPassword(FacesContext ctx, UIComponent component, Object value) throws ValidatorException { + UIInput passwordComp = (UIInput) component.getAttributes().get("passwordComp"); + if (passwordComp != null) { + String password = null; + password = (String) passwordComp.getValue(); + if (password != null && !password.isEmpty()) { + String oldPassword = (String) value; + if (oldPassword == null || oldPassword.isEmpty() + || !this.getUserService().encodePassword(oldPassword).equals(editUser.getCryptedPassword())) { + ((UIInput) component).setValid(false); + FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, + "Typed old password does not match stored one.", null); + throw new ValidatorException(message); + } + } + } + } + + /** + * Update selected user. + */ + public void updateUser() { + getUserService().updateUser(editUser); + setLoggedUser(getUserService().getUserByLogin(login)); + ObjectModifiedEvent event = new ObjectModifiedEvent(editUser); + callListeners(event); + } + + /** + * @return editable instance of the object. + */ + public UserView getEditUser() { + return editUser; + } + + /** + * @param editUser + * instance to be edited. + */ + public void setEditUser(UserView editUser) { + this.editUser = editUser; + } + + /** + * @return the authenticationToken + * @see #authenticationToken + */ + public String getAuthenticationToken() { + if (authenticationToken == null) { + authenticationToken = getUserService().login(Configuration.ANONYMOUS_LOGIN, ""); + } + return authenticationToken; + } + + /** + * @param authenticationToken + * the authenticationToken to set + * @see #authenticationToken + */ + public void setAuthenticationToken(String authenticationToken) { + this.authenticationToken = authenticationToken; + } } diff --git a/web/src/main/java/lcsb/mapviewer/security/MvInvalidSessionStrategy.java b/web/src/main/java/lcsb/mapviewer/security/MvInvalidSessionStrategy.java index e3c433620d78980b1e66eeae73f7a604ec160eae..b457ecbfe317618e8179068358c1ff5ee2b541e8 100644 --- a/web/src/main/java/lcsb/mapviewer/security/MvInvalidSessionStrategy.java +++ b/web/src/main/java/lcsb/mapviewer/security/MvInvalidSessionStrategy.java @@ -43,38 +43,38 @@ public class MvInvalidSessionStrategy implements InvalidSessionStrategy { @Override public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - boolean ajaxRedirect = "partial/ajax".equals(request.getHeader(FACES_REQUEST_HEADER)); - - if (!response.isCommitted()) { - if (ajaxRedirect) { - // with expired ajax queries we have a problem.. We must refresh webpage - // and create a new session, - // we cannot redirect directly to the original page, because browser - // won't reload it, - // so the trick is to send javascript code that will reload browser - String reloadString = createAjaxReloadPageXml(); - logger.info("Session expired with Ajax request, reloadXml:" + reloadString); - - response.setContentType("text/xml"); - response.getWriter().write(reloadString); - - } else { - String requestURI; - if (!Configuration.LOGIN_PAGE.endsWith(request.getServletPath())) { - // we don't want to redirect, let's keep the last url - requestURI = getRequestUrl(request); - logger.info("Session expired without Ajax request:" + requestURI); - } else { - requestURI = getRequestUrl(request); - logger.info("User forced logout" + requestURI); - } - - logger.info("Staring new session"); - request.getSession(true); - response.sendRedirect(requestURI); - } - } - return; +// boolean ajaxRedirect = "partial/ajax".equals(request.getHeader(FACES_REQUEST_HEADER)); +// +// if (!response.isCommitted()) { +// if (ajaxRedirect) { +// // with expired ajax queries we have a problem.. We must refresh webpage +// // and create a new session, +// // we cannot redirect directly to the original page, because browser +// // won't reload it, +// // so the trick is to send javascript code that will reload browser +// String reloadString = createAjaxReloadPageXml(); +// logger.info("Session expired with Ajax request, reloadXml:" + reloadString); +// +// response.setContentType("text/xml"); +// response.getWriter().write(reloadString); +// +// } else { +// String requestURI; +// if (!Configuration.LOGIN_PAGE.endsWith(request.getServletPath())) { +// // we don't want to redirect, let's keep the last url +// requestURI = getRequestUrl(request); +// logger.info("Session expired without Ajax request:" + requestURI); +// } else { +// requestURI = getRequestUrl(request); +// logger.info("User forced logout" + requestURI); +// } +// +// logger.info("Staring new session"); +// request.getSession(true); +// response.sendRedirect(requestURI); +// } +// } +// return; } /** diff --git a/web/src/main/webapp/WEB-INF/security-context.xml b/web/src/main/webapp/WEB-INF/security-context.xml index f294a895dd74770d90d5065fdb99f0879e920906..41c1b8c8345460bcd9bdaa0ae1320bfb3f61de05 100644 --- a/web/src/main/webapp/WEB-INF/security-context.xml +++ b/web/src/main/webapp/WEB-INF/security-context.xml @@ -48,7 +48,7 @@ <bean id="sessionManagementFilter" class="org.springframework.security.web.session.SessionManagementFilter"> <constructor-arg name="securityContextRepository" ref="httpSessionSecurityContextRepository" /> - <property name="invalidSessionStrategy" ref="mapViewerInvalidSessionStrategy"/> +<!-- <property name="invalidSessionStrategy" ref="mapViewerInvalidSessionStrategy"/> --> <property name="authenticationFailureHandler" ref="authenticationFailureHandler"/> </bean> @@ -95,13 +95,6 @@ <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" /> - <bean id="jsfRedirectStrategy" class="lcsb.mapviewer.security.MvJsfRedirectStrategy" /> - - <bean id="mapViewerInvalidSessionStrategy" class="lcsb.mapviewer.security.MvInvalidSessionStrategy" > -<!-- <constructor-arg name="invalidSessionUrl" value="viewExpired.xhtml"/> --> - <constructor-arg value="index.xhtml"/> -<!-- <constructor-arg name="invalidSessionUrl" value="index.xhtml"/> --> - </bean> <bean id="httpSessionSecurityContextRepository" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/> diff --git a/web/src/test/java/lcsb/mapviewer/bean/GalaxyBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/GalaxyBeanTest.java index 12824a17655664fa85b0a0bd6c9ac6576d99f6c2..21b132558e623e4bf1a8e8468fa9fdb3ad4aeee9 100644 --- a/web/src/test/java/lcsb/mapviewer/bean/GalaxyBeanTest.java +++ b/web/src/test/java/lcsb/mapviewer/bean/GalaxyBeanTest.java @@ -2,47 +2,47 @@ package lcsb.mapviewer.bean; import java.io.Serializable; -import lcsb.mapviewer.model.map.model.Model; - import org.apache.commons.lang3.SerializationUtils; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import lcsb.mapviewer.model.map.model.Model; +import lcsb.mapviewer.services.SecurityException; + public class GalaxyBeanTest extends WebTestFunctions { - GalaxyBean galaxyBean; - - @Before - public void setUp() throws Exception { - galaxyBean = new GalaxyBean(); - galaxyBean.setLayoutService(layoutService); - } - - @After - public void tearDown() throws Exception { - } - - @Test - @Ignore - public void test() { - galaxyBean.createLayout( - "CC75308E16F6AA9C", "NAME\tVALUE\nSNCA\t1\nPINK1\t-1\n", (Model) modelService.getLastModelByProjectId("pdmap", adminToken), - userService.getUserByLogin("galaxy")); - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(galaxyBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + GalaxyBean galaxyBean; + + @Before + public void setUp() throws Exception { + galaxyBean = new GalaxyBean(); + galaxyBean.setLayoutService(layoutService); + } + + @After + public void tearDown() throws Exception { + } + + @Test + @Ignore + public void test() throws SecurityException { + galaxyBean.createLayout("CC75308E16F6AA9C", "NAME\tVALUE\nSNCA\t1\nPINK1\t-1\n", + (Model) modelService.getLastModelByProjectId("pdmap", adminToken), userService.getUserByLogin("galaxy")); + } + + /** + * Checks if bean implements {@link Serializable} properly. + */ + @Test + public void testSearialization() { + try { + SerializationUtils.serialize(galaxyBean); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/web/src/test/java/lcsb/mapviewer/bean/WebTestFunctions.java b/web/src/test/java/lcsb/mapviewer/bean/WebTestFunctions.java index fccf8ea97ff33d35499ff9af035184565b46f1f5..af6b07728d1bdf9579c96fd73c5bb37ed04109a4 100644 --- a/web/src/test/java/lcsb/mapviewer/bean/WebTestFunctions.java +++ b/web/src/test/java/lcsb/mapviewer/bean/WebTestFunctions.java @@ -81,639 +81,638 @@ import lcsb.mapviewer.services.interfaces.ISearchService; import lcsb.mapviewer.services.interfaces.IUserService; import lcsb.mapviewer.services.search.db.chemical.IChemicalService; import lcsb.mapviewer.services.search.db.drug.IDrugService; -import lcsb.mapviewer.services.view.AuthenticationToken; import lcsb.mapviewer.services.view.ModelViewFactory; @Transactional(value = "txManager") @Rollback(true) @ContextConfiguration(locations = { "/applicationContext-persist.xml", // - "/applicationContext-annotation.xml", // - "/applicationContext-service.xml", // - "/dataSource.xml", // + "/applicationContext-annotation.xml", // + "/applicationContext-service.xml", // + "/dataSource.xml", // }) @RunWith(SpringJUnit4ClassRunner.class) public abstract class WebTestFunctions { - private Logger logger = Logger.getLogger(WebTestFunctions.class); + private Logger logger = Logger.getLogger(WebTestFunctions.class); - @Autowired - protected ChEMBLParser chemblParser; + @Autowired + protected ChEMBLParser chemblParser; - @Autowired - protected DrugbankHTMLParser drugBankHTMLParser; + @Autowired + protected DrugbankHTMLParser drugBankHTMLParser; - @Autowired - protected ModelAnnotator modelAnnotator; + @Autowired + protected ModelAnnotator modelAnnotator; - @Autowired - protected BiocompendiumAnnotator restService; + @Autowired + protected BiocompendiumAnnotator restService; - public double EPSILON = 1e-6; + public double EPSILON = 1e-6; - @Autowired - protected IConfigurationService configurationService; + @Autowired + protected IConfigurationService configurationService; - @Autowired - protected IModelService modelService; + @Autowired + protected IModelService modelService; - @Autowired - protected IExternalServicesService externalServicesService; + @Autowired + protected IExternalServicesService externalServicesService; - @Autowired - protected ILayoutService layoutService; + @Autowired + protected ILayoutService layoutService; - @Autowired - protected ILogService logService; + @Autowired + protected ILogService logService; - @Autowired - protected IExporterService exportService; + @Autowired + protected IExporterService exportService; - @Autowired - protected LogDao logDao; + @Autowired + protected LogDao logDao; - @Autowired - protected SearchHistoryDao searchHistoryDao; + @Autowired + protected SearchHistoryDao searchHistoryDao; - @Autowired - protected PasswordEncoder passwordEncoder; + @Autowired + protected PasswordEncoder passwordEncoder; - @Autowired - protected IUserService userService; + @Autowired + protected IUserService userService; - @Autowired - protected ConfigurationDao configurationDao; + @Autowired + protected ConfigurationDao configurationDao; - @Autowired - protected IDataMiningService dataMiningService; + @Autowired + protected IDataMiningService dataMiningService; - @Autowired - protected ISearchService searchService; + @Autowired + protected ISearchService searchService; - @Autowired - protected IDrugService drugService; + @Autowired + protected IDrugService drugService; - @Autowired - protected IChemicalService chemicalService; + @Autowired + protected IChemicalService chemicalService; - @Autowired - protected IProjectService projectService; + @Autowired + protected IProjectService projectService; - @Autowired - protected ProjectDao projectDao; + @Autowired + protected ProjectDao projectDao; - @Autowired - protected CacheQueryDao cacheQueryDao; + @Autowired + protected CacheQueryDao cacheQueryDao; - @Autowired - protected PolylineDao polylineDao; + @Autowired + protected PolylineDao polylineDao; - @Autowired - protected ModelDao modelDao; + @Autowired + protected ModelDao modelDao; - @Autowired - protected ICommentService commentService; + @Autowired + protected ICommentService commentService; - @Autowired - protected UserDao userDao; + @Autowired + protected UserDao userDao; - @Autowired - protected PrivilegeDao privilegeDao; + @Autowired + protected PrivilegeDao privilegeDao; - @Autowired - protected CommentDao commentDao; + @Autowired + protected CommentDao commentDao; - @Autowired - protected DbUtils dbUtils; + @Autowired + protected DbUtils dbUtils; - @Autowired - protected ReactionDao reactionDao; + @Autowired + protected ReactionDao reactionDao; - @Autowired - protected ElementDao aliasDao; + @Autowired + protected ElementDao aliasDao; - @Autowired - protected ModelViewFactory modelViewFactory; + @Autowired + protected ModelViewFactory modelViewFactory; - @Autowired - protected IReferenceGenomeService referenceGenomeService; + @Autowired + protected IReferenceGenomeService referenceGenomeService; - protected User user; + protected User user; - private ConfigurationBean configurationBean; - private LayoutBean layoutBean; - private MapBean mapBean; - private ProjectBean projectBean; - private UserBean userBean; + private ConfigurationBean configurationBean; + private LayoutBean layoutBean; + private MapBean mapBean; + private ProjectBean projectBean; + private UserBean userBean; - private ExportBean exportBean; + private ExportBean exportBean; - private FeedbackBean feedbackBean; - private MiriamBean miriamBean; - private MissingConnectionBean missingConnectionBean; - private SearchBean searchBean; - private UsersBean usersBean; + private FeedbackBean feedbackBean; + private MiriamBean miriamBean; + private MissingConnectionBean missingConnectionBean; + private SearchBean searchBean; + private UsersBean usersBean; - private ReferenceGenomeBean referenceGenomeBean; + private ReferenceGenomeBean referenceGenomeBean; - protected CustomPrimefacesUtils primefacesUtils = new CustomPrimefacesUtils(); + protected CustomPrimefacesUtils primefacesUtils = new CustomPrimefacesUtils(); - AuthenticationToken token; + String token; - AuthenticationToken adminToken; + String adminToken; - @Before - public void generalSetUp() { - dbUtils.setAutoFlush(false); - createConfigurationBean(); - createLayoutBean(); - createMapBean(); - createProjectBean(); - createUserBean(); - createExportBean(); - createFeedbackBean(); - createMiriamBean(); - createMissingConnectionBean(); - createSearchBean(); - createUsersBean(); - createReferenceGenomeBean(); - - configurationBean.internalInit(); - layoutBean.internalInit(); - mapBean.internalInit(); - projectBean.internalInit(); - userBean.internalInit(); - - exportBean.internalInit(); - - feedbackBean.internalInit(); - miriamBean.internalInit(); - missingConnectionBean.internalInit(); - searchBean.internalInit(); - usersBean.internalInit(); - - referenceGenomeBean.internalInit(); - - token = userService.login(Configuration.ANONYMOUS_LOGIN, null); - - // assume that we have admin account with all the privileges - adminToken = userService.login("admin", "admin"); - - } - - @After - public void generatTearDown() throws IOException { - File f = new File("map_images"); - if (f.exists()) { - logger.info("Removing output test directory: " + f.getAbsolutePath()); - FileUtils.deleteDirectory(f); - } - - } - - protected String readFile(String file) throws IOException { - StringBuilder stringBuilder = new StringBuilder(); - BufferedReader reader = new BufferedReader(new FileReader(file)); - try { - String line = null; - String ls = System.getProperty("line.separator"); - - while ((line = reader.readLine()) != null) { - stringBuilder.append(line); - stringBuilder.append(ls); - } - } finally { - reader.close(); - } - - return stringBuilder.toString(); - } - - protected Node getNodeFromXmlString(String text) throws InvalidXmlSchemaException { - InputSource is = new InputSource(); - is.setCharacterStream(new StringReader(text)); - return getXmlDocumentFromInputSource(is).getChildNodes().item(0); - } - - protected Document getXmlDocumentFromFile(String fileName) throws InvalidXmlSchemaException, IOException { - File file = new File(fileName); - InputStream inputStream = new FileInputStream(file); - Reader reader = null; - try { - reader = new InputStreamReader(inputStream, "UTF-8"); - InputSource is = new InputSource(reader); - - Document result = getXmlDocumentFromInputSource(is); - inputStream.close(); - return result; - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; - } - - protected Document getXmlDocumentFromInputSource(InputSource stream) throws InvalidXmlSchemaException { - DocumentBuilder db; - try { - db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw new InvalidXmlSchemaException("Problem with xml parser"); - } - Document doc = null; - try { - doc = db.parse(stream); - } catch (SAXException e) { - logger.error(e); - } catch (IOException e) { - logger.error(e); - } - return doc; - } - - /** - * This method remove model with all connections from db (used only when the - * db must be handled manually) - * - * @param id - */ - protected void removeModelById(int id) { - modelDao.delete(modelDao.getById(id)); - } - - protected void createUser() { - user = userDao.getUserByLogin("john.doe"); - if (user == null) { - user = new User(); - user.setName("John"); - user.setSurname("Doe"); - user.setEmail("john.doe@uni.lu"); - user.setLogin("john.doe"); - user.setCryptedPassword(passwordEncoder.encode("passwd")); - userDao.add(user); - } - } - - private static Map<String, Model> models = new HashMap<String, Model>(); - - protected Model getModelForFile(String fileName, boolean fromCache) throws Exception { - if (!fromCache) { - logger.debug("File without cache: " + fileName); - return new CellDesignerXmlParser().createModel(new ConverterParams().filename(fileName)); - } - Model result = WebTestFunctions.models.get(fileName); - if (result == null) { - logger.debug("File to cache: " + fileName); - - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - result = parser.createModel(new ConverterParams().filename(fileName).sizeAutoAdjust(false)); - WebTestFunctions.models.put(fileName, result); - } - return result; - } - - protected String createTmpFileName() { - try { - File f = File.createTempFile("prefix", ".txt"); - String filename = f.getName(); - f.delete(); - return filename; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - protected String nodeToString(Node node) { - return nodeToString(node, false); - } - - protected String nodeToString(Node node, boolean includeHeadNode) { - if (node == null) - return null; - StringWriter sw = new StringWriter(); - try { - Transformer t = TransformerFactory.newInstance().newTransformer(); - t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - t.setOutputProperty(OutputKeys.INDENT, "yes"); - t.setOutputProperty(OutputKeys.METHOD, "xml"); - - NodeList list = node.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) { - Node element = list.item(i); - t.transform(new DOMSource(element), new StreamResult(sw)); - } - } catch (TransformerException te) { - logger.debug("nodeToString Transformer Exception"); - } - if (includeHeadNode) { - return "<" + node.getNodeName() + ">" + sw.toString() + "</" + node.getNodeName() + ">"; - } - return sw.toString(); - } - - protected boolean equalFiles(String fileA, String fileB) throws IOException { - int BLOCK_SIZE = 65536; - FileInputStream inputStreamA = new FileInputStream(fileA); - FileInputStream inputStreamB = new FileInputStream(fileB); - // vary BLOCK_SIZE to suit yourself. - // it should probably a factor or multiple of the size of a disk - // sector/cluster. - // Note that your max heap size may need to be adjused - // if you have a very big block size or lots of these comparators. - - // assume inputStreamA and inputStreamB are streams from your two files. - byte[] streamABlock = new byte[BLOCK_SIZE]; - byte[] streamBBlock = new byte[BLOCK_SIZE]; - boolean match = true; - int bytesReadA = 0; - int bytesReadB = 0; - do { - bytesReadA = inputStreamA.read(streamABlock); - bytesReadB = inputStreamB.read(streamBBlock); - match = ((bytesReadA == bytesReadB) && Arrays.equals(streamABlock, streamBBlock)); - } while (match && (bytesReadA > -1)); - inputStreamA.close(); - inputStreamB.close(); - return match; - } - - public PrivilegeDao getPrivilegeDao() { - return privilegeDao; - } - - public void setPrivilegeDao(PrivilegeDao privilegeDao) { - this.privilegeDao = privilegeDao; - } - - public File createTempDirectory() throws IOException { - final File temp; - - temp = File.createTempFile("temp", Long.toString(System.nanoTime())); - - if (!(temp.delete())) { - throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); - } - - if (!(temp.mkdir())) { - throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); - } - - return (temp); - } - - protected String getWebpage(String accessUrl) throws IOException { - String inputLine; - StringBuilder tmp = new StringBuilder(); - URL url = new URL(accessUrl); - URLConnection urlConn = url.openConnection(); - BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); - - while ((inputLine = in.readLine()) != null) { - tmp.append(inputLine); - } - in.close(); - return tmp.toString(); - } - - protected UserBean getUserBean() { - if (userBean == null) { - createUserBean(); - } - return userBean; - } - - protected LayoutBean getLayoutBean() { - if (layoutBean == null) { - createLayoutBean(); - } - return layoutBean; - } - - private void createUserBean() { - if (userBean != null) { - return; - } - userBean = new UserBean(); - userBean.setPrimefacesUtils(primefacesUtils); - - userBean.setUserService(userService); - userBean.setConfigurationService(configurationService); - userBean.setLogService(logService); - - } - - private void createLayoutBean() { - if (layoutBean != null) { - return; - } - layoutBean = new LayoutBean(); - layoutBean.setPrimefacesUtils(primefacesUtils); - - layoutBean.setLayoutService(layoutService); - layoutBean.setModelService(modelService); - layoutBean.setUserBean(getUserBean()); - layoutBean.setMapBean(getMapBean()); - - } - - protected MapBean getMapBean() { - if (mapBean == null) { - createMapBean(); - } - return mapBean; - } - - private void createMapBean() { - if (mapBean != null) { - return; - } - mapBean = new MapBean(); - mapBean.setPrimefacesUtils(primefacesUtils); - - mapBean.setConfService(configurationService); - mapBean.setModelService(modelService); - mapBean.setProjectService(projectService); - mapBean.setConfigurationService(configurationService); - mapBean.setModelService(modelService); - mapBean.setUserService(userService); - mapBean.setUserBean(getUserBean()); - } - - protected ProjectBean getProjectBean() { - if (projectBean == null) { - createProjectBean(); - } - return projectBean; - } - - private void createProjectBean() { - if (projectBean != null) { - return; - } - projectBean = new ProjectBean(); - projectBean.setPrimefacesUtils(primefacesUtils); - - projectBean.setConfigurationService(configurationService); - projectBean.setModelService(modelService); - projectBean.setProjectService(projectService); - projectBean.setUserService(userService); - - projectBean.setLayoutBean(getLayoutBean()); - projectBean.setUserBean(getUserBean()); - } - - protected ExportBean getExportBean() { - if (exportBean == null) { - createExportBean(); - } - return exportBean; - } - - private void createExportBean() { - if (exportBean != null) { - return; - } - exportBean = new ExportBean(); - exportBean.setPrimefacesUtils(primefacesUtils); - - exportBean.setExporterService(exportService); - exportBean.setMapBean(getMapBean()); - } - - protected ConfigurationBean getConfigurationBean() { - if (configurationBean == null) { - createConfigurationBean(); - } - return configurationBean; - } - - private void createConfigurationBean() { - if (configurationBean != null) { - return; - } - configurationBean = new ConfigurationBean(); - configurationBean.setPrimefacesUtils(primefacesUtils); - - configurationBean.setConfigurationService(configurationService); - configurationBean.setUserService(userService); - configurationBean.setProjectService(projectService); - - configurationBean.setUserBean(getUserBean()); - } - - protected FeedbackBean getFeedbackBean() { - if (feedbackBean == null) { - createFeedbackBean(); - } - return feedbackBean; - } - - protected MiriamBean getMiriamBean() { - if (miriamBean == null) { - createMiriamBean(); - } - return miriamBean; - } - - protected MissingConnectionBean getMissingConnectionBean() { - if (missingConnectionBean == null) { - createMissingConnectionBean(); - } - return missingConnectionBean; - } - - protected SearchBean getSearchBean() { - if (searchBean == null) { - createSearchBean(); - } - return searchBean; - } - - protected UsersBean getUsersBean() { - if (usersBean == null) { - createUsersBean(); - } - return usersBean; - } - - private void createFeedbackBean() { - if (feedbackBean != null) { - return; - } - feedbackBean = new FeedbackBean(); - feedbackBean.setPrimefacesUtils(primefacesUtils); - - feedbackBean.setCommentService(commentService); - feedbackBean.setUserService(userService); - feedbackBean.setUserBean(userBean); - - feedbackBean.setUserBean(getUserBean()); - feedbackBean.setMapBean(getMapBean()); - - } - - private void createMiriamBean() { - if (miriamBean != null) { - return; - } - miriamBean = new MiriamBean(); - miriamBean.setPrimefacesUtils(primefacesUtils); - - } - - private void createMissingConnectionBean() { - if (missingConnectionBean != null) { - return; - } - missingConnectionBean = new MissingConnectionBean(); - missingConnectionBean.setPrimefacesUtils(primefacesUtils); - } - - private void createSearchBean() { - if (searchBean != null) { - return; - } - searchBean = new SearchBean(); - searchBean.setPrimefacesUtils(primefacesUtils); - - searchBean.setConfigurationService(configurationService); - searchBean.setUserService(userService); - - searchBean.setUserBean(getUserBean()); - searchBean.setMapBean(getMapBean()); - } - - private void createUsersBean() { - if (usersBean != null) { - return; - } - usersBean = new UsersBean(); - usersBean.setPrimefacesUtils(primefacesUtils); - - usersBean.setUserService(userService); - - usersBean.setUserBean(getUserBean()); - usersBean.setProjectBean(getProjectBean()); - } - - public ReferenceGenomeBean getReferenceGenomeBean() { - if (referenceGenomeBean == null) { - createReferenceGenomeBean(); - } - return referenceGenomeBean; - } - - private void createReferenceGenomeBean() { - if (referenceGenomeBean != null) { - return; - } - referenceGenomeBean = new ReferenceGenomeBean(); - referenceGenomeBean.setPrimefacesUtils(primefacesUtils); - - referenceGenomeBean.setReferenceGenomeService(referenceGenomeService); - referenceGenomeBean.setUserBean(getUserBean()); - referenceGenomeBean.setUserService(userService); - referenceGenomeBean.setMapBean(getMapBean()); - - } + @Before + public void generalSetUp() { + dbUtils.setAutoFlush(false); + createConfigurationBean(); + createLayoutBean(); + createMapBean(); + createProjectBean(); + createUserBean(); + createExportBean(); + createFeedbackBean(); + createMiriamBean(); + createMissingConnectionBean(); + createSearchBean(); + createUsersBean(); + createReferenceGenomeBean(); + + configurationBean.internalInit(); + layoutBean.internalInit(); + mapBean.internalInit(); + projectBean.internalInit(); + userBean.internalInit(); + + exportBean.internalInit(); + + feedbackBean.internalInit(); + miriamBean.internalInit(); + missingConnectionBean.internalInit(); + searchBean.internalInit(); + usersBean.internalInit(); + + referenceGenomeBean.internalInit(); + + token = userService.login(Configuration.ANONYMOUS_LOGIN, null); + + // assume that we have admin account with all the privileges + adminToken = userService.login("admin", "admin"); + + } + + @After + public void generatTearDown() throws IOException { + File f = new File("map_images"); + if (f.exists()) { + logger.info("Removing output test directory: " + f.getAbsolutePath()); + FileUtils.deleteDirectory(f); + } + + } + + protected String readFile(String file) throws IOException { + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader reader = new BufferedReader(new FileReader(file)); + try { + String line = null; + String ls = System.getProperty("line.separator"); + + while ((line = reader.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append(ls); + } + } finally { + reader.close(); + } + + return stringBuilder.toString(); + } + + protected Node getNodeFromXmlString(String text) throws InvalidXmlSchemaException { + InputSource is = new InputSource(); + is.setCharacterStream(new StringReader(text)); + return getXmlDocumentFromInputSource(is).getChildNodes().item(0); + } + + protected Document getXmlDocumentFromFile(String fileName) throws InvalidXmlSchemaException, IOException { + File file = new File(fileName); + InputStream inputStream = new FileInputStream(file); + Reader reader = null; + try { + reader = new InputStreamReader(inputStream, "UTF-8"); + InputSource is = new InputSource(reader); + + Document result = getXmlDocumentFromInputSource(is); + inputStream.close(); + return result; + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } + + protected Document getXmlDocumentFromInputSource(InputSource stream) throws InvalidXmlSchemaException { + DocumentBuilder db; + try { + db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + } catch (ParserConfigurationException e) { + throw new InvalidXmlSchemaException("Problem with xml parser"); + } + Document doc = null; + try { + doc = db.parse(stream); + } catch (SAXException e) { + logger.error(e); + } catch (IOException e) { + logger.error(e); + } + return doc; + } + + /** + * This method remove model with all connections from db (used only when the db + * must be handled manually) + * + * @param id + */ + protected void removeModelById(int id) { + modelDao.delete(modelDao.getById(id)); + } + + protected void createUser() { + user = userDao.getUserByLogin("john.doe"); + if (user == null) { + user = new User(); + user.setName("John"); + user.setSurname("Doe"); + user.setEmail("john.doe@uni.lu"); + user.setLogin("john.doe"); + user.setCryptedPassword(passwordEncoder.encode("passwd")); + userDao.add(user); + } + } + + private static Map<String, Model> models = new HashMap<String, Model>(); + + protected Model getModelForFile(String fileName, boolean fromCache) throws Exception { + if (!fromCache) { + logger.debug("File without cache: " + fileName); + return new CellDesignerXmlParser().createModel(new ConverterParams().filename(fileName)); + } + Model result = WebTestFunctions.models.get(fileName); + if (result == null) { + logger.debug("File to cache: " + fileName); + + CellDesignerXmlParser parser = new CellDesignerXmlParser(); + result = parser.createModel(new ConverterParams().filename(fileName).sizeAutoAdjust(false)); + WebTestFunctions.models.put(fileName, result); + } + return result; + } + + protected String createTmpFileName() { + try { + File f = File.createTempFile("prefix", ".txt"); + String filename = f.getName(); + f.delete(); + return filename; + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + + protected String nodeToString(Node node) { + return nodeToString(node, false); + } + + protected String nodeToString(Node node, boolean includeHeadNode) { + if (node == null) + return null; + StringWriter sw = new StringWriter(); + try { + Transformer t = TransformerFactory.newInstance().newTransformer(); + t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + t.setOutputProperty(OutputKeys.INDENT, "yes"); + t.setOutputProperty(OutputKeys.METHOD, "xml"); + + NodeList list = node.getChildNodes(); + for (int i = 0; i < list.getLength(); i++) { + Node element = list.item(i); + t.transform(new DOMSource(element), new StreamResult(sw)); + } + } catch (TransformerException te) { + logger.debug("nodeToString Transformer Exception"); + } + if (includeHeadNode) { + return "<" + node.getNodeName() + ">" + sw.toString() + "</" + node.getNodeName() + ">"; + } + return sw.toString(); + } + + protected boolean equalFiles(String fileA, String fileB) throws IOException { + int BLOCK_SIZE = 65536; + FileInputStream inputStreamA = new FileInputStream(fileA); + FileInputStream inputStreamB = new FileInputStream(fileB); + // vary BLOCK_SIZE to suit yourself. + // it should probably a factor or multiple of the size of a disk + // sector/cluster. + // Note that your max heap size may need to be adjused + // if you have a very big block size or lots of these comparators. + + // assume inputStreamA and inputStreamB are streams from your two files. + byte[] streamABlock = new byte[BLOCK_SIZE]; + byte[] streamBBlock = new byte[BLOCK_SIZE]; + boolean match = true; + int bytesReadA = 0; + int bytesReadB = 0; + do { + bytesReadA = inputStreamA.read(streamABlock); + bytesReadB = inputStreamB.read(streamBBlock); + match = ((bytesReadA == bytesReadB) && Arrays.equals(streamABlock, streamBBlock)); + } while (match && (bytesReadA > -1)); + inputStreamA.close(); + inputStreamB.close(); + return match; + } + + public PrivilegeDao getPrivilegeDao() { + return privilegeDao; + } + + public void setPrivilegeDao(PrivilegeDao privilegeDao) { + this.privilegeDao = privilegeDao; + } + + public File createTempDirectory() throws IOException { + final File temp; + + temp = File.createTempFile("temp", Long.toString(System.nanoTime())); + + if (!(temp.delete())) { + throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); + } + + if (!(temp.mkdir())) { + throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); + } + + return (temp); + } + + protected String getWebpage(String accessUrl) throws IOException { + String inputLine; + StringBuilder tmp = new StringBuilder(); + URL url = new URL(accessUrl); + URLConnection urlConn = url.openConnection(); + BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); + + while ((inputLine = in.readLine()) != null) { + tmp.append(inputLine); + } + in.close(); + return tmp.toString(); + } + + protected UserBean getUserBean() { + if (userBean == null) { + createUserBean(); + } + return userBean; + } + + protected LayoutBean getLayoutBean() { + if (layoutBean == null) { + createLayoutBean(); + } + return layoutBean; + } + + private void createUserBean() { + if (userBean != null) { + return; + } + userBean = new UserBean(); + userBean.setPrimefacesUtils(primefacesUtils); + + userBean.setUserService(userService); + userBean.setConfigurationService(configurationService); + userBean.setLogService(logService); + + } + + private void createLayoutBean() { + if (layoutBean != null) { + return; + } + layoutBean = new LayoutBean(); + layoutBean.setPrimefacesUtils(primefacesUtils); + + layoutBean.setLayoutService(layoutService); + layoutBean.setModelService(modelService); + layoutBean.setUserBean(getUserBean()); + layoutBean.setMapBean(getMapBean()); + + } + + protected MapBean getMapBean() { + if (mapBean == null) { + createMapBean(); + } + return mapBean; + } + + private void createMapBean() { + if (mapBean != null) { + return; + } + mapBean = new MapBean(); + mapBean.setPrimefacesUtils(primefacesUtils); + + mapBean.setConfService(configurationService); + mapBean.setModelService(modelService); + mapBean.setProjectService(projectService); + mapBean.setConfigurationService(configurationService); + mapBean.setModelService(modelService); + mapBean.setUserService(userService); + mapBean.setUserBean(getUserBean()); + } + + protected ProjectBean getProjectBean() { + if (projectBean == null) { + createProjectBean(); + } + return projectBean; + } + + private void createProjectBean() { + if (projectBean != null) { + return; + } + projectBean = new ProjectBean(); + projectBean.setPrimefacesUtils(primefacesUtils); + + projectBean.setConfigurationService(configurationService); + projectBean.setModelService(modelService); + projectBean.setProjectService(projectService); + projectBean.setUserService(userService); + + projectBean.setLayoutBean(getLayoutBean()); + projectBean.setUserBean(getUserBean()); + } + + protected ExportBean getExportBean() { + if (exportBean == null) { + createExportBean(); + } + return exportBean; + } + + private void createExportBean() { + if (exportBean != null) { + return; + } + exportBean = new ExportBean(); + exportBean.setPrimefacesUtils(primefacesUtils); + + exportBean.setExporterService(exportService); + exportBean.setMapBean(getMapBean()); + } + + protected ConfigurationBean getConfigurationBean() { + if (configurationBean == null) { + createConfigurationBean(); + } + return configurationBean; + } + + private void createConfigurationBean() { + if (configurationBean != null) { + return; + } + configurationBean = new ConfigurationBean(); + configurationBean.setPrimefacesUtils(primefacesUtils); + + configurationBean.setConfigurationService(configurationService); + configurationBean.setUserService(userService); + configurationBean.setProjectService(projectService); + + configurationBean.setUserBean(getUserBean()); + } + + protected FeedbackBean getFeedbackBean() { + if (feedbackBean == null) { + createFeedbackBean(); + } + return feedbackBean; + } + + protected MiriamBean getMiriamBean() { + if (miriamBean == null) { + createMiriamBean(); + } + return miriamBean; + } + + protected MissingConnectionBean getMissingConnectionBean() { + if (missingConnectionBean == null) { + createMissingConnectionBean(); + } + return missingConnectionBean; + } + + protected SearchBean getSearchBean() { + if (searchBean == null) { + createSearchBean(); + } + return searchBean; + } + + protected UsersBean getUsersBean() { + if (usersBean == null) { + createUsersBean(); + } + return usersBean; + } + + private void createFeedbackBean() { + if (feedbackBean != null) { + return; + } + feedbackBean = new FeedbackBean(); + feedbackBean.setPrimefacesUtils(primefacesUtils); + + feedbackBean.setCommentService(commentService); + feedbackBean.setUserService(userService); + feedbackBean.setUserBean(userBean); + + feedbackBean.setUserBean(getUserBean()); + feedbackBean.setMapBean(getMapBean()); + + } + + private void createMiriamBean() { + if (miriamBean != null) { + return; + } + miriamBean = new MiriamBean(); + miriamBean.setPrimefacesUtils(primefacesUtils); + + } + + private void createMissingConnectionBean() { + if (missingConnectionBean != null) { + return; + } + missingConnectionBean = new MissingConnectionBean(); + missingConnectionBean.setPrimefacesUtils(primefacesUtils); + } + + private void createSearchBean() { + if (searchBean != null) { + return; + } + searchBean = new SearchBean(); + searchBean.setPrimefacesUtils(primefacesUtils); + + searchBean.setConfigurationService(configurationService); + searchBean.setUserService(userService); + + searchBean.setUserBean(getUserBean()); + searchBean.setMapBean(getMapBean()); + } + + private void createUsersBean() { + if (usersBean != null) { + return; + } + usersBean = new UsersBean(); + usersBean.setPrimefacesUtils(primefacesUtils); + + usersBean.setUserService(userService); + + usersBean.setUserBean(getUserBean()); + usersBean.setProjectBean(getProjectBean()); + } + + public ReferenceGenomeBean getReferenceGenomeBean() { + if (referenceGenomeBean == null) { + createReferenceGenomeBean(); + } + return referenceGenomeBean; + } + + private void createReferenceGenomeBean() { + if (referenceGenomeBean != null) { + return; + } + referenceGenomeBean = new ReferenceGenomeBean(); + referenceGenomeBean.setPrimefacesUtils(primefacesUtils); + + referenceGenomeBean.setReferenceGenomeService(referenceGenomeService); + referenceGenomeBean.setUserBean(getUserBean()); + referenceGenomeBean.setUserService(userService); + referenceGenomeBean.setMapBean(getMapBean()); + + } }