diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalParser.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalParser.java index 886b9f1a894bf2195bb37507fed14282c403c704..4172c33e14352d92fffbcd540394c76e396246d5 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalParser.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ChemicalParser.java @@ -1,6 +1,5 @@ package lcsb.mapviewer.annotation.services; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java index 792c63710303c061a1a4067a954d7dbafdb843d0..dfe1637a68abe0d90ce01601e3663b2ea2747d21 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/ModelAnnotator.java @@ -12,13 +12,12 @@ import java.util.Set; import javax.annotation.PostConstruct; -import org.apache.commons.logging.Log; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; -import lcsb.mapviewer.annotation.services.annotators.BrendaAnnotator; import lcsb.mapviewer.annotation.services.annotators.BiocompendiumAnnotator; +import lcsb.mapviewer.annotation.services.annotators.BrendaAnnotator; import lcsb.mapviewer.annotation.services.annotators.CazyAnnotator; import lcsb.mapviewer.annotation.services.annotators.ChebiAnnotator; import lcsb.mapviewer.annotation.services.annotators.ElementAnnotator; @@ -54,673 +53,677 @@ import lcsb.mapviewer.modelutils.map.ElementUtils; */ public class ModelAnnotator { - /** - * Time required for annotating in - * {@link #performAnnotations(Model, IProgressUpdater)} method. - */ - private static final double ANNOTATING_RATIO = 0.8; - /** - * Time required for copying annotations from other elements in - * {@link #performAnnotations(Model, IProgressUpdater)} method. - */ - private static final double COPYING_RATIO = 0.2; - - /** - * Connector used for accessing data from miriam registry. - */ - @Autowired - private MiriamConnector miriamConnector; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(ModelAnnotator.class); - - /** - * BRENDA annotator. - */ - @Autowired - private BrendaAnnotator brendaAnnotator; - - /** - * Service accessing <a href= "http://biocompendium.embl.de/" >internal - * annotating service</a>. - */ - @Autowired - private BiocompendiumAnnotator biocompendiumAnnotator; - - /** - * CAZy annotator. - */ - @Autowired - private CazyAnnotator cazyAnnotator; - - /** - * Backend to the chebi database. - */ - @Autowired - private ChebiAnnotator chebiBackend; - - /** - * Uniprot annotator. - */ - @Autowired - private UniprotAnnotator uniprotAnnotator; - - /** - * PDB annotator. - */ - @Autowired - private PdbAnnotator pdbAnnotator; - - /** - * Recon annotator. - */ - @Autowired - private ReconAnnotator reconAnnotator; - - /** - * Service accessing <a href= "http://www.ebi.ac.uk/QuickGO/" >Gene - * Ontology</a>. - */ - @Autowired - private GoAnnotator goAnnotator; - - /** - * Service accessing <a href= "http://www.genenames.org/" >HUGO Gene - * Nomenclature Committee</a>. - */ - @Autowired - private HgncAnnotator hgncAnnotator; - - /** - * Service accessing <a href= "http://www.kegg.jp/" > KEGG EC Nomenclature</a>. - */ - @Autowired - private KeggAnnotator keggAnnotator; - - /** - * Service accessing <a href= "http://www.ncbi.nlm.nih.gov/gene/" >Entrez</a>. - */ - @Autowired - private EntrezAnnotator entrezAnnotator; - - /** - * Service accessing <a href= "http://ensembl.org">Ensembl</a>. - */ - @Autowired - private EnsemblAnnotator ensemblAnnotator; - - /** - * STITCH annotator. - */ - @Autowired - private StitchAnnotator stitchAnnotator; - - /** - * STRING annotator. - */ - @Autowired - private StringAnnotator stringAnnotator; - - /** - * TAIR annotator. - */ - @Autowired - private TairAnnotator tairAnnotator; - - - /** - * List of all avaliable {@link ElementAnnotator} objects. - */ - private List<ElementAnnotator> availableAnnotators; - - /** - * List of all avaliable {@link ElementAnnotator} objects. - */ - private List<ElementAnnotator> defaultAnnotators; - - /** - * Post intintialization method. Will be called after spring creates beans and - * set the list of valid annotators. - */ - @PostConstruct - public final void init() { - availableAnnotators = new ArrayList<>(); - defaultAnnotators = new ArrayList<>(); - - addAnnotator(brendaAnnotator); - addAnnotator(biocompendiumAnnotator); - addAnnotator(cazyAnnotator); - addAnnotator(chebiBackend); - addAnnotator(uniprotAnnotator); - addAnnotator(goAnnotator); - addAnnotator(hgncAnnotator); - addAnnotator(keggAnnotator); - addAnnotator(pdbAnnotator); - addAnnotator(reconAnnotator); - addAnnotator(entrezAnnotator); - addAnnotator(ensemblAnnotator); - addAnnotator(stitchAnnotator); - addAnnotator(stringAnnotator); - addAnnotator(tairAnnotator); - } - - /** - * Adds annotator list of available annotators in {@link ModelAnnotator} - * class. - * - * @param annotator - * {@link ElementAnnotator} annotator o add - */ - private void addAnnotator(ElementAnnotator annotator) { - availableAnnotators.add(annotator); - if (annotator.isDefault()) { - defaultAnnotators.add(annotator); - } - } - - /** - * Performs all possible and automatic annotations on the model. - * - * @param model - * model to update - * @param progressUpdater - * callback function used for updating progress of the function - */ - public void performAnnotations(Model model, final IProgressUpdater progressUpdater) { - performAnnotations(model, progressUpdater, null, null); - } - - /** - * Performs all possible and automatic annotations on the model. - * - * @param annotators - * this map contains lists of {@link ElementAnnotator} objects that - * should be used for a given classes - * @param model - * model to update - * @param progressUpdater - * callback function used for updating progress of the function - */ - public void performAnnotations(Model model, final IProgressUpdater progressUpdater, Map<Class<?>, - List<ElementAnnotator>> annotators, Map<Class<?>, List<UserAnnotatorsParam>> annotatorsParams) { - progressUpdater.setProgress(0); - List<Model> models = new ArrayList<Model>(); - models.add(model); - models.addAll(model.getSubmodels()); - final double size = models.size(); - double counter = 0; - for (Model m : models) { - final double ratio = counter / size; - - copyAnnotationFromOtherSpecies(m, new IProgressUpdater() { - @Override - public void setProgress(final double progress) { - progressUpdater.setProgress(ratio * IProgressUpdater.MAX_PROGRESS + (progress * COPYING_RATIO) / size); - } - }); - annotateModel(m, new IProgressUpdater() { - - @Override - public void setProgress(double progress) { - progressUpdater - .setProgress(ratio * IProgressUpdater.MAX_PROGRESS + (COPYING_RATIO * IProgressUpdater.MAX_PROGRESS + progress * ANNOTATING_RATIO) / size); - } - }, annotators, annotatorsParams); - counter++; - } - } - - /** - * Due to some limitation of CellDesigner, some annotations are missing in xml - * file. Therefore there are two other places where we look for annotations: - * <ul> - * <li>notes,</li> - * <li>other elements with the same name and type.</li> - * </ul> - * - * This method copies data to elements without annotations from other elements - * with the same name and type. - * - * @param model - * model in which element annotations are updated - * @param progressUpdater - * callback function that updates the progress of function execution - */ - protected void copyAnnotationFromOtherSpecies(Model model, IProgressUpdater progressUpdater) { - double counter = 0; - double amount = model.getElements().size(); - for (Species element : model.getSpeciesList()) { - if (element.getMiriamData().size() == 0) { - List<Element> speciesList = model.getElementsByName(element.getName()); - for (Element species2 : speciesList) { - if (species2.getClass().equals(element.getClass()) && species2.getMiriamData().size() > 0 && element.getMiriamData().size() == 0) { - for (MiriamData md : species2.getMiriamData()) { - element.addMiriamData(new MiriamData(md)); - } - } - } - } - counter++; - progressUpdater.setProgress(counter / amount * IProgressUpdater.MAX_PROGRESS); - } - } - - /** - * Annotates all elements in the model using set of {@link ElementAnnotator} - * given in the param. If the set is empty then all annotators will be used. - * - * @param annotators - * this map contains lists of {@link ElementAnnotator} objects that - * should be used for a given classes - * @param model - * model where annotation shoud be updated - * @param progressUpdater - * callback function used to refresh progress of function execution - */ - protected void annotateModel(Model model, IProgressUpdater progressUpdater, Map<Class<?>, List<ElementAnnotator>> annotators) { - annotateModel(model, progressUpdater, annotators, null); - } - - /** - * Annotates all elements in the model using set of {@link ElementAnnotator} - * given in the param. If the set is empty then all annotators will be used. - * - * @param annotators - * this map contains lists of {@link ElementAnnotator} objects that - * should be used for a given classes - * @param annotatorsParams - * this map contains lists of {@link UserAnnotatorsParam} objects that - * should be used for a given {@link ElementAnnotator} class - * @param model - * model where annotation should be updated - * @param progressUpdater - * callback function used to refresh progress of function execution - */ - protected void annotateModel(Model model, IProgressUpdater progressUpdater, Map<Class<?>, List<ElementAnnotator>> annotators, - Map<Class<?>, List<UserAnnotatorsParam>> annotatorsParams) { - ElementUtils elementUtils = new ElementUtils(); - - progressUpdater.setProgress(0); - - double counter = 0; - double amount = model.getElements().size() + model.getReactions().size(); - - // annotate all elements - for (Element element : model.getElements()) { - List<ElementAnnotator> list = null; - if (annotators != null) { - list = annotators.get(element.getClass()); - } - if (list == null) { - list = getDefaultAnnotators(); - } - - for (ElementAnnotator elementAnnotator : list) { - try { - if (annotatorsParams != null){ - List<UserAnnotatorsParam> params = annotatorsParams.get(elementAnnotator.getClass()); - if (params != null) { - elementAnnotator.annotateElement(element, params); - } - } else { - elementAnnotator.annotateElement(element); - } - - } catch (AnnotatorException e) { - logger.warn(elementUtils.getElementTag(element) + " " + elementAnnotator.getCommonName() + " annotation problem: " + e.getMessage()); - } - } - counter++; - progressUpdater.setProgress(IProgressUpdater.MAX_PROGRESS * counter / amount); - } - - // annotate all reactions - for (BioEntity element : model.getReactions()) { - List<ElementAnnotator> list = null; - if (annotators != null) { - list = annotators.get(element.getClass()); - } - if (list == null) { - list = getDefaultAnnotators(); - } - - for (ElementAnnotator elementAnnotator : list) { - try { - elementAnnotator.annotateElement(element); - } catch (AnnotatorException e) { - logger.warn(elementUtils.getElementTag(element) + " " + elementAnnotator.getCommonName() + " annotation problem", e); - } - } - counter++; - progressUpdater.setProgress(IProgressUpdater.MAX_PROGRESS * counter / amount); - } - } - - /** - * Returns list of default annotators ({@link ElementAnnotator} with - * {@link ElementAnnotator#isDefault} flag). - * - * @return list of default annotators - */ - List<ElementAnnotator> getDefaultAnnotators() { - return defaultAnnotators; - } - - /** - * This method returns list of improper annotations for the model. Improper - * annotation is the annotation of the wrong type for given type of element. - * Types of proper annotations are defined in {@link MiriamType} enum. - * - * @param m - * model - * @param updater - * updater call back function that updat information about progress - * of the function - * @param validAnnotations - * map that contains information which {@link MiriamType miriam - * types} are valid for which class - * @return list of improper annotations - */ - public Collection<ImproperAnnotations> findImproperAnnotations(Model m, IProgressUpdater updater, - Map<Class<? extends BioEntity>, Set<MiriamType>> validAnnotations) { - if (validAnnotations == null) { - logger.warn("List of valid annotations is missing. Using default."); - validAnnotations = getDefaultValidClasses(); - } - updater.setProgress(0.0); - List<Model> models = new ArrayList<Model>(); - models.add(m); - models.addAll(m.getSubmodels()); - List<ImproperAnnotations> result = new ArrayList<>(); - - double modelSize = models.size(); - double modelCounter = 0; - for (Model model : models) { - double ratio = modelCounter / modelSize; - double size = model.getElements().size() + model.getReactions().size(); - double counter = 0; - for (Element element : model.getElements()) { - result.addAll(findImproperAnnotations(element, validAnnotations.get(element.getClass()))); - counter++; - updater.setProgress(ratio * IProgressUpdater.MAX_PROGRESS + (counter / size * IProgressUpdater.MAX_PROGRESS) / modelSize); - } - for (Reaction reaction : model.getReactions()) { - result.addAll(findImproperAnnotations(reaction, validAnnotations.get(reaction.getClass()))); - counter++; - updater.setProgress(ratio * IProgressUpdater.MAX_PROGRESS + (counter / size * IProgressUpdater.MAX_PROGRESS) / modelSize); - } - modelCounter++; - } - return result; - } - - /** - * This method returns list of improper annotations for the element. - * - * @param element - * where we look for improper annotations - * @param validClasses - * list of {@link MiriamType miriam types} that are valid for a given - * {@link BioEntity} - * @return list of improper annotations - */ - protected List<ImproperAnnotations> findImproperAnnotations(BioEntity element, Collection<MiriamType> validClasses) { - List<ImproperAnnotations> result = new ArrayList<>(); - for (MiriamData md : element.getMiriamData()) { - boolean valid = false; - if (validClasses.contains(md.getDataType())) { - valid = true; - } - if (valid && miriamConnector.getUrlString(md) == null) { - valid = false; - } - if (!valid) { - result.add(new ImproperAnnotations(element, md)); - } - } - return result; - } - - /** - * Returns list of all elements that miss annotation. - * - * @param m - * model where the search is performed - * @param requestedAnnotations - * map that contains information which {@link MiriamType miriam - * types} are obigatory for which class - * - * @return list of all elements that miss annotation - */ - public Collection<ProblematicAnnotation> findMissingAnnotations(Model m, Map<Class<? extends BioEntity>, Set<MiriamType>> requestedAnnotations) { - if (requestedAnnotations == null) { - logger.warn("List of requested annotations is missing. Using default."); - requestedAnnotations = getDefaultRequiredClasses(); - } - List<ProblematicAnnotation> result = new ArrayList<>(); - - List<Model> models = new ArrayList<>(); - models.add(m); - models.addAll(m.getSubmodels()); - for (Model model : models) { - for (Element alias : model.getElements()) { - result.addAll(findMissing(alias, requestedAnnotations.get(alias.getClass()))); - } - for (Reaction reaction : model.getReactions()) { - result.addAll(findMissing(reaction, requestedAnnotations.get(reaction.getClass()))); - } - } - return result; - } - - /** - * Checks if {@link BioEntity} is properly annotated and if not return info - * about missing annotation. - * - * @param element - * object to be checked - * @param requestedAnnotations - * at list one of this annotations should appear in the element, if - * the list is null then check is skipped, if the list is empty - * (size()==0) then method checks if element contains at least one - * miriam - * @return list of containing improper annotations about element - */ - private List<ProblematicAnnotation> findMissing(BioEntity element, Collection<MiriamType> requestedAnnotations) { - List<ProblematicAnnotation> result = new ArrayList<>(); - // if there are no requested annotations then don't check - if (requestedAnnotations == null) { - return result; - // if there are no requested annotations, but the list was mentioned then - // we check if at least one annotation exists - } else if (requestedAnnotations.size() == 0) { - if (element.getMiriamData().size() == 0) { - result.add(new MissingAnnotation(element)); - } - return result; - } - // check if at least one annotation match requested list - for (MiriamData md : element.getMiriamData()) { - for (MiriamType mt : requestedAnnotations) { - if (mt.equals(md.getDataType())) { - return result; - } - } - } - result.add(new MissingRequiredAnnotations(element, requestedAnnotations)); - return result; - } - - /** - * - * @return {@link #availableAnnotators} - */ - public List<ElementAnnotator> getAvailableAnnotators() { - return availableAnnotators; - } - - /** - * Returns list of available annotators for a given class type. - * - * @param clazz - * class type - * @return list of available annotators for a given class type - */ - public List<ElementAnnotator> getAvailableAnnotators(Class<?> clazz) { - List<ElementAnnotator> result = new ArrayList<ElementAnnotator>(); - for (ElementAnnotator annotator : availableAnnotators) { - if (annotator.isAnnotatable(clazz)) { - result.add(annotator); - } - } - return result; - } - - /** - * Returns list of {@link ElementAnnotator} names that are available for class - * given in the parameter. - * - * @param clazz - * class for which list of annotators will be returned - * @return annotators names for a given class - */ - public List<String> getAvailableAnnotatorNames(Class<?> clazz) { - List<String> result = new ArrayList<>(); - for (ElementAnnotator annotator : getAvailableAnnotators(clazz)) { - result.add(annotator.getCommonName()); - } - return result; - } - - /** - * Returns list of default {@link ElementAnnotator} names that are available - * for class given in the parameter. - * - * @param clazz - * class for which list of default annotators will be returned - * @return annotators names for a given class - */ - public List<String> getAvailableDefaultAnnotatorNames(Class<?> clazz) { - List<String> result = new ArrayList<>(); - for (ElementAnnotator annotator : getAvailableDefaultAnnotators(clazz)) { - result.add(annotator.getCommonName()); - } - return result; - } - - /** - * Returns list of default {@link ElementAnnotator annotators} that are - * available for class given in the parameter. - * - * @param clazz - * class for which list of default annotators will be returned - * @return annotators for a given class - */ - public List<ElementAnnotator> getAvailableDefaultAnnotators(Class<?> clazz) { - List<ElementAnnotator> result = new ArrayList<>(); - for (ElementAnnotator annotator : availableAnnotators) { - if (annotator.isAnnotatable(clazz) && annotator.isDefault()) { - result.add(annotator); - } - } - return result; - } - - /** - * Converts list of strings into list of {@link ElementAnnotator}. Strings - * must be valid {@link ElementAnnotator} common names. - * - * @param list - * list of {@link ElementAnnotator#getCommonName()}. - * @return list of {@link ElementAnnotator annotators} - */ - public List<ElementAnnotator> getAnnotatorsFromCommonNames(List<String> list) { - List<ElementAnnotator> result = new ArrayList<>(); - for (String string : list) { - boolean added = false; - for (ElementAnnotator annotator : availableAnnotators) { - if (annotator.getCommonName().equals(string)) { - added = true; - result.add(annotator); - } - } - if (!added) { - throw new InvalidArgumentException("Unknown annotator name: " + string); - } - } - return result; - } - - /** - * Returns map with informations about default valid {@link MiriamType miriam - * types } for {@link BioEntity} class type. - * - * @return map with informations about valid {@link MiriamType miriam types } - * for {@link BioEntity} class type - */ - @SuppressWarnings("unchecked") - public Map<Class<? extends BioEntity>, Set<MiriamType>> getDefaultValidClasses() { - Map<Class<? extends BioEntity>, Set<MiriamType>> result = new HashMap<Class<? extends BioEntity>, Set<MiriamType>>(); - ElementUtils eu = new ElementUtils(); - ClassTreeNode tree = eu.getAnnotatedElementClassTree(); - - Queue<ClassTreeNode> nodes = new LinkedList<ClassTreeNode>(); - nodes.add(tree); - while (!nodes.isEmpty()) { - ClassTreeNode node = nodes.poll(); - Set<MiriamType> set = new HashSet<MiriamType>(); - Class<? extends BioEntity> clazz = (Class<? extends BioEntity>) node.getClazz(); - for (MiriamType mt : MiriamType.values()) { - for (Class<?> clazz2 : mt.getValidClass()) { - if (clazz2.isAssignableFrom(clazz)) { - set.add(mt); - } - } - } - result.put(clazz, set); - for (ClassTreeNode child : node.getChildren()) { - nodes.add(child); - } - } - return result; - } - - /** - * Returns map with informations about default required {@link MiriamType - * miriam types } for {@link BioEntity} class type. - * - * @return map with informations about required {@link MiriamType miriam types - * } for {@link BioEntity} class type - */ - @SuppressWarnings("unchecked") - public Map<Class<? extends BioEntity>, Set<MiriamType>> getDefaultRequiredClasses() { - Map<Class<? extends BioEntity>, Set<MiriamType>> result = new HashMap<>(); - ElementUtils eu = new ElementUtils(); - ClassTreeNode tree = eu.getAnnotatedElementClassTree(); - - Queue<ClassTreeNode> nodes = new LinkedList<>(); - nodes.add(tree); - while (!nodes.isEmpty()) { - ClassTreeNode node = nodes.poll(); - Set<MiriamType> set = null; - Class<? extends BioEntity> clazz = (Class<? extends BioEntity>) node.getClazz(); - if ((Boolean) (node.getData())) { - set = new HashSet<>(); - for (MiriamType mt : MiriamType.values()) { - for (Class<?> clazz2 : mt.getRequiredClass()) { - if (clazz2.isAssignableFrom(clazz)) { - set.add(mt); - } - } - } - } - result.put(clazz, set); - for (ClassTreeNode child : node.getChildren()) { - nodes.add(child); - } - } - return result; - } + /** + * Time required for annotating in + * {@link #performAnnotations(Model, IProgressUpdater)} method. + */ + private static final double ANNOTATING_RATIO = 0.8; + /** + * Time required for copying annotations from other elements in + * {@link #performAnnotations(Model, IProgressUpdater)} method. + */ + private static final double COPYING_RATIO = 0.2; + + /** + * Connector used for accessing data from miriam registry. + */ + @Autowired + private MiriamConnector miriamConnector; + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(ModelAnnotator.class); + + /** + * BRENDA annotator. + */ + @Autowired + private BrendaAnnotator brendaAnnotator; + + /** + * Service accessing <a href= "http://biocompendium.embl.de/" >internal + * annotating service</a>. + */ + @Autowired + private BiocompendiumAnnotator biocompendiumAnnotator; + + /** + * CAZy annotator. + */ + @Autowired + private CazyAnnotator cazyAnnotator; + + /** + * Backend to the chebi database. + */ + @Autowired + private ChebiAnnotator chebiBackend; + + /** + * Uniprot annotator. + */ + @Autowired + private UniprotAnnotator uniprotAnnotator; + + /** + * PDB annotator. + */ + @Autowired + private PdbAnnotator pdbAnnotator; + + /** + * Recon annotator. + */ + @Autowired + private ReconAnnotator reconAnnotator; + + /** + * Service accessing <a href= "http://www.ebi.ac.uk/QuickGO/" >Gene + * Ontology</a>. + */ + @Autowired + private GoAnnotator goAnnotator; + + /** + * Service accessing <a href= "http://www.genenames.org/" >HUGO Gene + * Nomenclature Committee</a>. + */ + @Autowired + private HgncAnnotator hgncAnnotator; + + /** + * Service accessing <a href= "http://www.kegg.jp/" > KEGG EC Nomenclature</a>. + */ + @Autowired + private KeggAnnotator keggAnnotator; + + /** + * Service accessing <a href= "http://www.ncbi.nlm.nih.gov/gene/" >Entrez</a>. + */ + @Autowired + private EntrezAnnotator entrezAnnotator; + + /** + * Service accessing <a href= "http://ensembl.org">Ensembl</a>. + */ + @Autowired + private EnsemblAnnotator ensemblAnnotator; + + /** + * STITCH annotator. + */ + @Autowired + private StitchAnnotator stitchAnnotator; + + /** + * STRING annotator. + */ + @Autowired + private StringAnnotator stringAnnotator; + + /** + * TAIR annotator. + */ + @Autowired + private TairAnnotator tairAnnotator; + + /** + * List of all avaliable {@link ElementAnnotator} objects. + */ + private List<ElementAnnotator> availableAnnotators; + + /** + * List of all avaliable {@link ElementAnnotator} objects. + */ + private List<ElementAnnotator> defaultAnnotators; + + /** + * Post intintialization method. Will be called after spring creates beans and + * set the list of valid annotators. + */ + @PostConstruct + public final void init() { + availableAnnotators = new ArrayList<>(); + defaultAnnotators = new ArrayList<>(); + + addAnnotator(brendaAnnotator); + addAnnotator(biocompendiumAnnotator); + addAnnotator(cazyAnnotator); + addAnnotator(chebiBackend); + addAnnotator(uniprotAnnotator); + addAnnotator(goAnnotator); + addAnnotator(hgncAnnotator); + addAnnotator(keggAnnotator); + addAnnotator(pdbAnnotator); + addAnnotator(reconAnnotator); + addAnnotator(entrezAnnotator); + addAnnotator(ensemblAnnotator); + addAnnotator(stitchAnnotator); + addAnnotator(stringAnnotator); + addAnnotator(tairAnnotator); + } + + /** + * Adds annotator list of available annotators in {@link ModelAnnotator} class. + * + * @param annotator + * {@link ElementAnnotator} annotator o add + */ + private void addAnnotator(ElementAnnotator annotator) { + availableAnnotators.add(annotator); + if (annotator.isDefault()) { + defaultAnnotators.add(annotator); + } + } + + /** + * Performs all possible and automatic annotations on the model. + * + * @param model + * model to update + * @param progressUpdater + * callback function used for updating progress of the function + */ + public void performAnnotations(Model model, final IProgressUpdater progressUpdater) { + performAnnotations(model, progressUpdater, null, null); + } + + /** + * Performs all possible and automatic annotations on the model. + * + * @param annotators + * this map contains lists of {@link ElementAnnotator} objects that + * should be used for a given classes + * @param model + * model to update + * @param progressUpdater + * callback function used for updating progress of the function + */ + public void performAnnotations(Model model, final IProgressUpdater progressUpdater, + Map<Class<?>, List<ElementAnnotator>> annotators, Map<Class<?>, List<UserAnnotatorsParam>> annotatorsParams) { + progressUpdater.setProgress(0); + List<Model> models = new ArrayList<Model>(); + models.add(model); + models.addAll(model.getSubmodels()); + final double size = models.size(); + double counter = 0; + for (Model m : models) { + final double ratio = counter / size; + + copyAnnotationFromOtherSpecies(m, new IProgressUpdater() { + @Override + public void setProgress(final double progress) { + progressUpdater.setProgress(ratio * IProgressUpdater.MAX_PROGRESS + (progress * COPYING_RATIO) / size); + } + }); + annotateModel(m, new IProgressUpdater() { + + @Override + public void setProgress(double progress) { + progressUpdater.setProgress(ratio * IProgressUpdater.MAX_PROGRESS + + (COPYING_RATIO * IProgressUpdater.MAX_PROGRESS + progress * ANNOTATING_RATIO) / size); + } + }, annotators, annotatorsParams); + counter++; + } + } + + /** + * Due to some limitation of CellDesigner, some annotations are missing in xml + * file. Therefore there are two other places where we look for annotations: + * <ul> + * <li>notes,</li> + * <li>other elements with the same name and type.</li> + * </ul> + * + * This method copies data to elements without annotations from other elements + * with the same name and type. + * + * @param model + * model in which element annotations are updated + * @param progressUpdater + * callback function that updates the progress of function execution + */ + protected void copyAnnotationFromOtherSpecies(Model model, IProgressUpdater progressUpdater) { + double counter = 0; + double amount = model.getElements().size(); + for (Species element : model.getSpeciesList()) { + if (element.getMiriamData().size() == 0) { + List<Element> speciesList = model.getElementsByName(element.getName()); + for (Element species2 : speciesList) { + if (species2.getClass().equals(element.getClass()) && species2.getMiriamData().size() > 0 + && element.getMiriamData().size() == 0) { + for (MiriamData md : species2.getMiriamData()) { + element.addMiriamData(new MiriamData(md)); + } + } + } + } + counter++; + progressUpdater.setProgress(counter / amount * IProgressUpdater.MAX_PROGRESS); + } + } + + /** + * Annotates all elements in the model using set of {@link ElementAnnotator} + * given in the param. If the set is empty then all annotators will be used. + * + * @param annotators + * this map contains lists of {@link ElementAnnotator} objects that + * should be used for a given classes + * @param model + * model where annotation shoud be updated + * @param progressUpdater + * callback function used to refresh progress of function execution + */ + protected void annotateModel(Model model, IProgressUpdater progressUpdater, + Map<Class<?>, List<ElementAnnotator>> annotators) { + annotateModel(model, progressUpdater, annotators, null); + } + + /** + * Annotates all elements in the model using set of {@link ElementAnnotator} + * given in the param. If the set is empty then all annotators will be used. + * + * @param annotators + * this map contains lists of {@link ElementAnnotator} objects that + * should be used for a given classes + * @param annotatorsParams + * this map contains lists of {@link UserAnnotatorsParam} objects that + * should be used for a given {@link ElementAnnotator} class + * @param model + * model where annotation should be updated + * @param progressUpdater + * callback function used to refresh progress of function execution + */ + protected void annotateModel(Model model, IProgressUpdater progressUpdater, + Map<Class<?>, List<ElementAnnotator>> annotators, Map<Class<?>, List<UserAnnotatorsParam>> annotatorsParams) { + ElementUtils elementUtils = new ElementUtils(); + + progressUpdater.setProgress(0); + + double counter = 0; + double amount = model.getElements().size() + model.getReactions().size(); + + // annotate all elements + for (Element element : model.getElements()) { + List<ElementAnnotator> list = null; + if (annotators != null) { + list = annotators.get(element.getClass()); + } + if (list == null) { + list = getDefaultAnnotators(); + } + + for (ElementAnnotator elementAnnotator : list) { + try { + if (annotatorsParams != null) { + List<UserAnnotatorsParam> params = annotatorsParams.get(elementAnnotator.getClass()); + if (params != null) { + elementAnnotator.annotateElement(element, params); + } + } else { + elementAnnotator.annotateElement(element); + } + + } catch (AnnotatorException e) { + logger.warn(elementUtils.getElementTag(element) + " " + elementAnnotator.getCommonName() + + " annotation problem: " + e.getMessage()); + } + } + counter++; + progressUpdater.setProgress(IProgressUpdater.MAX_PROGRESS * counter / amount); + } + + // annotate all reactions + for (BioEntity element : model.getReactions()) { + List<ElementAnnotator> list = null; + if (annotators != null) { + list = annotators.get(element.getClass()); + } + if (list == null) { + list = getDefaultAnnotators(); + } + + for (ElementAnnotator elementAnnotator : list) { + try { + elementAnnotator.annotateElement(element); + } catch (AnnotatorException e) { + logger.warn( + elementUtils.getElementTag(element) + " " + elementAnnotator.getCommonName() + " annotation problem", e); + } + } + counter++; + progressUpdater.setProgress(IProgressUpdater.MAX_PROGRESS * counter / amount); + } + } + + /** + * Returns list of default annotators ({@link ElementAnnotator} with + * {@link ElementAnnotator#isDefault} flag). + * + * @return list of default annotators + */ + List<ElementAnnotator> getDefaultAnnotators() { + return defaultAnnotators; + } + + /** + * This method returns list of improper annotations for the model. Improper + * annotation is the annotation of the wrong type for given type of element. + * Types of proper annotations are defined in {@link MiriamType} enum. + * + * @param m + * model + * @param updater + * updater call back function that updat information about progress of + * the function + * @param validAnnotations + * map that contains information which {@link MiriamType miriam types} + * are valid for which class + * @return list of improper annotations + */ + public Collection<ImproperAnnotations> findImproperAnnotations(Model m, IProgressUpdater updater, + Map<Class<? extends BioEntity>, Set<MiriamType>> validAnnotations) { + if (validAnnotations == null) { + logger.warn("List of valid annotations is missing. Using default."); + validAnnotations = getDefaultValidClasses(); + } + updater.setProgress(0.0); + List<Model> models = new ArrayList<Model>(); + models.add(m); + models.addAll(m.getSubmodels()); + List<ImproperAnnotations> result = new ArrayList<>(); + + double modelSize = models.size(); + double modelCounter = 0; + for (Model model : models) { + double ratio = modelCounter / modelSize; + double size = model.getElements().size() + model.getReactions().size(); + double counter = 0; + for (Element element : model.getElements()) { + result.addAll(findImproperAnnotations(element, validAnnotations.get(element.getClass()))); + counter++; + updater.setProgress( + ratio * IProgressUpdater.MAX_PROGRESS + (counter / size * IProgressUpdater.MAX_PROGRESS) / modelSize); + } + for (Reaction reaction : model.getReactions()) { + result.addAll(findImproperAnnotations(reaction, validAnnotations.get(reaction.getClass()))); + counter++; + updater.setProgress( + ratio * IProgressUpdater.MAX_PROGRESS + (counter / size * IProgressUpdater.MAX_PROGRESS) / modelSize); + } + modelCounter++; + } + return result; + } + + /** + * This method returns list of improper annotations for the element. + * + * @param element + * where we look for improper annotations + * @param validClasses + * list of {@link MiriamType miriam types} that are valid for a given + * {@link BioEntity} + * @return list of improper annotations + */ + protected List<ImproperAnnotations> findImproperAnnotations(BioEntity element, Collection<MiriamType> validClasses) { + List<ImproperAnnotations> result = new ArrayList<>(); + for (MiriamData md : element.getMiriamData()) { + boolean valid = false; + if (validClasses.contains(md.getDataType())) { + valid = true; + } + if (valid && miriamConnector.getUrlString(md) == null) { + valid = false; + } + if (!valid) { + result.add(new ImproperAnnotations(element, md)); + } + } + return result; + } + + /** + * Returns list of all elements that miss annotation. + * + * @param m + * model where the search is performed + * @param requestedAnnotations + * map that contains information which {@link MiriamType miriam types} + * are obigatory for which class + * + * @return list of all elements that miss annotation + */ + public Collection<ProblematicAnnotation> findMissingAnnotations(Model m, + Map<Class<? extends BioEntity>, Set<MiriamType>> requestedAnnotations) { + if (requestedAnnotations == null) { + logger.warn("List of requested annotations is missing. Using default."); + requestedAnnotations = getDefaultRequiredClasses(); + } + List<ProblematicAnnotation> result = new ArrayList<>(); + + List<Model> models = new ArrayList<>(); + models.add(m); + models.addAll(m.getSubmodels()); + for (Model model : models) { + for (Element alias : model.getElements()) { + result.addAll(findMissing(alias, requestedAnnotations.get(alias.getClass()))); + } + for (Reaction reaction : model.getReactions()) { + result.addAll(findMissing(reaction, requestedAnnotations.get(reaction.getClass()))); + } + } + return result; + } + + /** + * Checks if {@link BioEntity} is properly annotated and if not return info + * about missing annotation. + * + * @param element + * object to be checked + * @param requestedAnnotations + * at list one of this annotations should appear in the element, if the + * list is null then check is skipped, if the list is empty (size()==0) + * then method checks if element contains at least one miriam + * @return list of containing improper annotations about element + */ + private List<ProblematicAnnotation> findMissing(BioEntity element, Collection<MiriamType> requestedAnnotations) { + List<ProblematicAnnotation> result = new ArrayList<>(); + // if there are no requested annotations then don't check + if (requestedAnnotations == null) { + return result; + // if there are no requested annotations, but the list was mentioned then + // we check if at least one annotation exists + } else if (requestedAnnotations.size() == 0) { + if (element.getMiriamData().size() == 0) { + result.add(new MissingAnnotation(element)); + } + return result; + } + // check if at least one annotation match requested list + for (MiriamData md : element.getMiriamData()) { + for (MiriamType mt : requestedAnnotations) { + if (mt.equals(md.getDataType())) { + return result; + } + } + } + result.add(new MissingRequiredAnnotations(element, requestedAnnotations)); + return result; + } + + /** + * + * @return {@link #availableAnnotators} + */ + public List<ElementAnnotator> getAvailableAnnotators() { + return availableAnnotators; + } + + /** + * Returns list of available annotators for a given class type. + * + * @param clazz + * class type + * @return list of available annotators for a given class type + */ + public List<ElementAnnotator> getAvailableAnnotators(Class<?> clazz) { + List<ElementAnnotator> result = new ArrayList<ElementAnnotator>(); + for (ElementAnnotator annotator : availableAnnotators) { + if (annotator.isAnnotatable(clazz)) { + result.add(annotator); + } + } + return result; + } + + /** + * Returns list of {@link ElementAnnotator} names that are available for class + * given in the parameter. + * + * @param clazz + * class for which list of annotators will be returned + * @return annotators names for a given class + */ + public List<String> getAvailableAnnotatorNames(Class<?> clazz) { + List<String> result = new ArrayList<>(); + for (ElementAnnotator annotator : getAvailableAnnotators(clazz)) { + result.add(annotator.getCommonName()); + } + return result; + } + + /** + * Returns list of default {@link ElementAnnotator} names that are available for + * class given in the parameter. + * + * @param clazz + * class for which list of default annotators will be returned + * @return annotators names for a given class + */ + public List<String> getAvailableDefaultAnnotatorNames(Class<?> clazz) { + List<String> result = new ArrayList<>(); + for (ElementAnnotator annotator : getAvailableDefaultAnnotators(clazz)) { + result.add(annotator.getCommonName()); + } + return result; + } + + /** + * Returns list of default {@link ElementAnnotator annotators} that are + * available for class given in the parameter. + * + * @param clazz + * class for which list of default annotators will be returned + * @return annotators for a given class + */ + public List<ElementAnnotator> getAvailableDefaultAnnotators(Class<?> clazz) { + List<ElementAnnotator> result = new ArrayList<>(); + for (ElementAnnotator annotator : availableAnnotators) { + if (annotator.isAnnotatable(clazz) && annotator.isDefault()) { + result.add(annotator); + } + } + return result; + } + + /** + * Converts list of strings into list of {@link ElementAnnotator}. Strings must + * be valid {@link ElementAnnotator} common names. + * + * @param list + * list of {@link ElementAnnotator#getCommonName()}. + * @return list of {@link ElementAnnotator annotators} + */ + public List<ElementAnnotator> getAnnotatorsFromCommonNames(List<String> list) { + List<ElementAnnotator> result = new ArrayList<>(); + for (String string : list) { + boolean added = false; + for (ElementAnnotator annotator : availableAnnotators) { + if (annotator.getCommonName().equals(string)) { + added = true; + result.add(annotator); + } + } + if (!added) { + throw new InvalidArgumentException("Unknown annotator name: " + string); + } + } + return result; + } + + /** + * Returns map with informations about default valid {@link MiriamType miriam + * types } for {@link BioEntity} class type. + * + * @return map with informations about valid {@link MiriamType miriam types } + * for {@link BioEntity} class type + */ + @SuppressWarnings("unchecked") + public Map<Class<? extends BioEntity>, Set<MiriamType>> getDefaultValidClasses() { + Map<Class<? extends BioEntity>, Set<MiriamType>> result = new HashMap<Class<? extends BioEntity>, Set<MiriamType>>(); + ElementUtils eu = new ElementUtils(); + ClassTreeNode tree = eu.getAnnotatedElementClassTree(); + + Queue<ClassTreeNode> nodes = new LinkedList<ClassTreeNode>(); + nodes.add(tree); + while (!nodes.isEmpty()) { + ClassTreeNode node = nodes.poll(); + Set<MiriamType> set = new HashSet<MiriamType>(); + Class<? extends BioEntity> clazz = (Class<? extends BioEntity>) node.getClazz(); + for (MiriamType mt : MiriamType.values()) { + for (Class<?> clazz2 : mt.getValidClass()) { + if (clazz2.isAssignableFrom(clazz)) { + set.add(mt); + } + } + } + result.put(clazz, set); + for (ClassTreeNode child : node.getChildren()) { + nodes.add(child); + } + } + return result; + } + + /** + * Returns map with informations about default required {@link MiriamType miriam + * types } for {@link BioEntity} class type. + * + * @return map with informations about required {@link MiriamType miriam types } + * for {@link BioEntity} class type + */ + @SuppressWarnings("unchecked") + public Map<Class<? extends BioEntity>, Set<MiriamType>> getDefaultRequiredClasses() { + Map<Class<? extends BioEntity>, Set<MiriamType>> result = new HashMap<>(); + ElementUtils eu = new ElementUtils(); + ClassTreeNode tree = eu.getAnnotatedElementClassTree(); + + Queue<ClassTreeNode> nodes = new LinkedList<>(); + nodes.add(tree); + while (!nodes.isEmpty()) { + ClassTreeNode node = nodes.poll(); + Set<MiriamType> set = null; + Class<? extends BioEntity> clazz = (Class<? extends BioEntity>) node.getClazz(); + if ((Boolean) (node.getData())) { + set = new HashSet<>(); + for (MiriamType mt : MiriamType.values()) { + for (Class<?> clazz2 : mt.getRequiredClass()) { + if (clazz2.isAssignableFrom(clazz)) { + set.add(mt); + } + } + } + } + result.put(clazz, set); + for (ClassTreeNode child : node.getChildren()) { + nodes.add(child); + } + } + return result; + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotator.java index a3df6fdc1a2a56dd9893eea4a9a1007562f77e3a..59969b9406507f8160e96e6b4ca0bd0a1a928075 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/BrendaAnnotator.java @@ -4,7 +4,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; @@ -31,145 +30,139 @@ import lcsb.mapviewer.model.map.species.Rna; */ public class BrendaAnnotator extends ElementAnnotator implements IExternalService { - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(BrendaAnnotator.class); - - /** - * Service used for annotation of entities using {@link MiriamType#TAIR_LOCUS - * TAIR}. - */ - @Autowired - private TairAnnotator tairAnnotator; - - /** - * Default constructor. - */ - public BrendaAnnotator() { - super(BrendaAnnotator.class, new Class[] { Protein.class, Gene.class, Rna.class }, false); - } - - @Override - public ExternalServiceStatus getServiceStatus() { - ExternalServiceStatus status = new ExternalServiceStatus(getCommonName(), getUrl()); - - GeneralCacheInterface cacheCopy = getCache(); - this.setCache(null); - - try { - Collection<MiriamData> mds = new UniprotAnnotator().uniProtToEC(createMiriamData(MiriamType.UNIPROT, "P12345")); - - status.setStatus(ExternalServiceStatusType.OK); - List<String> ecs = new ArrayList<>(); - if (mds != null) { - for (MiriamData md: mds) { - ecs.add(md.getResource()); - } - } - if (mds == null || mds.size() != 2 || ecs.indexOf("2.6.1.1") < 0 || ecs.indexOf("2.6.1.7") < 0) { - status.setStatus(ExternalServiceStatusType.CHANGED); - } - } catch (Exception e) { - logger.error(status.getName() + " is down", e); - status.setStatus(ExternalServiceStatusType.DOWN); - } - this.setCache(cacheCopy); - return status; - } - - @Override - public void annotateElement(BioEntity object) throws AnnotatorException { - if (isAnnotatable(object)) { - - MiriamData mdTair = null; - for (MiriamData md : object.getMiriamData()) { - if (md.getDataType().equals(MiriamType.BRENDA)) { - return; - } - else if (md.getDataType().equals(MiriamType.TAIR_LOCUS)) { - mdTair = md; - } - } - - if (mdTair != null) { - tairAnnotator.annotateElement(object); - } - - List<MiriamData> mdUniprots = new ArrayList<MiriamData>(); - for (MiriamData md : object.getMiriamData()) { - if (md.getDataType().equals(MiriamType.UNIPROT)) { - mdUniprots.add(md); - } - } - - UniprotAnnotator uniprotAnnotator = new UniprotAnnotator(); - - - List<String> ecIds = new ArrayList<String>(); - for (MiriamData mdUniprot: mdUniprots) { - try { - Collection<MiriamData> mdECs = uniprotAnnotator.uniProtToEC(mdUniprot); - if (mdECs != null) { - for (MiriamData mdEC: mdECs) { - mdEC.setAnnotator(BrendaAnnotator.class); - mdEC.setDataType(MiriamType.BRENDA); - if (ecIds.indexOf(mdEC.getResource()) == -1) { - ecIds.add(mdEC.getResource()); - object.addMiriamData(mdEC); - } - } - } - } catch (UniprotSearchException e) { - logger.warn("Cannot find EC data for UniProt id: " + mdUniprot.getResource()); - } - } - } - } - - - @Override - public Object refreshCacheQuery(Object query) throws SourceNotAvailable { - String name; - String result = null; - if (query instanceof String) { - name = (String) query; - if (name.startsWith("http")) { - try { - result = getWebPageContent(name); - } catch (IOException e) { - throw new SourceNotAvailable(e); - } - } else { - throw new InvalidArgumentException("Don't know what to do with query: " + query); - } - } else { - throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass()); - } - return result; - } - - - - - @Override - public String getCommonName() { - return MiriamType.BRENDA.getCommonName(); - } - - @Override - public String getUrl() { - return MiriamType.BRENDA.getDbHomepage(); - } - - @Override - protected WebPageDownloader getWebPageDownloader() { - return super.getWebPageDownloader(); - } - - @Override - protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { - super.setWebPageDownloader(webPageDownloader); - } + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(BrendaAnnotator.class); + + /** + * Service used for annotation of entities using {@link MiriamType#TAIR_LOCUS + * TAIR}. + */ + @Autowired + private TairAnnotator tairAnnotator; + + /** + * Default constructor. + */ + public BrendaAnnotator() { + super(BrendaAnnotator.class, new Class[] { Protein.class, Gene.class, Rna.class }, false); + } + + @Override + public ExternalServiceStatus getServiceStatus() { + ExternalServiceStatus status = new ExternalServiceStatus(getCommonName(), getUrl()); + + GeneralCacheInterface cacheCopy = getCache(); + this.setCache(null); + + try { + Collection<MiriamData> mds = new UniprotAnnotator().uniProtToEC(createMiriamData(MiriamType.UNIPROT, "P12345")); + + status.setStatus(ExternalServiceStatusType.OK); + List<String> ecs = new ArrayList<>(); + if (mds != null) { + for (MiriamData md : mds) { + ecs.add(md.getResource()); + } + } + if (mds == null || mds.size() != 2 || ecs.indexOf("2.6.1.1") < 0 || ecs.indexOf("2.6.1.7") < 0) { + status.setStatus(ExternalServiceStatusType.CHANGED); + } + } catch (Exception e) { + logger.error(status.getName() + " is down", e); + status.setStatus(ExternalServiceStatusType.DOWN); + } + this.setCache(cacheCopy); + return status; + } + + @Override + public void annotateElement(BioEntity object) throws AnnotatorException { + if (isAnnotatable(object)) { + + MiriamData mdTair = null; + for (MiriamData md : object.getMiriamData()) { + if (md.getDataType().equals(MiriamType.BRENDA)) { + return; + } else if (md.getDataType().equals(MiriamType.TAIR_LOCUS)) { + mdTair = md; + } + } + + if (mdTair != null) { + tairAnnotator.annotateElement(object); + } + + List<MiriamData> mdUniprots = new ArrayList<MiriamData>(); + for (MiriamData md : object.getMiriamData()) { + if (md.getDataType().equals(MiriamType.UNIPROT)) { + mdUniprots.add(md); + } + } + + UniprotAnnotator uniprotAnnotator = new UniprotAnnotator(); + + List<String> ecIds = new ArrayList<String>(); + for (MiriamData mdUniprot : mdUniprots) { + try { + Collection<MiriamData> mdECs = uniprotAnnotator.uniProtToEC(mdUniprot); + if (mdECs != null) { + for (MiriamData mdEC : mdECs) { + mdEC.setAnnotator(BrendaAnnotator.class); + mdEC.setDataType(MiriamType.BRENDA); + if (ecIds.indexOf(mdEC.getResource()) == -1) { + ecIds.add(mdEC.getResource()); + object.addMiriamData(mdEC); + } + } + } + } catch (UniprotSearchException e) { + logger.warn("Cannot find EC data for UniProt id: " + mdUniprot.getResource()); + } + } + } + } + + @Override + public Object refreshCacheQuery(Object query) throws SourceNotAvailable { + String name; + String result = null; + if (query instanceof String) { + name = (String) query; + if (name.startsWith("http")) { + try { + result = getWebPageContent(name); + } catch (IOException e) { + throw new SourceNotAvailable(e); + } + } else { + throw new InvalidArgumentException("Don't know what to do with query: " + query); + } + } else { + throw new InvalidArgumentException("Don't know what to do with class: " + query.getClass()); + } + return result; + } + + @Override + public String getCommonName() { + return MiriamType.BRENDA.getCommonName(); + } + + @Override + public String getUrl() { + return MiriamType.BRENDA.getDbHomepage(); + } + + @Override + protected WebPageDownloader getWebPageDownloader() { + return super.getWebPageDownloader(); + } + + @Override + protected void setWebPageDownloader(WebPageDownloader webPageDownloader) { + super.setWebPageDownloader(webPageDownloader); + } } diff --git a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java index b526374026678105928dd5fd72282935b7df8687..cc2af5f03a65e73a088b803350be2885206ba860 100644 --- a/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java +++ b/annotation/src/main/java/lcsb/mapviewer/annotation/services/annotators/ChebiAnnotator.java @@ -1,7 +1,5 @@ package lcsb.mapviewer.annotation.services.annotators; -import java.net.MalformedURLException; -import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; @@ -9,7 +7,6 @@ import java.util.List; import java.util.Queue; import java.util.Set; -import javax.xml.namespace.QName; import javax.xml.ws.WebServiceException; import org.apache.log4j.Logger; diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java index 27c802a421de0faf6bbec7666ddb761fa20ed4af..7107cb2661fdd8d47bd73055a369d8dc49c2f15e 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/MultipleAnnotatorsTest.java @@ -1,82 +1,66 @@ package lcsb.mapviewer.annotation.services.annotators; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import lcsb.mapviewer.annotation.AnnotationTestFunctions; -import lcsb.mapviewer.annotation.cache.WebPageDownloader; -import lcsb.mapviewer.annotation.services.ExternalServiceStatusType; -import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.species.GenericProtein; import lcsb.mapviewer.model.map.species.Species; public class MultipleAnnotatorsTest extends AnnotationTestFunctions { - - @Autowired - KeggAnnotator keggAnnotator; - - @Autowired - UniprotAnnotator uniprotAnnotator; - - @Autowired - HgncAnnotator hgncAnnotator; - - @Autowired - BiocompendiumAnnotator biocompendiumAnnotator; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testAnnotateUniprotByUniprotAndKegg() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); - - keggAnnotator.annotateElement(protein); - uniprotAnnotator.annotateElement(protein); - hgncAnnotator.annotateElement(protein); - //biocompendiumAnnotator.annotateElement(protein); - - - int cntNoAnnotator = 0; - for (MiriamData md: protein.getMiriamData()) { - if (md.getAnnotator() == null) { - cntNoAnnotator++; - } - } - - assertTrue("Wrong number of annotated elements with no information about annotator", cntNoAnnotator == 1); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + + @Autowired + KeggAnnotator keggAnnotator; + + @Autowired + UniprotAnnotator uniprotAnnotator; + + @Autowired + HgncAnnotator hgncAnnotator; + + @Autowired + BiocompendiumAnnotator biocompendiumAnnotator; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAnnotateUniprotByUniprotAndKegg() throws Exception { + try { + + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P12345")); + + keggAnnotator.annotateElement(protein); + uniprotAnnotator.annotateElement(protein); + hgncAnnotator.annotateElement(protein); + // biocompendiumAnnotator.annotateElement(protein); + + int cntNoAnnotator = 0; + for (MiriamData md : protein.getMiriamData()) { + if (md.getAnnotator() == null) { + cntNoAnnotator++; + } + } + + assertTrue("Wrong number of annotated elements with no information about annotator", cntNoAnnotator == 1); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } } diff --git a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java index 18172cd7d104adb1db9faf515d6674117f95d724..7a1f8552f7308809432bba5c30e29164ab7439f3 100644 --- a/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java +++ b/annotation/src/test/java/lcsb/mapviewer/annotation/services/annotators/UniprotAnnotatorTest.java @@ -9,7 +9,6 @@ import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; import java.io.IOException; -import java.util.ArrayList; import java.util.Collection; import org.junit.After; @@ -31,342 +30,344 @@ import lcsb.mapviewer.model.map.species.Species; public class UniprotAnnotatorTest extends AnnotationTestFunctions { - @Autowired - UniprotAnnotator uniprotAnnotator; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testAnnotate1() throws Exception { - try { - - Species protein = new GenericProtein("id"); - protein.setName("P12345"); - uniprotAnnotator.annotateElement(protein); - - assertTrue(protein.getMiriamData().size() > 0); - - boolean entrez = false; - boolean hgnc = false; - boolean uniprot = false; - boolean ec = false; - - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.UNIPROT)) { - uniprot = true; - } else if (md.getDataType().equals(MiriamType.HGNC_SYMBOL)) { - hgnc = true; - } else if (md.getDataType().equals(MiriamType.ENTREZ)) { - entrez = true; - } else if (md.getDataType().equals(MiriamType.EC)) { - ec = true; - } - } - assertTrue("No HGNC annotation extracted from uniprot annotator", hgnc); - assertTrue("No ENTREZ annotation extracted from uniprot annotator", entrez); - assertTrue("No UNIPROT annotation extracted from uniprot annotator", uniprot); - assertTrue("No UNIPROT annotation extracted from uniprot annotator", ec); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testEC1() throws Exception { - try { - - Collection<MiriamData> mds = uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.UNIPROT, "P12345")); - - assertEquals(mds.size(), 2); - MiriamData md1 = new MiriamData(MiriamType.EC, "2.6.1.1", UniprotAnnotator.class); - MiriamData md2 = new MiriamData(MiriamType.EC, "2.6.1.7", UniprotAnnotator.class); - for (MiriamData md: mds) { - assertTrue(md.compareTo(md1) == 0 || md.compareTo(md2) == 0); - } - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testEC2() throws Exception { - try { - - Collection<MiriamData> mds = uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.UNIPROT, "P25405")); - - assertTrue("No EC miriam data extracted from uniprot annotator", mds.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testInvalidUniprotToECNull() throws Exception { - try { - assertNull(uniprotAnnotator.uniProtToEC(null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidUniprotToECWrongMd() throws Exception { - try { - uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.WIKIPEDIA, "bla")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAnnotateInvalid2() throws Exception { - try { - Species protein = new GenericProtein("id"); - uniprotAnnotator.annotateElement(protein); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testInvalidUniprotToHgnc() throws Exception { - try { - assertNull(uniprotAnnotator.uniProtToHgnc(null)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testInvalidUniprotToHgnc2() throws Exception { - try { - uniprotAnnotator.uniProtToHgnc(new MiriamData(MiriamType.WIKIPEDIA, "bla")); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAnnotate2() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P01308")); - uniprotAnnotator.annotateElement(protein); - - assertTrue(protein.getMiriamData().size() > 1); - - boolean entrez = false; - boolean hgnc = false; - boolean uniprot = false; - - for (MiriamData md : protein.getMiriamData()) { - if (md.getDataType().equals(MiriamType.UNIPROT)) { - uniprot = true; - } else if (md.getDataType().equals(MiriamType.HGNC_SYMBOL)) { - hgnc = true; - } else if (md.getDataType().equals(MiriamType.ENTREZ)) { - entrez = true; - } - } - assertTrue("No HGNC annotation extracted from uniprot annotator", hgnc); - assertTrue("No ENTREZ annotation extracted from uniprot annotator", entrez); - assertTrue("No UNIPROT annotation extracted from uniprot annotator", uniprot); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testAnnotateInvalidUniprot() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "bla")); - uniprotAnnotator.annotateElement(protein); - - assertEquals(1, protein.getMiriamData().size()); - - assertEquals(1, getWarnings().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testAnnotateInvalid() throws Exception { - try { - Species protein = new GenericProtein("id"); - protein.setName("bla"); - uniprotAnnotator.annotateElement(protein); - - assertEquals(0, protein.getMiriamData().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testUniprotToHgnc() throws Exception { - try { - assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "KDR", UniprotAnnotator.class), uniprotAnnotator.uniProtToHgnc(new MiriamData(MiriamType.UNIPROT, "P35968"))); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidCacheQuery() throws Exception { - try { - uniprotAnnotator.refreshCacheQuery("invalid_query"); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshInvalidCacheQuery2() throws Exception { - try { - uniprotAnnotator.refreshCacheQuery(new Object()); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - assertTrue(e.getMessage().contains("Don't know what to do")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRefreshCacheQuery() throws Exception { - try { - Object res = uniprotAnnotator.refreshCacheQuery("http://google.pl/"); - assertNotNull(res); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testStatus() throws Exception { - try { - assertEquals(ExternalServiceStatusType.OK, uniprotAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSimulateDownStatus() throws Exception { - WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenThrow(new IOException()); - uniprotAnnotator.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.DOWN, uniprotAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - uniprotAnnotator.setWebPageDownloader(downloader); - } - } - - @Test - public void testAnnotateWithUniprotServerError() throws Exception { - WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); - GeneralCacheInterface cache = uniprotAnnotator.getCache(); - uniprotAnnotator.setCache(new GeneralCacheWithExclusion(cache, 1)); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenThrow(new IOException()); - uniprotAnnotator.setWebPageDownloader(mockDownloader); - Species protein = new GenericProtein("id"); - protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P01308")); - uniprotAnnotator.annotateElement(protein); - fail("Exception expected"); - } catch (AnnotatorException e) { - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - uniprotAnnotator.setCache(cache); - uniprotAnnotator.setWebPageDownloader(downloader); - } - } - - @Test - public void testSimulateDownStatus2() throws Exception { - WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenReturn(""); - uniprotAnnotator.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.DOWN, uniprotAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - uniprotAnnotator.setWebPageDownloader(downloader); - } - } - - @Test - public void testSimulateChangedStatus() throws Exception { - WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); - try { - WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); - when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenReturn("GN Name=ACSS2; Synonyms=ACAS2;"); - uniprotAnnotator.setWebPageDownloader(mockDownloader); - assertEquals(ExternalServiceStatusType.CHANGED, uniprotAnnotator.getServiceStatus().getStatus()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - uniprotAnnotator.setWebPageDownloader(downloader); - } - } + @Autowired + UniprotAnnotator uniprotAnnotator; + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testAnnotate1() throws Exception { + try { + + Species protein = new GenericProtein("id"); + protein.setName("P12345"); + uniprotAnnotator.annotateElement(protein); + + assertTrue(protein.getMiriamData().size() > 0); + + boolean entrez = false; + boolean hgnc = false; + boolean uniprot = false; + boolean ec = false; + + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.UNIPROT)) { + uniprot = true; + } else if (md.getDataType().equals(MiriamType.HGNC_SYMBOL)) { + hgnc = true; + } else if (md.getDataType().equals(MiriamType.ENTREZ)) { + entrez = true; + } else if (md.getDataType().equals(MiriamType.EC)) { + ec = true; + } + } + assertTrue("No HGNC annotation extracted from uniprot annotator", hgnc); + assertTrue("No ENTREZ annotation extracted from uniprot annotator", entrez); + assertTrue("No UNIPROT annotation extracted from uniprot annotator", uniprot); + assertTrue("No UNIPROT annotation extracted from uniprot annotator", ec); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testEC1() throws Exception { + try { + + Collection<MiriamData> mds = uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.UNIPROT, "P12345")); + + assertEquals(mds.size(), 2); + MiriamData md1 = new MiriamData(MiriamType.EC, "2.6.1.1", UniprotAnnotator.class); + MiriamData md2 = new MiriamData(MiriamType.EC, "2.6.1.7", UniprotAnnotator.class); + for (MiriamData md : mds) { + assertTrue(md.compareTo(md1) == 0 || md.compareTo(md2) == 0); + } + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testEC2() throws Exception { + try { + + Collection<MiriamData> mds = uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.UNIPROT, "P25405")); + + assertTrue("No EC miriam data extracted from uniprot annotator", mds.size() > 0); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testInvalidUniprotToECNull() throws Exception { + try { + assertNull(uniprotAnnotator.uniProtToEC(null)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testInvalidUniprotToECWrongMd() throws Exception { + try { + uniprotAnnotator.uniProtToEC(new MiriamData(MiriamType.WIKIPEDIA, "bla")); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAnnotateInvalid2() throws Exception { + try { + Species protein = new GenericProtein("id"); + uniprotAnnotator.annotateElement(protein); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testInvalidUniprotToHgnc() throws Exception { + try { + assertNull(uniprotAnnotator.uniProtToHgnc(null)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testInvalidUniprotToHgnc2() throws Exception { + try { + uniprotAnnotator.uniProtToHgnc(new MiriamData(MiriamType.WIKIPEDIA, "bla")); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testAnnotate2() throws Exception { + try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P01308")); + uniprotAnnotator.annotateElement(protein); + + assertTrue(protein.getMiriamData().size() > 1); + + boolean entrez = false; + boolean hgnc = false; + boolean uniprot = false; + + for (MiriamData md : protein.getMiriamData()) { + if (md.getDataType().equals(MiriamType.UNIPROT)) { + uniprot = true; + } else if (md.getDataType().equals(MiriamType.HGNC_SYMBOL)) { + hgnc = true; + } else if (md.getDataType().equals(MiriamType.ENTREZ)) { + entrez = true; + } + } + assertTrue("No HGNC annotation extracted from uniprot annotator", hgnc); + assertTrue("No ENTREZ annotation extracted from uniprot annotator", entrez); + assertTrue("No UNIPROT annotation extracted from uniprot annotator", uniprot); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testAnnotateInvalidUniprot() throws Exception { + try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "bla")); + uniprotAnnotator.annotateElement(protein); + + assertEquals(1, protein.getMiriamData().size()); + + assertEquals(1, getWarnings().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testAnnotateInvalid() throws Exception { + try { + Species protein = new GenericProtein("id"); + protein.setName("bla"); + uniprotAnnotator.annotateElement(protein); + + assertEquals(0, protein.getMiriamData().size()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + + } + + @Test + public void testUniprotToHgnc() throws Exception { + try { + assertEquals(new MiriamData(MiriamType.HGNC_SYMBOL, "KDR", UniprotAnnotator.class), + uniprotAnnotator.uniProtToHgnc(new MiriamData(MiriamType.UNIPROT, "P35968"))); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidCacheQuery() throws Exception { + try { + uniprotAnnotator.refreshCacheQuery("invalid_query"); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshInvalidCacheQuery2() throws Exception { + try { + uniprotAnnotator.refreshCacheQuery(new Object()); + fail("Exception expected"); + } catch (InvalidArgumentException e) { + assertTrue(e.getMessage().contains("Don't know what to do")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRefreshCacheQuery() throws Exception { + try { + Object res = uniprotAnnotator.refreshCacheQuery("http://google.pl/"); + assertNotNull(res); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testStatus() throws Exception { + try { + assertEquals(ExternalServiceStatusType.OK, uniprotAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testSimulateDownStatus() throws Exception { + WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenThrow(new IOException()); + uniprotAnnotator.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.DOWN, uniprotAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + uniprotAnnotator.setWebPageDownloader(downloader); + } + } + + @Test + public void testAnnotateWithUniprotServerError() throws Exception { + WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); + GeneralCacheInterface cache = uniprotAnnotator.getCache(); + uniprotAnnotator.setCache(new GeneralCacheWithExclusion(cache, 1)); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenThrow(new IOException()); + uniprotAnnotator.setWebPageDownloader(mockDownloader); + Species protein = new GenericProtein("id"); + protein.addMiriamData(new MiriamData(MiriamType.UNIPROT, "P01308")); + uniprotAnnotator.annotateElement(protein); + fail("Exception expected"); + } catch (AnnotatorException e) { + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + uniprotAnnotator.setCache(cache); + uniprotAnnotator.setWebPageDownloader(downloader); + } + } + + @Test + public void testSimulateDownStatus2() throws Exception { + WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())).thenReturn(""); + uniprotAnnotator.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.DOWN, uniprotAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + uniprotAnnotator.setWebPageDownloader(downloader); + } + } + + @Test + public void testSimulateChangedStatus() throws Exception { + WebPageDownloader downloader = uniprotAnnotator.getWebPageDownloader(); + try { + WebPageDownloader mockDownloader = Mockito.mock(WebPageDownloader.class); + when(mockDownloader.getFromNetwork(anyString(), anyString(), anyString())) + .thenReturn("GN Name=ACSS2; Synonyms=ACAS2;"); + uniprotAnnotator.setWebPageDownloader(mockDownloader); + assertEquals(ExternalServiceStatusType.CHANGED, uniprotAnnotator.getServiceStatus().getStatus()); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } finally { + uniprotAnnotator.setWebPageDownloader(downloader); + } + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/Comparator.java b/commons/src/main/java/lcsb/mapviewer/common/Comparator.java index 6030a1a6f1d798306cccaf5a19e4336926972383..92102ccf029363a97198e3e0cda7bb9b01141917 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/Comparator.java +++ b/commons/src/main/java/lcsb/mapviewer/common/Comparator.java @@ -1,9 +1,7 @@ package lcsb.mapviewer.common; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; import org.apache.log4j.Logger; diff --git a/commons/src/main/java/lcsb/mapviewer/common/Configuration.java b/commons/src/main/java/lcsb/mapviewer/common/Configuration.java index 8afe7171c40f77edb086d39c1258edee4c7be199..e8fb36c07b1f78c338d1c670e62a6df650d42845 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/Configuration.java +++ b/commons/src/main/java/lcsb/mapviewer/common/Configuration.java @@ -17,411 +17,410 @@ import org.apache.log4j.Logger; */ public final class Configuration { - /** - * Default value for {@link #memorySaturationRatioTriggerClean}. It defines at - * what memory usage level application should release cached objects (to - * prevent unnecessary out of memory execptions). - * - */ - private static final double DEFAULT_MEMORY_SATURATION_TRIGGER_CLEAN = 0.9; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(Configuration.class); - - /** - * How many elements should be visible in autocomplete lists. - */ - private static final int DEFAULT_AUTOCOMPLETE_SIZE = 5; - - /** - * What is the minimal zoom level in the Google Maps API. It cannot be set to - * 0 because Google Maps API was designed to visualize map of Earth which is - * based on torus. Therefore, if we use too small zoom level we will see next - * to the right edge elements from the left part. When we increase minimal - * zoom level there will be a gap (huge enough) between the overlapping parts - * and user will be unaware of that fact. - */ - public static final int MIN_ZOOM_LEVEL = 2; - - /** - * This constant describes minimum size (in square pixels) of object visible - * during nesting (it is a soft limit, can be override by depth of the - * depending tree). - */ - public static final double MIN_VISIBLE_OBJECT_SIZE = 55000; - - /** - * This constant describes maximum size (in square pixels) of object visible - * during nesting. - */ - public static final double MAX_VISIBLE_OBJECT_SIZE = 80000; - - /** - * Address where Parkinson's Disease map is available in the Internet. - */ - public static final String PUBLICALY_AVAILABLE_PD_MAP = "http://pdmap.uni.lu/MapViewer/?id=pdmap"; - - /** - * Where the main webpgae is located. - */ - public static final String MAIN_PAGE = "/index.xhtml"; - - /** - * Name of the cookie for authentication token. - */ - public static final String AUTH_TOKEN = "MINERVA_AUTH_TOKEN"; - - /** - * Where miriam redirecting webpage is located. - */ - public static final String MIRIAM_PAGE = "miriam.xhtml"; - - /** - * Where the login webpage is located. - */ - public static final String LOGIN_PAGE = "/login.xhtml"; - - /** - * Spring url for login. - */ - public static final String SPRING_SECURITY_ACTION = "/login"; - - /** - * Spring url for logout. - */ - public static final String SPRING_SECURITY_LOGOUT = "/j_spring_security_logout"; - - /** - * Guest account. - */ - public static final String ANONYMOUS_LOGIN = "anonymous"; - - /** - * Should the application cache be turned on. - */ - private static boolean applicationCacheOn = true; - - /** - * Should the database cache be turned on. - */ - private static boolean dbCacheOn = true; - - /** - * This const defines at what memory usage level application should release - * cached objects (to prevent unnecessary out of memory execptions). - */ - private static Double memorySaturationRatioTriggerClean = DEFAULT_MEMORY_SATURATION_TRIGGER_CLEAN; - - /** - * What is the size of autocomplete elements. - */ - private static int autocompleteSize = DEFAULT_AUTOCOMPLETE_SIZE; - - /** - * Epsilon used for different types of comparisons. - */ - public static final double EPSILON = 1e-6; - - /** - * Git version from which framework was built. - */ - private static String systemBuildVersion = null; - - /** - * Date when the framework was built. - */ - private static String systemBuildTime = null; - - /** - * Version of the system (used by debian package). - */ - private static String systemVersion = null; - - /** - * Address that should be allowed to use x-frame. - */ - private static String xFrametDomain = null; - - /** - * Directory where tomcat webapp folder is located. Default value is "." - * because it should be set to proper value when tomcat application is - * deployed and run. - */ - private static String webAppDir = "./"; - - /** - * Default constructor which prevents instatiation. - */ - private Configuration() { - - } - - /** - * @return the applicationCacheOn - */ - public static boolean isApplicationCacheOn() { - return applicationCacheOn; - } - - /** - * @param applicationCacheOn - * the applicationCacheOn to set - */ - public static void setApplicationCacheOn(boolean applicationCacheOn) { - Configuration.applicationCacheOn = applicationCacheOn; - } - - /** - * @return the dbCacheOn - */ - public static boolean isDbCacheOn() { - return dbCacheOn; - } - - /** - * @param dbCacheOn - * the dbCacheOn to set - */ - public static void setDbCacheOn(boolean dbCacheOn) { - Configuration.dbCacheOn = dbCacheOn; - } - - /** - * @return the autocompleteSize - */ - public static int getAutocompleteSize() { - return autocompleteSize; - } - - /** - * @param autocompleteSize - * the autocompleteSize to set - */ - public static void setAutocompleteSize(int autocompleteSize) { - Configuration.autocompleteSize = autocompleteSize; - } - - /** - * @param baseDir - * directory where the system is placed - * @return {@link #systemBuildVersion} - */ - public static String getSystemBuildVersion(String baseDir) { - if (systemBuildVersion == null) { - loadSystemVersion(baseDir); - } - return systemBuildVersion; - } - - /** - * @param baseDir - * directory where the system is placed - * @return {@link #systemVersion} - */ - public static String getSystemVersion(String baseDir) { - if (systemVersion == null) { - loadSystemVersion(baseDir); - } - return systemVersion; - } - - /** - * @param baseDir - * directory where the system is placed - * @param forceReload - * if true then forces to reload data from text file - * @return {@link #systemBuildVersion} - */ - public static String getSystemBuildVersion(String baseDir, boolean forceReload) { - if (forceReload) { - systemBuildVersion = null; - } - return getSystemBuildVersion(baseDir); - } - - /** - * @param baseDir - * directory where the system is placed - * @param forceReload - * if true then forces to reload data from text file - * @return {@link #systemBuildVersion} - */ - public static String getSystemVersion(String baseDir, boolean forceReload) { - if (forceReload) { - systemVersion = null; - } - return getSystemVersion(baseDir); - } - - /** - * Loads system version (git version, build date) from the file. - * - * @param baseDir - * directory where the system is placed - */ - protected static void loadSystemVersion(String baseDir) { - systemBuildVersion = "Unknown"; - systemBuildTime = "Unknown"; - systemVersion = "Unknown"; - File buildVersionFile = null; - File changelogFile = null; - if (baseDir == null) { - buildVersionFile = new File("version.txt"); - changelogFile = new File("CHANGELOG"); - } else { - buildVersionFile = new File(baseDir + "version.txt"); - changelogFile = new File(baseDir + "CHANGELOG"); - } - if (buildVersionFile.exists()) { - loadSystemBuildVersion(buildVersionFile); - } else { - logger.error(buildVersionFile.getAbsoluteFile() + " doesn't exist."); - } - - if (changelogFile.exists()) { - loadSystemVersion(changelogFile); - } else { - logger.error(changelogFile.getAbsoluteFile() + " doesn't exist."); - } - } - - /** - * Loads system version (git version, build date) from the file. - * - * @param file - * file from which data is loaded - */ - protected static void loadSystemBuildVersion(File file) { - try { - BufferedReader reader = new BufferedReader(new FileReader(file)); - systemBuildVersion = reader.readLine(); - systemBuildTime = reader.readLine(); - reader.close(); - } catch (IOException e) { - logger.error(e); - } - } - - /** - * Loads system version from debian changelog file. - * - * @param file - * debian changelog file - */ - protected static void loadSystemVersion(File file) { - try { - BufferedReader reader = new BufferedReader(new FileReader(file)); - String line = reader.readLine(); - - int startIndex = line.indexOf("("); - int endIndex = line.indexOf(")"); - - if (startIndex >= 0 && endIndex >= 0) { - systemVersion = line.substring(startIndex + 1, endIndex); - } else { - logger.error("Invalid CHANGELOG file. Cannot find system version in line: " + line); - } - reader.close(); - } catch (IOException e) { - logger.error(e); - } - } - - /** - * @param baseDir - * directory where the system is placed - * @return the systemBuild - * @see #systemBuildTime - */ - public static String getSystemBuild(String baseDir) { - if (systemBuildTime == null) { - loadSystemVersion(baseDir); - } - return systemBuildTime; - } - - /** - * @param baseDir - * directory where the system is placed - * @param forceReload - * if true then forces to reload data from text file - * @return the systemBuild - * @see #systemBuildTime - */ - public static String getSystemBuild(String baseDir, boolean forceReload) { - if (forceReload) { - systemBuildTime = null; - } - return getSystemBuild(baseDir); - } - - /** - * @return the xFrametDomain - * @see #xFrametDomain - */ - public static String getxFrameDomain() { - return xFrametDomain; - } - - /** - * @param xFrametDomain - * the xFrametDomain to set - * @see #xFrametDomain - */ - public static void setxFrameDomain(String xFrametDomain) { - Configuration.xFrametDomain = xFrametDomain; - } - - /** - * @param path - * the path to webapp to set - * @see #webAppDir - */ - public static void setWebAppDir(String path) { - Configuration.webAppDir = path; - } - - /** - * @return the {@link #webAppDir} - */ - public static String getWebAppDir() { - return Configuration.webAppDir; - } - - /** - * @return the memorySaturationRatioTriggerClean - * @see #memorySaturationRatioTriggerClean - */ - public static Double getMemorySaturationRatioTriggerClean() { - return memorySaturationRatioTriggerClean; - } - - /** - * @param memorySaturationRatioTriggerClean - * the memorySaturationRatioTriggerClean to set - * @see #memorySaturationRatioTriggerClean - */ - public static void setMemorySaturationRatioTriggerClean(Double memorySaturationRatioTriggerClean) { - Configuration.memorySaturationRatioTriggerClean = memorySaturationRatioTriggerClean; - } - - /** - * Returns information about version of the framework. - * - * @param baseDir - * directory where project was deployed (or information about version - * is stored) - * @return information about version of the framework - */ - public static FrameworkVersion getFrameworkVersion(String baseDir) { - FrameworkVersion result = new FrameworkVersion(); - loadSystemVersion(baseDir); - result.setGitVersion(getSystemBuildVersion(baseDir)); - result.setTime(getSystemBuild(baseDir)); - result.setVersion(getSystemVersion(baseDir)); - return result; - } + /** + * Default value for {@link #memorySaturationRatioTriggerClean}. It defines at + * what memory usage level application should release cached objects (to prevent + * unnecessary out of memory exceptions). + * + */ + private static final double DEFAULT_MEMORY_SATURATION_TRIGGER_CLEAN = 0.9; + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(Configuration.class); + + /** + * How many elements should be visible in auto-complete lists. + */ + private static final int DEFAULT_AUTOCOMPLETE_SIZE = 5; + + /** + * What is the minimal zoom level in the Google Maps API. It cannot be set to 0 + * because Google Maps API was designed to visualize map of Earth which is based + * on torus. Therefore, if we use too small zoom level we will see next to the + * right edge elements from the left part. When we increase minimal zoom level + * there will be a gap (huge enough) between the overlapping parts and user will + * be unaware of that fact. + */ + public static final int MIN_ZOOM_LEVEL = 2; + + /** + * This constant describes minimum size (in square pixels) of object visible + * during nesting (it is a soft limit, can be override by depth of the depending + * tree). + */ + public static final double MIN_VISIBLE_OBJECT_SIZE = 55000; + + /** + * This constant describes maximum size (in square pixels) of object visible + * during nesting. + */ + public static final double MAX_VISIBLE_OBJECT_SIZE = 80000; + + /** + * Address where Parkinson's Disease map is available in the Internet. + */ + public static final String PUBLICALY_AVAILABLE_PD_MAP = "http://pdmap.uni.lu/MapViewer/?id=pdmap"; + + /** + * Where the main web page is located. + */ + public static final String MAIN_PAGE = "/index.xhtml"; + + /** + * Name of the cookie for authentication token. + */ + public static final String AUTH_TOKEN = "MINERVA_AUTH_TOKEN"; + + /** + * Where miriam redirecting web page is located. + */ + public static final String MIRIAM_PAGE = "miriam.xhtml"; + + /** + * Where the login web page is located. + */ + public static final String LOGIN_PAGE = "/login.xhtml"; + + /** + * Spring url for login. + */ + public static final String SPRING_SECURITY_ACTION = "/login"; + + /** + * Spring url for logout. + */ + public static final String SPRING_SECURITY_LOGOUT = "/j_spring_security_logout"; + + /** + * Guest account. + */ + public static final String ANONYMOUS_LOGIN = "anonymous"; + + /** + * Should the application cache be turned on. + */ + private static boolean applicationCacheOn = true; + + /** + * Should the database cache be turned on. + */ + private static boolean dbCacheOn = true; + + /** + * This constant defines at what memory usage level application should release + * cached objects (to prevent unnecessary out of memory exceptions). + */ + private static Double memorySaturationRatioTriggerClean = DEFAULT_MEMORY_SATURATION_TRIGGER_CLEAN; + + /** + * What is the size of auto-complete elements. + */ + private static int autocompleteSize = DEFAULT_AUTOCOMPLETE_SIZE; + + /** + * Epsilon used for different types of comparisons. + */ + public static final double EPSILON = 1e-6; + + /** + * Git version from which framework was built. + */ + private static String systemBuildVersion = null; + + /** + * Date when the framework was built. + */ + private static String systemBuildTime = null; + + /** + * Version of the system (used by debian package). + */ + private static String systemVersion = null; + + /** + * Address that should be allowed to use x-frame. + */ + private static String xFrametDomain = null; + + /** + * Directory where tomcat webapp folder is located. Default value is "." because + * it should be set to proper value when tomcat application is deployed and run. + */ + private static String webAppDir = "./"; + + /** + * Default constructor which prevents instantiation. + */ + private Configuration() { + + } + + /** + * @return the applicationCacheOn + */ + public static boolean isApplicationCacheOn() { + return applicationCacheOn; + } + + /** + * @param applicationCacheOn + * the applicationCacheOn to set + */ + public static void setApplicationCacheOn(boolean applicationCacheOn) { + Configuration.applicationCacheOn = applicationCacheOn; + } + + /** + * @return the dbCacheOn + */ + public static boolean isDbCacheOn() { + return dbCacheOn; + } + + /** + * @param dbCacheOn + * the dbCacheOn to set + */ + public static void setDbCacheOn(boolean dbCacheOn) { + Configuration.dbCacheOn = dbCacheOn; + } + + /** + * @return the autocompleteSize + */ + public static int getAutocompleteSize() { + return autocompleteSize; + } + + /** + * @param autocompleteSize + * the autocompleteSize to set + */ + public static void setAutocompleteSize(int autocompleteSize) { + Configuration.autocompleteSize = autocompleteSize; + } + + /** + * @param baseDir + * directory where the system is placed + * @return {@link #systemBuildVersion} + */ + public static String getSystemBuildVersion(String baseDir) { + if (systemBuildVersion == null) { + loadSystemVersion(baseDir); + } + return systemBuildVersion; + } + + /** + * @param baseDir + * directory where the system is placed + * @return {@link #systemVersion} + */ + public static String getSystemVersion(String baseDir) { + if (systemVersion == null) { + loadSystemVersion(baseDir); + } + return systemVersion; + } + + /** + * @param baseDir + * directory where the system is placed + * @param forceReload + * if true then forces to reload data from text file + * @return {@link #systemBuildVersion} + */ + public static String getSystemBuildVersion(String baseDir, boolean forceReload) { + if (forceReload) { + systemBuildVersion = null; + } + return getSystemBuildVersion(baseDir); + } + + /** + * @param baseDir + * directory where the system is placed + * @param forceReload + * if true then forces to reload data from text file + * @return {@link #systemBuildVersion} + */ + public static String getSystemVersion(String baseDir, boolean forceReload) { + if (forceReload) { + systemVersion = null; + } + return getSystemVersion(baseDir); + } + + /** + * Loads system version (git version, build date) from the file. + * + * @param baseDir + * directory where the system is placed + */ + protected static void loadSystemVersion(String baseDir) { + systemBuildVersion = "Unknown"; + systemBuildTime = "Unknown"; + systemVersion = "Unknown"; + File buildVersionFile = null; + File changelogFile = null; + if (baseDir == null) { + buildVersionFile = new File("version.txt"); + changelogFile = new File("CHANGELOG"); + } else { + buildVersionFile = new File(baseDir + "version.txt"); + changelogFile = new File(baseDir + "CHANGELOG"); + } + if (buildVersionFile.exists()) { + loadSystemBuildVersion(buildVersionFile); + } else { + logger.error(buildVersionFile.getAbsoluteFile() + " doesn't exist."); + } + + if (changelogFile.exists()) { + loadSystemVersion(changelogFile); + } else { + logger.error(changelogFile.getAbsoluteFile() + " doesn't exist."); + } + } + + /** + * Loads system version (git version, build date) from the file. + * + * @param file + * file from which data is loaded + */ + protected static void loadSystemBuildVersion(File file) { + try { + BufferedReader reader = new BufferedReader(new FileReader(file)); + systemBuildVersion = reader.readLine().trim(); + systemBuildTime = reader.readLine().trim(); + reader.close(); + } catch (IOException e) { + logger.error(e); + } + } + + /** + * Loads system version from debian changelog file. + * + * @param file + * debian changelog file + */ + protected static void loadSystemVersion(File file) { + try { + BufferedReader reader = new BufferedReader(new FileReader(file)); + String line = reader.readLine(); + + int startIndex = line.indexOf("("); + int endIndex = line.indexOf(")"); + + if (startIndex >= 0 && endIndex >= 0) { + systemVersion = line.substring(startIndex + 1, endIndex); + } else { + logger.error("Invalid CHANGELOG file. Cannot find system version in line: " + line); + } + reader.close(); + } catch (IOException e) { + logger.error(e); + } + } + + /** + * @param baseDir + * directory where the system is placed + * @return the systemBuild + * @see #systemBuildTime + */ + public static String getSystemBuild(String baseDir) { + if (systemBuildTime == null) { + loadSystemVersion(baseDir); + } + return systemBuildTime; + } + + /** + * @param baseDir + * directory where the system is placed + * @param forceReload + * if true then forces to reload data from text file + * @return the systemBuild + * @see #systemBuildTime + */ + public static String getSystemBuild(String baseDir, boolean forceReload) { + if (forceReload) { + systemBuildTime = null; + } + return getSystemBuild(baseDir); + } + + /** + * @return the xFrametDomain + * @see #xFrametDomain + */ + public static String getxFrameDomain() { + return xFrametDomain; + } + + /** + * @param xFrametDomain + * the xFrametDomain to set + * @see #xFrametDomain + */ + public static void setxFrameDomain(String xFrametDomain) { + Configuration.xFrametDomain = xFrametDomain; + } + + /** + * @param path + * the path to webapps to set + * @see #webAppDir + */ + public static void setWebAppDir(String path) { + Configuration.webAppDir = path; + } + + /** + * @return the {@link #webAppDir} + */ + public static String getWebAppDir() { + return Configuration.webAppDir; + } + + /** + * @return the memorySaturationRatioTriggerClean + * @see #memorySaturationRatioTriggerClean + */ + public static Double getMemorySaturationRatioTriggerClean() { + return memorySaturationRatioTriggerClean; + } + + /** + * @param memorySaturationRatioTriggerClean + * the memorySaturationRatioTriggerClean to set + * @see #memorySaturationRatioTriggerClean + */ + public static void setMemorySaturationRatioTriggerClean(Double memorySaturationRatioTriggerClean) { + Configuration.memorySaturationRatioTriggerClean = memorySaturationRatioTriggerClean; + } + + /** + * Returns information about version of the framework. + * + * @param baseDir + * directory where project was deployed (or information about version + * is stored) + * @return information about version of the framework + */ + public static FrameworkVersion getFrameworkVersion(String baseDir) { + FrameworkVersion result = new FrameworkVersion(); + loadSystemVersion(baseDir); + result.setGitVersion(getSystemBuildVersion(baseDir)); + result.setTime(getSystemBuild(baseDir)); + result.setVersion(getSystemVersion(baseDir)); + return result; + } } diff --git a/commons/src/main/java/lcsb/mapviewer/common/XmlParser.java b/commons/src/main/java/lcsb/mapviewer/common/XmlParser.java index 66be945a96a8b9866240b0ccdc99786d6a1b804e..2a7890b87939bd11183124f187bd9ff2e2c26abb 100644 --- a/commons/src/main/java/lcsb/mapviewer/common/XmlParser.java +++ b/commons/src/main/java/lcsb/mapviewer/common/XmlParser.java @@ -8,7 +8,6 @@ import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; -import java.util.Collection; import java.util.List; import javax.xml.parsers.DocumentBuilder; diff --git a/commons/testFiles/version/version.txt b/commons/testFiles/version/version.txt index 4a6ba583e1764693013054551b71a39c4dfaea86..69b227275f39291f37549cae92094325dd701cb8 100644 --- a/commons/testFiles/version/version.txt +++ b/commons/testFiles/version/version.txt @@ -1,2 +1,2 @@ 100 -102 \ No newline at end of file + 102 \ No newline at end of file diff --git a/console/src/main/java/lcsb/mapviewer/run/BellExport.java b/console/src/main/java/lcsb/mapviewer/run/BellExport.java deleted file mode 100644 index f3c63406f72f52f727ab78bb90300bd7ef08caae..0000000000000000000000000000000000000000 --- a/console/src/main/java/lcsb/mapviewer/run/BellExport.java +++ /dev/null @@ -1,137 +0,0 @@ -package lcsb.mapviewer.run; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.annotation.services.ModelAnnotator; -import lcsb.mapviewer.common.IProgressUpdater; -import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.persist.ApplicationContextLoader; -import lcsb.mapviewer.persist.DbUtils; -import lcsb.mapviewer.services.interfaces.IExporterService; -import lcsb.mapviewer.services.interfaces.IExporterService.ExporterParameters; -import lcsb.mapviewer.services.utils.data.ExportFileType; - -/** - * This class prepare data for Bell format (further transformation is done by - * Marek). - * - * @author Piotr Gawron - * - */ -public class BellExport { - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(BellExport.class.getName()); - - /** - * Object that performs different types of export transformation. - */ - @Autowired - private IExporterService exporter; - - /** - * Object used to annotate the model. - */ - @Autowired - private ModelAnnotator modelAnnotator; - - /** - * Object used to annotate the model. - */ - @Autowired - private DbUtils dbUtils; - - /** - * Static main method used to run this stand alone code. - * - * @param args - * command line arguments - */ - public static void main(String[] args) { - ApplicationContextLoader.loadApplicationContext("consoleApplicationContext.xml"); - BellExport main = new BellExport(); - ApplicationContextLoader.injectDependencies(main); - main.run(); - } - - /** - * Default constructor. - */ - public BellExport() { - - } - - /** - * Method that export pd map into file that can be exported to bell (by - * Marek). - * - */ - private void run() { - CellDesignerXmlParser p = new CellDesignerXmlParser(); - try { - String filename = PdMapAnnotations.getLastPdFilename(); - String version = PdMapAnnotations.getLastPdVersion(); - - // filename = "testFiles/other_full/ASTHMAP18000X8000V1_38.xml"; - // version = "1.1.38"; - dbUtils.createSessionForCurrentThread(); - Model model = p.createModel(new ConverterParams().filename(filename)); - - modelAnnotator.performAnnotations(model, new IProgressUpdater() { - @Override - public void setProgress(double progress) { - } - }); - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).// - fileName("out/bell/" + version + "-reactions.txt").// - fileType(ExportFileType.TAB_SEPARATED).// - type(Species.class).// - moleculeEdges(false); - - exporter.exportReactions(params); - - params = new IExporterService.ExporterParameters().model(model).// - fileName("out/bell/" + version + "-species.txt").// - fileType(ExportFileType.TAB_SEPARATED).// - type(Species.class).// - // column(ExportColumn.FULL).// - moleculeEdges(false); - exporter.exportSpecies(params); - - params = new IExporterService.ExporterParameters().model(model).// - fileName("out/bell/" + version + "-compartments.txt").// - fileType(ExportFileType.TAB_SEPARATED).// - type(Object.class); // - // column(ExportColumn.FULL); - exporter.exportCompartments(params); - - } catch (Exception e) { - logger.error(e.getMessage(), e); - } finally { - dbUtils.closeSessionForCurrentThread(); - } - } - - /** - * @return the modelAnnotator - * @see #modelAnnotator - */ - public ModelAnnotator getModelAnnotator() { - return modelAnnotator; - } - - /** - * @param modelAnnotator - * the modelAnnotator to set - * @see #modelAnnotator - */ - public void setModelAnnotator(ModelAnnotator modelAnnotator) { - this.modelAnnotator = modelAnnotator; - } -} diff --git a/console/src/main/java/lcsb/mapviewer/run/ConsoleConverter.java b/console/src/main/java/lcsb/mapviewer/run/ConsoleConverter.java deleted file mode 100644 index ef5e72cef0cab945fa196369d34eb1dfbd438012..0000000000000000000000000000000000000000 --- a/console/src/main/java/lcsb/mapviewer/run/ConsoleConverter.java +++ /dev/null @@ -1,450 +0,0 @@ -package lcsb.mapviewer.run; - -import java.awt.geom.Point2D; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.log4j.Logger; - -import lcsb.mapviewer.annotation.services.MiriamConnector; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; -import lcsb.mapviewer.model.graphics.PolylineData; -import lcsb.mapviewer.model.map.InconsistentModelException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.modifier.Catalysis; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.modelutils.map.ElementUtils; - -/** - * This class is entry point for console tool to convert data from tab separated - * file a CellDesigner format. - * - * @author Piotr Gawron - * - */ -public class ConsoleConverter { - - /** - * Default class logger. - */ - private final Logger logger = Logger.getLogger(ConsoleConverter.class); - - /** - * Options from the input. - */ - private RunOptions inputOptions; - - /** - * Connector used for accessing data from miriam registry. - */ - private MiriamConnector mc = new MiriamConnector(); - - /** - * Util class used to access some information about {@link Element}. - */ - private ElementUtils elementUtils = new ElementUtils(); - - /** - * Default constructor. - * - * @param args - * parameters with which the program was run - */ - public ConsoleConverter(String[] args) { - inputOptions = new RunOptions(args); - } - - /** - * Main entry point to the program. - * - * @param args - * parameters with which the program was run - */ - public static void main(String[] args) { - // ApplicationContextLoader.loadApplicationContext("consoleApplicationContext.xml"); - ConsoleConverter main = new ConsoleConverter(args); - // ApplicationContextLoader.injectDependencies(main); - try { - main.run(); - } catch (InvalidInputDataExecption e) { - main.logger.error(e, e); - } - } - - /** - * This method transform {@link #inputOptions input data}. - * - * @throws InvalidInputDataExecption - * thrown when the input data are invalid - */ - private void run() throws InvalidInputDataExecption { - if (inputOptions.isFormat()) { - inputOptions.printFormat(); - } else if (!inputOptions.isValidInput() || inputOptions.isHelpOption()) { - inputOptions.printHelp(); - } else { - logger.debug("Running..."); - - String nodesFilename = inputOptions.getNodesFilename(); - - Model model = new ModelFullIndexed(null); - model.setWidth(inputOptions.getModelSize()); - model.setHeight(inputOptions.getModelSize()); - - Set<Element> elements = null; - try { - elements = getNodes(nodesFilename); - } catch (IOException e) { - throw new InvalidInputDataExecption("Problem with input file: " + nodesFilename, e); - } - - double middleX = inputOptions.getModelSize() / 2; - double middleY = inputOptions.getModelSize() / 2; - - double size = elements.size(); - double x = 0; - - for (Element alias : model.getElements()) { - alias.setWidth(inputOptions.getAliasWidth()); - alias.setHeight(inputOptions.getAliasHeight()); - double angle = x / size * 2 * Math.PI; - alias.setX(middleX + Math.sin(angle) * inputOptions.getRadius()); - alias.setY(middleY + Math.cos(angle) * inputOptions.getRadius()); - model.addElement(alias); - x++; - } - - String reactionsFilename = inputOptions.getReactionsFilename(); - - List<Reaction> reactions; - try { - reactions = getReactions(reactionsFilename, model); - } catch (IOException e) { - throw new InvalidInputDataExecption("Problem with input file: " + reactionsFilename, e); - } - model.addReactions(reactions); - String outputFilename = inputOptions.getOutputFilename(); - - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - PrintWriter writer = null; - try { - writer = new PrintWriter(outputFilename, "UTF-8"); - writer.println(parser.toXml(model)); - } catch (FileNotFoundException e) { - throw new InvalidInputDataExecption("Problem with output file: " + outputFilename, e); - } catch (UnsupportedEncodingException e) { - logger.error(e, e); - } catch (InconsistentModelException e) { - throw new InvalidStateException(e); - } finally { - writer.close(); - } - - } - } - - /** - * Returns list of {@link Reaction reactions} obtained from input file. - * - * @param filename - * file with information about reactions - * @param model - * {@link Model} where the data about nodes is stored - * @return list of {@link Reaction reactions} obtained from input file - * @throws InvalidInputDataExecption - * thrown when the file is invalid - * @throws IOException - * thrown when there is a problem with acceesing input file - */ - private List<Reaction> getReactions(String filename, Model model) throws InvalidInputDataExecption, IOException { - List<Reaction> result = new ArrayList<Reaction>(); - Integer identifierColumn = null; - Integer typeColumn = null; - Integer reactantsColumn = null; - Integer modifiersColumn = null; - Integer productsColumn = null; - Integer annotationsColumn = null; - Set<Integer> ids = new HashSet<Integer>(); - BufferedReader br = new BufferedReader(new FileReader(new File(filename))); - try { - String line = br.readLine(); - String[] cols = line.split("\t", -1); - int columns = cols.length; - for (int i = 0; i < cols.length; i++) { - if (cols[i].equalsIgnoreCase(RunOptions.IDENTIFIER_REACTIONS_HEADER)) { - identifierColumn = i; - } else if (cols[i].equalsIgnoreCase(RunOptions.TYPE_REACTIONS_HEADER)) { - typeColumn = i; - } else if (cols[i].equalsIgnoreCase(RunOptions.REACTANTS_REACTIONS_HEADER)) { - reactantsColumn = i; - } else if (cols[i].equalsIgnoreCase(RunOptions.MODIFIERS_REACTIONS_HEADER)) { - modifiersColumn = i; - } else if (cols[i].equalsIgnoreCase(RunOptions.PRODUCTS_REACTIONS_HEADER)) { - productsColumn = i; - } else if (cols[i].equalsIgnoreCase(RunOptions.ANNOTATIONS_REACTIONS_HEADER)) { - annotationsColumn = i; - } else { - throw new InvalidInputDataExecption("Unknown column name " + cols[i], filename); - } - } - if (identifierColumn == null) { - throw new InvalidInputDataExecption("No \"" + RunOptions.IDENTIFIER_REACTIONS_HEADER + "\" defined.", filename); - } else if (typeColumn == null) { - throw new InvalidInputDataExecption("No \"" + RunOptions.TYPE_REACTIONS_HEADER + "\" defined.", filename); - } else if (reactantsColumn == null) { - throw new InvalidInputDataExecption("No \"" + RunOptions.REACTANTS_REACTIONS_HEADER + "\" defined.", filename); - } else if (modifiersColumn == null) { - throw new InvalidInputDataExecption("No \"" + RunOptions.MODIFIERS_REACTIONS_HEADER + "\" defined.", filename); - } else if (productsColumn == null) { - throw new InvalidInputDataExecption("No \"" + RunOptions.PRODUCTS_REACTIONS_HEADER + "\" defined.", filename); - } else if (annotationsColumn == null) { - throw new InvalidInputDataExecption("No \"" + RunOptions.ANNOTATIONS_REACTIONS_HEADER + "\" defined.", filename); - } - int row = 2; - while ((line = br.readLine()) != null) { - cols = line.split("\t", -1); - if (cols.length != columns) { - throw new InvalidInputDataExecption("Invalid number of columns in row " + row, filename); - } - String id = cols[identifierColumn]; - if (ids.contains(id)) { - throw new InvalidInputDataExecption("Id \"" + id + "\" is not unique.", filename); - } - - String className = cols[typeColumn]; - Class<?> clazz = elementUtils.getClassByName(className); - if (clazz == null) { - throw new InvalidInputDataExecption("Unknown element type: " + className, filename); - } - List<Product> products = new ArrayList<Product>(); - String productString = cols[productsColumn]; - for (String string : productString.split(",")) { - if (!string.isEmpty()) { - Species alias = model.getElementByElementId(string.trim()); - Product product = new Product(alias); - products.add(product); - } - } - if (products.size() == 0) { - throw new InvalidInputDataExecption("List of products cannot be empty (row: " + row + ")", filename); - } - - List<Reactant> reactants = new ArrayList<Reactant>(); - String reactantString = cols[reactantsColumn]; - for (String string : reactantString.split(",")) { - if (!string.isEmpty()) { - Species element = model.getElementByElementId(string.trim()); - Reactant product = new Reactant(element); - reactants.add(product); - } - } - if (reactants.size() == 0) { - throw new InvalidInputDataExecption("List of reactants cannot be empty (row: " + row + ")", filename); - } - - List<Modifier> modifiers = new ArrayList<Modifier>(); - String modifierString = cols[modifiersColumn]; - for (String string : modifierString.split(",")) { - if (!string.isEmpty()) { - Species element = model.getElementByElementId(string.trim()); - Modifier modifier = new Catalysis(element); - modifiers.add(modifier); - } - } - Element alias1 = products.get(0).getElement(); - Element alias2 = reactants.get(0).getElement(); - - Point2D middle = new Point2D.Double((alias1.getCenterX() + alias2.getCenterX()) / 2, (alias1.getCenterY() + alias2.getCenterY()) / 2); - - Set<MiriamData> annotations = new HashSet<MiriamData>(); - if (annotationsColumn != null) { - String[] annotationString = cols[annotationsColumn].split(","); - for (String string : annotationString) { - if (!string.isEmpty()) { - try { - annotations.add(MiriamType.getMiriamByUri(string)); - } catch (InvalidArgumentException e) { - throw new InvalidInputDataExecption("Invalid miriam urn: " + string, filename); - } - } - } - } - - try { - if (!Reaction.class.isAssignableFrom(clazz)) { - throw new InvalidInputDataExecption("Invalid reaction type type: " + className, filename); - } - Reaction reaction = (Reaction) clazz.newInstance(); - for (Product product : products) { - product.setLine(new PolylineData(middle, product.getElement().getCenter())); - reaction.addProduct(product); - } - for (Reactant reactant : reactants) { - reactant.setLine(new PolylineData(reactant.getElement().getCenter(), middle)); - reaction.addReactant(reactant); - } - for (Modifier modifier : modifiers) { - modifier.setLine(new PolylineData(middle, modifier.getElement().getCenter())); - reaction.addModifier(modifier); - } - reaction.addMiriamData(annotations); - reaction.setIdReaction(id); - result.add(reaction); - } catch (InstantiationException e) { - throw new InvalidStateException(e); - } catch (IllegalAccessException e) { - throw new InvalidStateException(e); - } - row++; - } - } finally { - br.close(); - } - return result; - } - - /** - * This method parses the data from input file into set of {@link Element - * elements}. - * - * @param filename - * nam of input file - * @return set of {@link Element elements} - * @throws InvalidInputDataExecption - * thrown when the input data is invalid - * @throws IOException - * thrown when there is a problem with input file - */ - private Set<Element> getNodes(String filename) throws InvalidInputDataExecption, IOException { - ElementUtils elementUtils = new ElementUtils(); - - Set<Element> result = new HashSet<>(); - Set<String> ids = new HashSet<>(); - - Integer identifierColumn = null; - Integer typeColumn = null; - Integer nameColumn = null; - Integer annotationsColumn = null; - - BufferedReader br = new BufferedReader(new FileReader(new File(filename))); - try { - String line = br.readLine(); - String[] cols = line.split("\t", -1); - int columns = cols.length; - for (int i = 0; i < cols.length; i++) { - if (cols[i].equalsIgnoreCase(RunOptions.IDENTIFIER_NODES_HEADER)) { - identifierColumn = i; - } else if (cols[i].equalsIgnoreCase(RunOptions.TYPE_NODES_HEADER)) { - typeColumn = i; - } else if (cols[i].equalsIgnoreCase(RunOptions.NAME_NODES_HEADER)) { - nameColumn = i; - } else if (cols[i].equalsIgnoreCase(RunOptions.ANNOTATIONS_NODES_HEADER)) { - annotationsColumn = i; - } else { - throw new InvalidInputDataExecption("Unknown column name " + cols[i], filename); - } - } - if (identifierColumn == null) { - throw new InvalidInputDataExecption("No \"" + RunOptions.IDENTIFIER_NODES_HEADER + "\" defined.", filename); - } - if (typeColumn == null) { - throw new InvalidInputDataExecption("No \"" + RunOptions.TYPE_NODES_HEADER + "\" defined.", filename); - } - if (nameColumn == null) { - throw new InvalidInputDataExecption("No \"" + RunOptions.NAME_NODES_HEADER + "\" defined.", filename); - } - int row = 2; - while ((line = br.readLine()) != null) { - if (line.isEmpty()) { - continue; - } - cols = line.split("\t", -1); - if (cols.length != columns) { - throw new InvalidInputDataExecption( - "Invalid number of columns in row " + row + ". Expected " + columns + ", but " + cols.length + " found", filename); - } - String id = cols[identifierColumn]; - if (ids.contains(id)) { - throw new InvalidInputDataExecption("Id \"" + id + "\" is not unique.", filename); - } - - String className = cols[typeColumn]; - Class<?> clazz = elementUtils.getClassByName(className); - if (clazz == null) { - throw new InvalidInputDataExecption("Unknown element type: " + className, filename); - } - String name = cols[nameColumn]; - if (name.isEmpty()) { - throw new InvalidInputDataExecption("Name cannot be empty (row " + row + ").", filename); - } - Set<MiriamData> annotations = new HashSet<MiriamData>(); - if (annotationsColumn != null) { - String[] annotationString = cols[annotationsColumn].split(","); - for (String string : annotationString) { - if (!string.isEmpty()) { - try { - annotations.add(MiriamType.getMiriamByUri(string)); - } catch (InvalidArgumentException e) { - throw new InvalidInputDataExecption("Invalid miriam urn: " + string, filename); - } - } - } - } - - try { - if (!Element.class.isAssignableFrom(clazz)) { - throw new InvalidInputDataExecption("Invliad element type: " + className, filename); - } - Element element = (Element) clazz.getConstructor(String.class).newInstance(id); - element.setName(name); - element.addMiriamData(annotations); - result.add(element); - } catch (ReflectiveOperationException | SecurityException e) { - throw new InvalidStateException(e); - } - row++; - } - } finally { - br.close(); - } - - return result; - } - - /** - * @return the mc - * @see #mc - */ - public MiriamConnector getMc() { - return mc; - } - - /** - * @param mc - * the mc to set - * @see #mc - */ - public void setMc(MiriamConnector mc) { - this.mc = mc; - } -} diff --git a/console/src/main/java/lcsb/mapviewer/run/RunOptions.java b/console/src/main/java/lcsb/mapviewer/run/RunOptions.java deleted file mode 100644 index c8a80569ab1c249266ce53a1412256e9a08a956b..0000000000000000000000000000000000000000 --- a/console/src/main/java/lcsb/mapviewer/run/RunOptions.java +++ /dev/null @@ -1,413 +0,0 @@ -package lcsb.mapviewer.run; - -import java.util.List; - -import org.apache.commons.cli.BasicParser; -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.OptionBuilder; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.log4j.Logger; - -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.modelutils.map.ElementUtils; - -/** - * This class is used to parse and store input data for {@link ConsoleConverter} - * . - * - * @author Piotr Gawron - * - */ -public class RunOptions { - /** - * Default class logger. - */ - private final Logger logger = Logger.getLogger(RunOptions.class); - - /** - * Default size of the model (width/height). - */ - private static final int MODEL_SIZE = 8000; - /** - * What is the default radius of the circle used for positioning elements. - */ - private static final double RADIUS = 3500; - - /** - * Default width of created alias. - */ - private static final int ALIAS_WIDTH = 80; - - /** - * Default height of created alias. - */ - private static final int ALIAS_HEIGHT = 20; - - /** - * What is the abbreviation of help option. - */ - private static final String HELP_OPTION = "h"; - /** - * What is the abbreviation of nodes file option. - */ - private static final String NODES_OPTION = "ni"; - /** - * What is the abbreviation of reactions file option. - */ - private static final String REACTIONS_OPTION = "ri"; - /** - * What is the abbreviation of output file option. - */ - private static final String OUTPUT_OPTION = "o"; - /** - * What is the abbreviation of printing file format option. - */ - private static final String FORMAT_OPTION = "f"; - - /** - * String used for identifier column in nodes file. - */ - public static final String IDENTIFIER_NODES_HEADER = "IDENTIFIER"; - /** - * String used for type column in nodes file. - */ - public static final String TYPE_NODES_HEADER = "TYPE"; - /** - * String used for name column in nodes file. - */ - public static final String NAME_NODES_HEADER = "NAME"; - /** - * String used for annotations column in nodes file. - */ - public static final String ANNOTATIONS_NODES_HEADER = "ANNOTATIONS"; - - /** - * Description of nodes file. - */ - private static final String NODES_DESCRIPTION = "<nodes-file>\n" - + "This file contains information about node elements (chemicals, proteins, etc.) " // - + "that will be included in the output file. The file is tab separeted list of elements " // - + "with the header row. Following columns are obligatory:\n" // - + "* " + IDENTIFIER_NODES_HEADER - + " - unique identifier of the element\n" // - + "* " + TYPE_NODES_HEADER - + " - type of the element. Following types are acceptable: $TYPES\n" // - + "* " + NAME_NODES_HEADER + " - name of the element\n" // - + "* " + ANNOTATIONS_NODES_HEADER + " - comma separated list of annotations in " // - + "Miriam format (http://www.ebi.ac.uk/miriam/main/)\n"; // - - /** - * String used for identifier column in reactions file. - */ - public static final String IDENTIFIER_REACTIONS_HEADER = IDENTIFIER_NODES_HEADER; - /** - * String used for type column in reactions file. - */ - public static final String TYPE_REACTIONS_HEADER = TYPE_NODES_HEADER; - /** - * String used for reactants column in reactions file. - */ - public static final String REACTANTS_REACTIONS_HEADER = "REACTANTS"; - /** - * String used for modifiers column in reactions file. - */ - public static final String MODIFIERS_REACTIONS_HEADER = "MODIFIERS"; - /** - * String used for products column in reactions file. - */ - public static final String PRODUCTS_REACTIONS_HEADER = "PRODUCTS"; - /** - * String used for annotations column in reactions file. - */ - public static final String ANNOTATIONS_REACTIONS_HEADER = ANNOTATIONS_NODES_HEADER; - - /** - * Description of reactions file. - */ - private static final String REACTIONS_DESCRIPTION = "<reactions-file>\n" // - + "This file contains information about reactions. The file is tab separeted list of all " // - + "reactions with the header row. Following columns are obligatory:\n" // - + "* " + IDENTIFIER_REACTIONS_HEADER - + " - unique identifier of the reaction\n" // - + "* " - + TYPE_REACTIONS_HEADER - + " - type of the element. Following types are acceptable: $R_TYPES\n" // - + "* " + REACTANTS_REACTIONS_HEADER + " - comma separated list of reactant identifiers\n" // - + "* " + MODIFIERS_REACTIONS_HEADER + " - comma separated list of modifier identifiers\n" // - + "* " + PRODUCTS_REACTIONS_HEADER + " - comma separated list of product identifiers\n" // - + "* " + ANNOTATIONS_REACTIONS_HEADER + " - comma separated list of annotations in " // - + "Miriam format (http://www.ebi.ac.uk/miriam/main/)\n"; // - - /** - * Object with available input options. - */ - private Options options; - - /** - * What should be the command line to run the program. - */ - private String commandLineRun = null; - - /** - * Was the input valid? - */ - private boolean validInput = false; - - /** - * Data parsed from input. - */ - private CommandLine commandLine; - - /** - * Default constructor that parses data. - * - * @param args - * parameters used to run the program - */ - public RunOptions(String[] args) { - options = new Options(); - options.addOption(createOption("nodes-input", NODES_OPTION, true, "nodes-file", "tab separated file with input nodes (chemicals, proteins, etc.)")); - options.addOption(createOption("reaction-input", REACTIONS_OPTION, true, "reactions-file", "tab separated file with input reactions")); - options.addOption(createOption("output", OUTPUT_OPTION, true, "output-file", "CellDesigner file with output diagram")); - OptionBuilder.isRequired(false); - options.addOption(HELP_OPTION, false, "print this help menu"); - options.addOption(FORMAT_OPTION, false, "print format of input files"); - - commandLineRun = "java -jar " + new java.io.File(ConsoleConverter.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName() - + " [options]"; - - CommandLineParser parser = new BasicParser(); - - try { - validInput = true; - commandLine = parser.parse(options, args); - if (getNodesFilename() == null || getReactionsFilename() == null || getOutputFilename() == null) { - validInput = false; - } - } catch (ParseException e) { - validInput = false; - logger.info(e.getMessage()); - } - - } - - /** - * Creates new {@link Option} object. - * - * @param optionName - * full name of the option - * @param optionAbbreviation - * abbreviation of the option - * @param hasArgument - * has the option argument - * @param argumentName - * name of the argument - * @param description - * description of the option - * @return {@link Option} created from input values - */ - private Option createOption(String optionName, String optionAbbreviation, boolean hasArgument, String argumentName, String description) { - OptionBuilder.hasArg(hasArgument); - if (hasArgument) { - OptionBuilder.withArgName(argumentName); - } - OptionBuilder.withDescription(description); - OptionBuilder.withLongOpt(optionName); - return OptionBuilder.create(optionAbbreviation); - } - - /** - * @return the options - * @see #options - */ - public Options getOptions() { - return options; - } - - /** - * @param options - * the options to set - * @see #options - */ - public void setOptions(Options options) { - this.options = options; - } - - /** - * @return the commandLineRun - * @see #commandLineRun - */ - public String getCommandLineRun() { - return commandLineRun; - } - - /** - * @param commandLineRun - * the commandLineRun to set - * @see #commandLineRun - */ - public void setCommandLineRun(String commandLineRun) { - this.commandLineRun = commandLineRun; - } - - /** - * @return the validInput - * @see #validInput - */ - public boolean isValidInput() { - return validInput; - } - - /** - * @param validInput - * the validInput to set - * @see #validInput - */ - public void setValidInput(boolean validInput) { - this.validInput = validInput; - } - - /** - * @return the commandLine - * @see #commandLine - */ - public CommandLine getCommandLine() { - return commandLine; - } - - /** - * @param commandLine - * the commandLine to set - * @see #commandLine - */ - public void setCommandLine(CommandLine commandLine) { - this.commandLine = commandLine; - } - - /** - * Prints help to the console how to used the program (what parameters to put - * and what are they used for). - */ - public void printHelp() { - HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp(commandLineRun, options); - } - - /** - * Prints information about input file formats. - */ - public void printFormat() { - String desc = NODES_DESCRIPTION; - ElementUtils eu = new ElementUtils(); - List<Class<? extends Element>> classes = eu.getAvailableElementSubclasses(); - String classString = ""; - for (Class<? extends Element> class1 : classes) { - classString += class1.getSimpleName() + ", "; - } - desc = desc.replaceAll("\\$TYPES", classString); - desc += "\n"; - - List<Class<? extends Reaction>> rClasses = eu.getAvailableReactionSubclasses(); - classString = ""; - for (Class<? extends Reaction> class1 : rClasses) { - classString += class1.getSimpleName().replace("Reaction", "") + ", "; - } - - desc += REACTIONS_DESCRIPTION.replaceAll("\\$R_TYPES", classString); - System.out.println(desc); - } - - /** - * Checks if {@link #HELP_OPTION} was selected in the input. - * - * @return <code>true</code> if {@link #HELP_OPTION} was selected, - * <code>false</code> otherwise - */ - public boolean isHelpOption() { - return commandLine.hasOption(HELP_OPTION); - } - - /** - * Returns name of the nodes file. - * - * @return name of the nodes file - */ - public String getNodesFilename() { - return commandLine.getOptionValue(NODES_OPTION); - } - - /** - * Returns name of the reactions file. - * - * @return name of the reactions file - */ - public String getReactionsFilename() { - return commandLine.getOptionValue(REACTIONS_OPTION); - } - - /** - * Returns name of the output file. - * - * @return name of the output file - */ - public String getOutputFilename() { - return commandLine.getOptionValue(OUTPUT_OPTION); - } - - /** - * Checks if {@link #FORMAT_OPTION} was selected in the input. - * - * @return <code>true</code> if {@link #FORMAT_OPTION} was selected, - * <code>false</code> otherwise - */ - public boolean isFormat() { - return commandLine.hasOption(FORMAT_OPTION); - } - - /** - * Returns size of created {@link lcsb.mapviewer.model.map.model.Model}. - * - * @return size of created {@link lcsb.mapviewer.model.map.model.Model} - */ - public int getModelSize() { - return RunOptions.MODEL_SIZE; - } - - /** - * Returns width of created - * {@link lcsb.mapviewer.model.map.species.Element}. - * - * @return width of created - * {@link lcsb.mapviewer.model.map.species.Element} - */ - public int getAliasWidth() { - return RunOptions.ALIAS_WIDTH; - } - - /** - * Returns height of created - * {@link lcsb.mapviewer.model.map.species.Element}. - * - * @return height of created - * {@link lcsb.mapviewer.model.map.species.Element} - */ - public int getAliasHeight() { - return RunOptions.ALIAS_HEIGHT; - } - - /** - * Returns radius of the circle on which elements will be located in the - * output CellDesigner file. - * - * @return radius of the circle on which elements will be located - */ - public double getRadius() { - return RunOptions.RADIUS; - } - -} diff --git a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterCollectionXmlParser.java b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterCollectionXmlParser.java index cf551a6b1a3ae482165d432636fa6a2c0469e07d..20d8dcd9641bb719d59ba124d2a1525e1157f65d 100644 --- a/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterCollectionXmlParser.java +++ b/converter-CellDesigner/src/main/java/lcsb/mapviewer/converter/model/celldesigner/parameter/ParameterCollectionXmlParser.java @@ -16,11 +16,8 @@ public class ParameterCollectionXmlParser extends XmlParser { private ParameterXmlParser parameterParser; - private Model model; - public ParameterCollectionXmlParser(Model model) { parameterParser = new ParameterXmlParser(model); - this.model = model; } public Set<SbmlParameter> parseXmlParameterCollection(Node functionsNode) throws InvalidXmlSchemaException { diff --git a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/AllAnnotationTests.java b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/AllAnnotationTests.java index 6b34932db2cda2e674c5ba4d08cd15c20d7ac06d..21ab5296beffaead88bddf4ad1cc046efbe5e691 100644 --- a/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/AllAnnotationTests.java +++ b/converter-CellDesigner/src/test/java/lcsb/mapviewer/converter/model/celldesigner/annotation/AllAnnotationTests.java @@ -4,11 +4,9 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; -import lcsb.mapviewer.converter.annotation.XmlAnnotationParserTest; - @RunWith(Suite.class) @SuiteClasses({ NoteFieldTest.class, // - RestAnnotationParserTest.class, // + RestAnnotationParserTest.class, // }) public class AllAnnotationTests { diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementParser.java index c84692525e46d0476ee972b9be7b6e1bb74fbb2f..1c8468a8c91b470457f3f135c62d2e77703e6137 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlElementParser.java @@ -15,7 +15,6 @@ import org.sbml.jsbml.ext.layout.Layout; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.converter.InvalidInputDataExecption; -import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.species.Element; public abstract class SbmlElementParser<T extends org.sbml.jsbml.Symbol> extends SbmlBioEntityParser { diff --git a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParser.java b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParser.java index 9d6c69c344d95acca703203fa8b61512f676b0e9..cb5c31938591da7e123fab4cc27a5b88bc190cc3 100644 --- a/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParser.java +++ b/converter-sbml/src/main/java/lcsb/mapviewer/converter/model/sbml/SbmlParser.java @@ -33,7 +33,6 @@ import lcsb.mapviewer.converter.model.sbml.species.SbmlSpeciesParser; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.InconsistentModelException; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.kinetics.SbmlFunction; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.modifier.Modulation; diff --git a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParserTest.java b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParserTest.java index c82b00a7e468e9216c66a5aa151999427068216c..2a049eecec810853e37d1db9f6255c4989176cbc 100644 --- a/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParserTest.java +++ b/converter-sbml/src/test/java/lcsb/mapviewer/converter/model/sbml/species/SbmlSpeciesParserTest.java @@ -6,7 +6,6 @@ import java.io.FileNotFoundException; import org.apache.log4j.Logger; import org.junit.Test; -import org.sbml.jsbml.SBMLDocument; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.InvalidInputDataExecption; @@ -129,5 +128,4 @@ public class SbmlSpeciesParserTest { assertTrue(element instanceof Unknown); } - } diff --git a/converter/src/test/java/lcsb/mapviewer/converter/OverviewParserTest.java b/converter/src/test/java/lcsb/mapviewer/converter/OverviewParserTest.java index feace015aecc51cdc5e9432d02f5f178aa45b73d..373feff8d779bc835c5b3fba639dfbae1eac550b 100644 --- a/converter/src/test/java/lcsb/mapviewer/converter/OverviewParserTest.java +++ b/converter/src/test/java/lcsb/mapviewer/converter/OverviewParserTest.java @@ -7,7 +7,6 @@ import static org.junit.Assert.fail; import java.awt.geom.Point2D; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; diff --git a/frontend-js/src/main/js/Configuration.js b/frontend-js/src/main/js/Configuration.js index c08cda5c9e24773062b0e36c137a48a1ae475e51..ee3699ad4ab53337db499fd1a84e7011d9d2e116 100644 --- a/frontend-js/src/main/js/Configuration.js +++ b/frontend-js/src/main/js/Configuration.js @@ -58,10 +58,35 @@ function Configuration(json) { self.setModificationStateTypes(json.modificationStateTypes); self.setPrivilegeTypes(json.privilegeTypes); self.setAnnotators(json.annotators); + self.setVersion(json.version); + self.setBuildDate(json.buildDate); + self.setGitHash(json.gitHash); self.setPluginsData(json.plugins); } } +Configuration.prototype.setVersion = function (version) { + this._version = version; +}; +Configuration.prototype.getVersion = function () { + return this._version; +}; + +Configuration.prototype.setBuildDate = function (buildDate) { + this._buildDate = buildDate; +}; +Configuration.prototype.getBuildDate = function () { + return this._buildDate; +}; + +Configuration.prototype.setGitHash = function (gitHash) { + this._gitHash = gitHash; +}; +Configuration.prototype.getGitHash = function () { + return this._gitHash; +}; + + Configuration.prototype.setOption = function (type, value) { this._options[type] = value; }; diff --git a/frontend-js/src/main/js/ConfigurationType.js b/frontend-js/src/main/js/ConfigurationType.js index bf850e2861634d9b9217d6602308bc802c599dbb..85734b7568d2a1247e68862cc8726fc600853b94 100644 --- a/frontend-js/src/main/js/ConfigurationType.js +++ b/frontend-js/src/main/js/ConfigurationType.js @@ -5,6 +5,7 @@ var ConfigurationType = { GOOGLE_ANALYTICS_IDENTIFIER: "GOOGLE_ANALYTICS_IDENTIFIER", LOGO_IMG: "LOGO_IMG", LOGO_LINK: "LOGO_LINK", + LOGO_TEXT: "LOGO_TEXT", LEGEND_FILES: "LEGEND_FILES", MIN_COLOR_VAL: "MIN_COLOR_VAL", MAX_COLOR_VAL: "MAX_COLOR_VAL", diff --git a/frontend-js/src/main/js/NetworkError.js b/frontend-js/src/main/js/NetworkError.js index 438539ed6b3d413974771d720701453807f1cd02..109b0ff5e62cf286e464960b45957e0240b41032 100644 --- a/frontend-js/src/main/js/NetworkError.js +++ b/frontend-js/src/main/js/NetworkError.js @@ -2,6 +2,7 @@ /* exported logger */ +// noinspection JSUnusedLocalSymbols var logger = require('./logger'); function NetworkError(message, connectionParams) { @@ -13,6 +14,9 @@ function NetworkError(message, connectionParams) { this.statusCode = connectionParams.statusCode; this.url = connectionParams.url; this.content = connectionParams.content; + if (this.content === undefined) { + this.content = ""; + } } NetworkError.prototype = Object.create(Error.prototype); diff --git a/frontend-js/src/main/js/ServerConnector.js b/frontend-js/src/main/js/ServerConnector.js index e7e6662fe691bcafb3d9185ecf2c88b04af1147f..8e7134f3aea9474b91c9a96b1d50e0193732b6cb 100644 --- a/frontend-js/src/main/js/ServerConnector.js +++ b/frontend-js/src/main/js/ServerConnector.js @@ -17,6 +17,7 @@ var Comment = require('./map/data/Comment'); var Configuration = require('./Configuration'); var Drug = require('./map/data/Drug'); var ConfigurationType = require('./ConfigurationType'); +var Functions = require('./Functions'); var IdentifiedElement = require('./map/data/IdentifiedElement'); var InvalidCredentialsError = require('./InvalidCredentialsError'); var LayoutAlias = require('./map/data/LayoutAlias'); @@ -129,17 +130,26 @@ ServerConnector.sendGetRequest = function (url, description) { }); }; +function isSessionExpiredError(error) { + if (error instanceof NetworkError) { + if (error.statusCode === HttpStatus.FORBIDDEN) { + if (error.content.indexOf('"reason":"Invalid token"') >= 0) { + return true; + } + if (error.content.indexOf('"reason":"Missing cookie') >= 0) { + return true; + } + } + } + return false; +} + ServerConnector.sendRequest = function (params) { var self = this; if (arguments.length > 1) { return Promise.reject(new Error("Only two arguments are supported")); } - if (self.getSessionData().getToken() === undefined) { - self.getSessionData().setLogin(undefined); - window.location.reload(false); - } - var description = params.url; if (params.description !== undefined) { description = params.description; @@ -158,6 +168,22 @@ ServerConnector.sendRequest = function (params) { }); }).then(function () { return content; + }, function (error) { + var promise = Promise.resolve(); + if (isSessionExpiredError(error)) { + self.getSessionData().setToken(undefined); + var login = self.getSessionData().getLogin(); + promise = self.login().then(function () { + if (login === "anonymous" || login === undefined) { + window.location.reload(false); + } else { + window.location.href = ServerConnector.getServerBaseUrl() + "login.xhtml?from=" + encodeURI(window.location.href); + } + }); + } + return promise.then(function () { + return Promise.reject(error); + }); }); }; @@ -212,30 +238,6 @@ ServerConnector.sendPatchRequest = function (url, json) { }); }; -ServerConnector.getToken = function () { - var self = this; - - var login = self.getSessionData(null).getLogin(); - var token = self.getSessionData(null).getToken(); - if (token === undefined || login === undefined) { - return self.login(); - } else { - // if the project is not initialized then check if we can download data - // using current token - if (self.getSessionData().getProject() === null) { - return self.getConfiguration().then(function () { - return token; - // if there was an error accessing configuration it means our token is - // invalid - }, function () { - return self.login(); - }); - } else { - return Promise.resolve(token); - } - } -}; - ServerConnector.getApiBaseUrl = function () { return this.getServerBaseUrl() + "/api/"; }; @@ -1327,11 +1329,12 @@ ServerConnector.getComments = function (params) { ServerConnector.getSessionData = function (project) { if (this._sessionData === undefined) { - this._sessionData = new SessionData(project); + this._sessionData = new SessionData(null); } if (project !== undefined && this._sessionData.getProject() === null) { this._sessionData.setProject(project); } + return this._sessionData; }; @@ -1357,6 +1360,14 @@ ServerConnector.getClosestElementsByCoordinates = function (params) { }); }; +ServerConnector.createSession = function () { + var self = this; + return self.getConfiguration().catch(function (error) { + if (isSessionExpiredError(error)) { + return self.login(); + } + }); +}; ServerConnector.login = function (login, password) { var self = this; var params = {}; @@ -1366,7 +1377,6 @@ ServerConnector.login = function (login, password) { } else { params.login = "anonymous"; } - self.getSessionData().setToken(""); return self.sendPostRequest(self.loginUrl(), params).then(function () { self.getSessionData().setLogin(params.login); return Promise.resolve(self.getSessionData().getToken()); diff --git a/frontend-js/src/main/js/gui/leftPanel/ProjectInfoPanel.js b/frontend-js/src/main/js/gui/leftPanel/ProjectInfoPanel.js index 357c3560f4a05e697db7c9b15b2cf8f4fb0f9eb2..a9501998f43888bf02af34a9c3a303b9e3f08736 100644 --- a/frontend-js/src/main/js/gui/leftPanel/ProjectInfoPanel.js +++ b/frontend-js/src/main/js/gui/leftPanel/ProjectInfoPanel.js @@ -153,12 +153,6 @@ ProjectInfoPanel.prototype._createInfoPanelGui = function () { type: "a", href: ServerConnector.getServerBaseUrl() + "/export.xhtml?id=" + projectId, content: '<i class="fa fa-mail-forward"> EXPORT', - onclick: function () { - //TODO session expired hack (it should be done on the export.xhtml web page) - if (ServerConnector.getSessionData().getToken() === undefined) { - exportButton.href = ServerConnector.getServerBaseUrl() + "login.xhtml?from=" + encodeURI(exportButton.href); - } - }, xss: false }); liElement = Functions.createElement({ diff --git a/frontend-js/src/main/js/minerva.js b/frontend-js/src/main/js/minerva.js index 6f877771230e337da3ea06a6e55f16949431421d..dd99ee55d21751b8f7f46e5f16197e815f022947 100644 --- a/frontend-js/src/main/js/minerva.js +++ b/frontend-js/src/main/js/minerva.js @@ -9,6 +9,7 @@ var ConfigurationType = require('./ConfigurationType'); var CustomMap = require('./map/CustomMap'); var CustomMapOptions = require('./map/CustomMapOptions'); var Export = require('./Export'); +var GuiUtils = require('./gui/leftPanel/GuiUtils'); var PluginManager = require('./plugin/PluginManager'); var SearchDbOverlay = require('./map/overlay/SearchDbOverlay'); @@ -242,7 +243,8 @@ function create(params) { + "<img src='resources/images/icons/ajax-loader.gif'/>" + "</div>"; // make sure that we are logged in - return ServerConnector.getToken().then(function () { + // make sure that we are logged in + return ServerConnector.createSession().then(function () { return ServerConnector.getConfiguration(); }).then(function (configuration) { params.setConfiguration(configuration); @@ -367,6 +369,156 @@ function create(params) { } +function createFooter(params) { + var logoLink, logoText, logoImg; + return ServerConnector.getConfigurationParam(ConfigurationType.LOGO_LINK).then(function (result) { + logoLink = result; + return ServerConnector.getConfigurationParam(ConfigurationType.LOGO_TEXT); + }).then(function (result) { + logoText = result; + return ServerConnector.getConfigurationParam(ConfigurationType.LOGO_IMG); + }).then(function (result) { + logoImg = result; + return ServerConnector.getConfiguration(); + }).then(function (configuration) { + var div = functions.createElement({ + type: "div", id: "footerTable", + content: '<table width="100%" border="0" cellspacing="0" cellpadding="0">' + + '<tr>' + + '<td align="left"><a href="' + logoLink + '" title="' + logoText + '" target="_blank">' + + '<h:graphicImage library="images" name="' + logoImg + '" width="80" height="80" border="0" alt="' + logoText + '"/>' + + '</a></td>' + + '<td align="center" class="footerText">MiNERVA version ' + configuration.getVersion() + ';<br/>' + + 'build ' + configuration.getBuildDate() + ';<br/>' + + 'git: ' + configuration.getGitHash() + '</td>' + + '<td align="right"><a href="http://wwwen.uni.lu/lcsb/" title="LCSB - Luxembourg Centre for Systems Biomedicine" target="_blank">' + + '<h:graphicImage library="images" name="lcsb.png" width="80" height="80" border="0" alt="LCSB - Luxembourg Centre for Systems Biomedicine"/>' + + '</a></td>' + + '</tr>\n' + + '</table>', xss: false + }); + return div; + }) +} + +function createLoginDiv(params) { + var loggedIn = false; + + var result = functions.createElement({type: "center"}); + var resultDiv = functions.createElement({type: "div", className: "loginPanel", style: "text-align:left"}); + result.appendChild(resultDiv); + resultDiv.appendChild(functions.createElement({ + type: "div", + className: "headerFormTitle", + content: "AUTHORIZATION FORM" + })); + var guiUtils = new GuiUtils(); + var table = functions.createElement({ + type: "div", + className: "loginDataPanelGrid", + style: "display: table;border-spacing:5px" + }); + table.appendChild(guiUtils.createTableRow([ + functions.createElement({type: "label", className: "labelText", content: "LOGIN:"}), + functions.createElement({type: "input", className: "minerva-input-text", id: "username"})] + )); + table.appendChild(guiUtils.createTableRow([ + functions.createElement({type: "label", className: "labelText", content: "PASSWORD:"}), + functions.createElement({ + type: "input", + inputType: "password", + className: "minerva-input-password", + id: "password" + })] + )); + + table.appendChild(guiUtils.createTableRow([ + functions.createElement({type: "label", className: "labelText"}), + functions.createElement({type: "button", className: "labelText", id: "login", content: "LOGIN"})] + )); + + resultDiv.appendChild(table); + resultDiv.appendChild(functions.createElement({type: "br"})); + resultDiv.appendChild(functions.createElement({type: "br"})); + resultDiv.appendChild(functions.createElement({ + type: "a", + href: "javascript:;", + id: "go_to_map_button", + className: "adminLink", + content: '<i class="fa fa-chevron-right"></i> BACK TO MAP', + xss: false + })); + resultDiv.appendChild(functions.createElement({type: "br"})); + resultDiv.appendChild(functions.createElement({ + type: "a", + href: "javascript:;", + id: "register_button", + className: "adminLink", + content: '<i class="fa fa-chevron-right"></i> REQUEST AN ACCOUNT</a>', + xss: false + })); + + var fromPage = GuiConnector.getParams["from"]; + + $("#login", result).on("click", function login() { + var loginString = document.getElementById('username').value; + var passwordString = document.getElementById('password').value; + return ServerConnector.login(loginString, passwordString).then(function () { + loggedIn = true; + if (fromPage !== undefined) { + window.location.href = fromPage; + } else { + window.location.href = ServerConnector.getServerBaseUrl(); + } + }, function (error) { + if (error.constructor.name === "InvalidCredentialsError") { + GuiConnector.alert("invalid credentials"); + } else { + GuiConnector.alert(error); + } + }); + }); + $('#go_to_map_button', result).click(function () { + return ServerConnector.getProjectId().then(function (projectId) { + window.location.href = ServerConnector.getServerBaseUrl() + '?id=' + projectId; + }); + }); + $('#register_button', result).click(function () { + return ServerConnector.getProjectId().then(function (projectId) { + var email, content; + return ServerConnector.getConfigurationParam("REQUEST_ACCOUNT_EMAIL").then(function (result) { + email = result; + return ServerConnector.getConfigurationParam("REQUEST_ACCOUNT_DEFAULT_CONTENT"); + }).then(function (result) { + content = encodeURIComponent(result); + document.location.href = 'mailto:' + email + '?subject=MINERVA account request&body=' + content; + }); + }); + }); + + return result; +} + + +function createLogin(params) { + params = modifyParamsForTouchInterface(params); + if (!(params instanceof CustomMapOptions)) { + params = new CustomMapOptions(params); + } + initGlobals(params); + // make sure that we are logged in + return ServerConnector.createSession().then(function () { + return ServerConnector.getConfiguration(); + }).then(function (configuration) { + var loginDiv = createLoginDiv(params); + params.getElement().appendChild(loginDiv); + return createFooter(params); + }).then(function (footer) { + params.getElement().appendChild(footer); + return insertGoogleAnalyticsCode(); + }) +} + function createExport(params) { params = modifyParamsForTouchInterface(params); if (!(params instanceof CustomMapOptions)) { @@ -379,9 +531,7 @@ function createExport(params) { var result; // make sure that we are logged in - return ServerConnector.getToken().then(function () { - return ServerConnector.getConfiguration(); - }).then(function (configuration) { + return ServerConnector.getConfiguration().then(function (configuration) { params.setConfiguration(configuration); return getProject(params); }).then(function (project) { @@ -402,10 +552,14 @@ function createAdmin(params) { params.getElement().style.display = "table"; params.getElement().innerHTML = "<div style='vertical-align:middle;display:table-cell;text-align: center'>" + "<img src='resources/images/icons/ajax-loader.gif'/>" + "</div>"; + if (ServerConnector.getSessionData(null).getLogin() === "anonymous") { + window.location.href = ServerConnector.getServerBaseUrl() + "login.xhtml?from=" + encodeURI(window.location.href); + return Promise.resolve() + } var result; // make sure that we are logged in - return ServerConnector.getToken().then(function () { + return ServerConnector.createSession().then(function () { return ServerConnector.getConfiguration(); }).then(function (configuration) { params.setConfiguration(configuration); @@ -421,11 +575,11 @@ function createAdmin(params) { var minerva = { create: create, + createLogin: createLogin, createExport: createExport, createAdmin: createAdmin, ServerConnector: OriginalServerConnector, - GuiConnector: GuiConnector, - DualListbox: require('dual-listbox').DualListbox + GuiConnector: GuiConnector }; module.exports = minerva; diff --git a/frontend-js/src/test/js/ServerConnector-test.js b/frontend-js/src/test/js/ServerConnector-test.js index 3a476c3233001d645f573ca1e7fb858777d6f666..868e4997c6ffc71a55899833745f5b093231509a 100644 --- a/frontend-js/src/test/js/ServerConnector-test.js +++ b/frontend-js/src/test/js/ServerConnector-test.js @@ -227,14 +227,6 @@ describe('ServerConnector', function () { }); }); - it('getToken', function () { - ServerConnector.getSessionData(null).setToken(undefined); - - return ServerConnector.getToken().then(function (token) { - assert.ok(token !== undefined); - }); - }); - it('getModelDownloadUrl', function () { return ServerConnector.getModelDownloadUrl({ backgroundOverlayId: "cv14081" @@ -326,16 +318,6 @@ describe('ServerConnector', function () { }); }); - describe('readFile', function () { - it('check session expired', function () { - ServerConnector.getSessionData().setToken(undefined); - assert.ok(ServerConnector.getSessionData().getLogin()); - return ServerConnector.sendGetRequest("package.json", "Downloading projects").then(function () { - assert.notOk(ServerConnector.getSessionData().getLogin()); - }); - }); - }); - describe('getUsers', function () { it('default', function () { return ServerConnector.getUsers().then(function (users) { diff --git a/frontend-js/src/test/js/gui/CommentDialog-test.js b/frontend-js/src/test/js/gui/CommentDialog-test.js index 26932c91ec6a2bdd4a14311fe642cac09b33e2f5..4bf8cb943329ab915c2be6f5295acb1a984a5f51 100644 --- a/frontend-js/src/test/js/gui/CommentDialog-test.js +++ b/frontend-js/src/test/js/gui/CommentDialog-test.js @@ -47,16 +47,13 @@ describe('CommentDialog', function () { }); }); it('logged user', function () { - var map; - var dialog; - return ServerConnector.login("admin", "admin").then(function () { - map = helper.createCustomMap(); - dialog = new CommentDialog({ - element: testDiv, - customMap: map - }); - return dialog.open([]); - }).then(function () { + helper.loginAsAdmin(); + var map = helper.createCustomMap(); + var dialog = new CommentDialog({ + element: testDiv, + customMap: map + }); + return dialog.open([]).then(function () { assert.ok($(testDiv).dialog('isOpen')); dialog.destroy(); }); diff --git a/frontend-js/src/test/js/gui/admin/AddProjectDialog-test.js b/frontend-js/src/test/js/gui/admin/AddProjectDialog-test.js index 001ebcf429c7849127914323323b488b4f1d21e7..79ce43f69091a9ca4f6441b3b240ef557981bb67 100644 --- a/frontend-js/src/test/js/gui/admin/AddProjectDialog-test.js +++ b/frontend-js/src/test/js/gui/admin/AddProjectDialog-test.js @@ -15,13 +15,12 @@ var assert = chai.assert; describe('AddProjectDialog', function () { it('init', function () { + helper.loginAsAdmin(); var dialog = new AddProjectDialog({ element: testDiv, customMap: null }); - return ServerConnector.login("admin", "admin").then(function () { - return dialog.init(); - }).then(function () { + return dialog.init().then(function () { assert.ok(dialog.getNotifyEmail() !== ""); assert.equal(0, logger.getWarnings().length); return dialog.destroy(); @@ -29,13 +28,12 @@ describe('AddProjectDialog', function () { }); it('onUserPreferencesChange', function () { + helper.loginAsAdmin(); var dialog = new AddProjectDialog({ element: testDiv, customMap: null }); - return ServerConnector.login("admin", "admin").then(function () { - return dialog.init(); - }).then(function () { + return dialog.init().then(function () { dialog.setCache(false); assert.notOk(dialog.isCache()); dialog.setCache(true); diff --git a/frontend-js/src/test/js/helper.js b/frontend-js/src/test/js/helper.js index c02367b163aee95a25d702b94601334161a36509..682e21268d502facdb28e25c44a5ec09b010f326 100644 --- a/frontend-js/src/test/js/helper.js +++ b/frontend-js/src/test/js/helper.js @@ -25,6 +25,7 @@ var Reaction = require("../../main/js/map/data/Reaction"); var SbmlFunction = require("../../main/js/map/data/SbmlFunction"); var SbmlParameter = require("../../main/js/map/data/SbmlParameter"); var SearchDbOverlay = require("../../main/js/map/overlay/SearchDbOverlay"); +var ServerConnector = require("../../main/js/ServerConnector"); var User = require("../../main/js/map/data/User"); var Cookies = require('js-cookie'); @@ -436,6 +437,12 @@ Helper.prototype.createKineticLaw = function () { }); }; +Helper.prototype.loginAsAdmin = function () { + ServerConnector.getSessionData().setLogin("admin"); + ServerConnector.getSessionData().setToken("ADMIN_TOKEN_ID"); +}; + + Helper.EPSILON = 1e-6; diff --git a/frontend-js/src/test/js/minerva-test.js b/frontend-js/src/test/js/minerva-test.js index eeb589fc2aabfe067d81181c58bcc6ec58df7e3c..133dac4438609342f8177c415a9acacfd34de143 100644 --- a/frontend-js/src/test/js/minerva-test.js +++ b/frontend-js/src/test/js/minerva-test.js @@ -20,20 +20,20 @@ describe('minerva global', function () { global.ServerConnector = ServerConnectorMock; }); - describe('create', function() { - it('default', function() { + describe('create', function () { + it('default', function () { var options = null; - return ServerConnectorMock.getProject().then(function(project) { + return ServerConnectorMock.getProject().then(function (project) { options = helper.createCustomMapOptions(project); return minerva.create(options); - }).then(function(result) { + }).then(function (result) { assert.ok(result); assert.equal(logger.getWarnings().length, 0); return result.destroy(); }); }); - it('invalid projectId', function() { + it('invalid projectId', function () { var options = { projectId: "unknownId", element: testDiv @@ -64,9 +64,9 @@ describe('minerva global', function () { }); - it("showComments", function() { + it("showComments", function () { var options = null; - var map ; + var map; return ServerConnectorMock.getProject().then(function (project) { options = helper.createCustomMapOptions(project); return minerva.create(options); @@ -75,7 +75,7 @@ describe('minerva global', function () { var commentCheckbox = document.getElementsByName("commentCheckbox")[0]; commentCheckbox.checked = true; return commentCheckbox.onclick(); - }).then(function() { + }).then(function () { assert.ok(ServerConnectorMock.getSessionData(options.getProject()).getShowComments()); return map.destroy(); }); @@ -153,7 +153,7 @@ describe('minerva global', function () { it('create restricted map', function () { var originalFunction = ServerConnectorMock.getProject; - ServerConnectorMock.getProject=function(){ + ServerConnectorMock.getProject = function () { return Promise.reject(new SecurityError("Access denied.")); }; helper.setUrl("http://test/?id=restricted_sample"); @@ -167,14 +167,14 @@ describe('minerva global', function () { assert.equal(null, map); }).catch(function (e) { assert.ok(e.message.indexOf("Access denied") >= 0); - }).finally(function(){ + }).finally(function () { ServerConnectorMock.getProject = originalFunction; }); }); - it('create with layout from session data', function() { + it('create with layout from session data', function () { var layout; - return ServerConnectorMock.getProject().then(function(project) { + return ServerConnectorMock.getProject().then(function (project) { var options = helper.createCustomMapOptions(project); layout = project.getModel().getLayouts()[1]; @@ -245,7 +245,7 @@ describe('minerva global', function () { return ServerConnectorMock.getProject().then(function (project) { var options = helper.createCustomMapOptions(project); options.setCustomTouchInterface(true); - return minerva.create(options).then(function(result) { + return minerva.create(options).then(function (result) { assert.ok(result); return result.destroy(); }); @@ -265,16 +265,38 @@ describe('minerva global', function () { }); }); - it('create Admin', function () { - var options = null; - return ServerConnectorMock.getProject().then(function (project) { - options = helper.createCustomMapOptions(project); + describe('createAdmin', function () { + it('as admin', function () { + helper.loginAsAdmin(); + var options = null; + var url = window.location.href; + return ServerConnectorMock.getProject().then(function (project) { + options = helper.createCustomMapOptions(project); - return minerva.createAdmin(options); - }).then(function (result) { - assert.ok(result); - assert.equal(logger.getWarnings().length, 0); - result.destroy(); + return minerva.createAdmin(options); + }).then(function (result) { + assert.ok(result); + assert.equal(logger.getWarnings().length, 0); + assert.equal(url, window.location.href); + result.destroy(); + }); + }); + it('as anonymous', function () { + var options = null; + return ServerConnectorMock.getProject().then(function (project) { + options = helper.createCustomMapOptions(project); + + return minerva.createAdmin(options); + }).then(function (result) { + assert.notOk(result); + }); + }); + }); + describe('createLogin', function () { + it('default', function () { + return minerva.createLogin({element: testDiv}).then(function () { + assert.ok(testDiv.innerHTML.indexOf("MiNERVA") >= 0); + }); }); }); it('getProject', function () { diff --git a/frontend-js/testFiles/apiCalls/configuration/token=MOCK_TOKEN_ID& b/frontend-js/testFiles/apiCalls/configuration/token=MOCK_TOKEN_ID& index b20401250fa29253a276aa355b8c48f3a2b55d35..432c6e04dc6b380716c7ffa327b9a123d0e16b1a 100644 --- a/frontend-js/testFiles/apiCalls/configuration/token=MOCK_TOKEN_ID& +++ b/frontend-js/testFiles/apiCalls/configuration/token=MOCK_TOKEN_ID& @@ -1 +1 @@ -{"modelFormats":[{"handler":"lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser","extension":"xml","name":"CellDesigner SBML"},{"handler":"lcsb.mapviewer.converter.model.sbgnml.SbgnmlXmlConverter","extension":"sbgn","name":"SBGN-ML"},{"handler":"lcsb.mapviewer.converter.model.sbml.SbmlParser","extension":"xml","name":"SBML"}],"elementTypes":[{"name":"Degraded","className":"lcsb.mapviewer.model.map.species.Degraded","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.IonChannelProtein","parentClass":"lcsb.mapviewer.model.map.species.Protein"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.TopSquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Ion","className":"lcsb.mapviewer.model.map.species.Ion","parentClass":"lcsb.mapviewer.model.map.species.Chemical"},{"name":"Species","className":"lcsb.mapviewer.model.map.species.Species","parentClass":"lcsb.mapviewer.model.map.species.Element"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.RightSquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Drug","className":"lcsb.mapviewer.model.map.species.Drug","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.Protein","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.TruncatedProtein","parentClass":"lcsb.mapviewer.model.map.species.Protein"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.PathwayCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"RNA","className":"lcsb.mapviewer.model.map.species.Rna","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Chemical","className":"lcsb.mapviewer.model.map.species.Chemical","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.Compartment","parentClass":"lcsb.mapviewer.model.map.species.Element"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.OvalCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.SquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Unknown","className":"lcsb.mapviewer.model.map.species.Unknown","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Element","className":"lcsb.mapviewer.model.map.species.Element","parentClass":"lcsb.mapviewer.model.map.BioEntity"},{"name":"Phenotype","className":"lcsb.mapviewer.model.map.species.Phenotype","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Complex","className":"lcsb.mapviewer.model.map.species.Complex","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Antisense RNA","className":"lcsb.mapviewer.model.map.species.AntisenseRna","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.ReceptorProtein","parentClass":"lcsb.mapviewer.model.map.species.Protein"},{"name":"Simple molecule","className":"lcsb.mapviewer.model.map.species.SimpleMolecule","parentClass":"lcsb.mapviewer.model.map.species.Chemical"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.GenericProtein","parentClass":"lcsb.mapviewer.model.map.species.Protein"},{"name":"Gene","className":"lcsb.mapviewer.model.map.species.Gene","parentClass":"lcsb.mapviewer.model.map.species.Species"}],"modificationStateTypes":{"PHOSPHORYLATED":{"commonName":"phosphorylated","abbreviation":"P"},"METHYLATED":{"commonName":"methylated","abbreviation":"Me"},"PALMYTOYLATED":{"commonName":"palmytoylated","abbreviation":"Pa"},"ACETYLATED":{"commonName":"acetylated","abbreviation":"Ac"},"SULFATED":{"commonName":"sulfated","abbreviation":"S"},"GLYCOSYLATED":{"commonName":"glycosylated","abbreviation":"G"},"PRENYLATED":{"commonName":"prenylated","abbreviation":"Pr"},"UBIQUITINATED":{"commonName":"ubiquitinated","abbreviation":"Ub"},"PROTONATED":{"commonName":"protonated","abbreviation":"H"},"HYDROXYLATED":{"commonName":"hydroxylated","abbreviation":"OH"},"MYRISTOYLATED":{"commonName":"myristoylated","abbreviation":"My"},"UNKNOWN":{"commonName":"unknown","abbreviation":"?"},"EMPTY":{"commonName":"empty","abbreviation":""},"DONT_CARE":{"commonName":"don't care","abbreviation":"*"}},"imageFormats":[{"handler":"lcsb.mapviewer.converter.graphics.PngImageGenerator","extension":"png","name":"PNG image"},{"handler":"lcsb.mapviewer.converter.graphics.PdfImageGenerator","extension":"pdf","name":"PDF"},{"handler":"lcsb.mapviewer.converter.graphics.SvgImageGenerator","extension":"svg","name":"SVG image"}],"plugins":[],"annotators":[{"name":"BRENDA","description":"","className":"lcsb.mapviewer.annotation.services.annotators.BrendaAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://www.brenda-enzymes.org"},{"name":"Biocompendium","description":"","className":"lcsb.mapviewer.annotation.services.annotators.BiocompendiumAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://biocompendium.embl.de/"},{"name":"CAZy","description":"","className":"lcsb.mapviewer.annotation.services.annotators.CazyAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://commonchemistry.org"},{"name":"Chebi","description":"","className":"lcsb.mapviewer.annotation.services.annotators.ChebiAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Chemical"],"url":"http://www.ebi.ac.uk/chebi/"},{"name":"Uniprot","description":"","className":"lcsb.mapviewer.annotation.services.annotators.UniprotAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://www.uniprot.org/"},{"name":"Gene Ontology","description":"","className":"lcsb.mapviewer.annotation.services.annotators.GoAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Phenotype","lcsb.mapviewer.model.map.compartment.Compartment","lcsb.mapviewer.model.map.species.Complex"],"url":"http://amigo.geneontology.org/amigo"},{"name":"HGNC","description":"","className":"lcsb.mapviewer.annotation.services.annotators.HgncAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Rna","lcsb.mapviewer.model.map.species.Gene"],"url":"http://www.genenames.org"},{"name":"KEGG","description":"Annotations extracted from KEGG ENZYME Database based on species EC numbers. Annotation include relevant publications and homologous genes for given EC numbers.","className":"lcsb.mapviewer.annotation.services.annotators.KeggAnnotator","parametersDefinitions":[{"name":"KEGG organism identifier","description":"Space-delimited list of organisms codes for which homologous genes (GENE section in the KEGG enzyme record) should be imported. Currently only ATH (Arabidopsis Thaliana) is supported.","type":"java.lang.String"}],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://www.genome.jp/kegg/"},{"name":"Protein Data Bank","description":"","className":"lcsb.mapviewer.annotation.services.annotators.PdbAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Rna","lcsb.mapviewer.model.map.species.Gene"],"url":"http://www.pdbe.org/"},{"name":"Recon annotator","description":"","className":"lcsb.mapviewer.annotation.services.annotators.ReconAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Chemical","lcsb.mapviewer.model.map.reaction.Reaction"],"url":"http://humanmetabolism.org/"},{"name":"Entrez Gene","description":"","className":"lcsb.mapviewer.annotation.services.annotators.EntrezAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Rna","lcsb.mapviewer.model.map.species.Gene"],"url":"http://www.ncbi.nlm.nih.gov/gene"},{"name":"Ensembl","description":"","className":"lcsb.mapviewer.annotation.services.annotators.EnsemblAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Rna","lcsb.mapviewer.model.map.species.Gene"],"url":"www.ensembl.org"},{"name":"STITCH","description":"","className":"lcsb.mapviewer.annotation.services.annotators.StitchAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.SimpleMolecule"],"url":"http://stitch.embl.de/"},{"name":"STRING","description":"","className":"lcsb.mapviewer.annotation.services.annotators.StringAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://string-db.org/"},{"name":"TAIR","description":"","className":"lcsb.mapviewer.annotation.services.annotators.TairAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://arabidopsis.org/index.jsp"}],"buildDate":" 19/02/2018 11:28","reactionTypes":[{"name":"Catalysis","className":"lcsb.mapviewer.model.map.reaction.type.CatalysisReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown positive influence","className":"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Generic Reaction","className":"lcsb.mapviewer.model.map.reaction.Reaction","parentClass":"lcsb.mapviewer.model.map.BioEntity"},{"name":"Known transition omitted","className":"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Reduced modulation","className":"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Translation","className":"lcsb.mapviewer.model.map.reaction.type.TranslationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Heterodimer association","className":"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Transcription","className":"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown reduced trigger","className":"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown negative influence","className":"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Truncation","className":"lcsb.mapviewer.model.map.reaction.type.TruncationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Transport","className":"lcsb.mapviewer.model.map.reaction.type.TransportReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown catalysis","className":"lcsb.mapviewer.model.map.reaction.type.UnknownCatalysisReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Reduced trigger","className":"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"State transition","className":"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Physical stimulation","className":"lcsb.mapviewer.model.map.reaction.type.PhysicalStimulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Boolean logic gate","className":"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Dissociation","className":"lcsb.mapviewer.model.map.reaction.type.DissociationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Inhibition","className":"lcsb.mapviewer.model.map.reaction.type.InhibitionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Reduced physical stimulation","className":"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Negative influence","className":"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown inhibition","className":"lcsb.mapviewer.model.map.reaction.type.UnknownInhibitionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Modulation","className":"lcsb.mapviewer.model.map.reaction.type.ModulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Positive influence","className":"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown reduced physical stimulation","className":"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown reduced modulation","className":"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown transition","className":"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Trigger","className":"lcsb.mapviewer.model.map.reaction.type.TriggerReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"}],"version":"12.0.0","mapTypes":[{"name":"Downstream targets","id":"DOWNSTREAM_TARGETS"},{"name":"Pathway","id":"PATHWAY"},{"name":"Unknown","id":"UNKNOWN"}],"miriamTypes":{"CAZY":{"commonName":"CAZy","uris":["urn:miriam:cazy"],"homepage":"http://commonchemistry.org","registryIdentifier":"MIR:00000195"},"CHEMBL_TARGET":{"commonName":"ChEMBL target","uris":["urn:miriam:chembl.target"],"homepage":"https://www.ebi.ac.uk/chembldb/","registryIdentifier":"MIR:00000085"},"UNIPROT":{"commonName":"Uniprot","uris":["urn:miriam:uniprot"],"homepage":"http://www.uniprot.org/","registryIdentifier":"MIR:00000005"},"MI_R_BASE_MATURE_SEQUENCE":{"commonName":"miRBase Mature Sequence Database","uris":["urn:miriam:mirbase.mature"],"homepage":"http://www.mirbase.org/","registryIdentifier":"MIR:00000235"},"PFAM":{"commonName":"Protein Family Database","uris":["urn:miriam:pfam"],"homepage":"http://pfam.xfam.org//","registryIdentifier":"MIR:00000028"},"ENSEMBL_PLANTS":{"commonName":"Ensembl Plants","uris":["urn:miriam:ensembl.plant"],"homepage":"http://plants.ensembl.org/","registryIdentifier":"MIR:00000205"},"WIKIPEDIA":{"commonName":"Wikipedia (English)","uris":["urn:miriam:wikipedia.en"],"homepage":"http://en.wikipedia.org/wiki/Main_Page","registryIdentifier":"MIR:00000384"},"CHEBI":{"commonName":"Chebi","uris":["urn:miriam:obo.chebi","urn:miriam:chebi"],"homepage":"http://www.ebi.ac.uk/chebi/","registryIdentifier":"MIR:00000002"},"WIKIDATA":{"commonName":"Wikidata","uris":["urn:miriam:wikidata"],"homepage":"https://www.wikidata.org/","registryIdentifier":"MIR:00000549"},"REACTOME":{"commonName":"Reactome","uris":["urn:miriam:reactome"],"homepage":"http://www.reactome.org/","registryIdentifier":"MIR:00000018"},"EC":{"commonName":"Enzyme Nomenclature","uris":["urn:miriam:ec-code"],"homepage":"http://www.enzyme-database.org/","registryIdentifier":"MIR:00000004"},"DOI":{"commonName":"Digital Object Identifier","uris":["urn:miriam:doi"],"homepage":"http://www.doi.org/","registryIdentifier":"MIR:00000019"},"UNIPROT_ISOFORM":{"commonName":"UniProt Isoform","uris":["urn:miriam:uniprot.isoform"],"homepage":"http://www.uniprot.org/","registryIdentifier":"MIR:00000388"},"OMIM":{"commonName":"Online Mendelian Inheritance in Man","uris":["urn:miriam:omim"],"homepage":"http://omim.org/","registryIdentifier":"MIR:00000016"},"DRUGBANK_TARGET_V4":{"commonName":"DrugBank Target v4","uris":["urn:miriam:drugbankv4.target"],"homepage":"http://www.drugbank.ca/targets","registryIdentifier":"MIR:00000528"},"MIR_TAR_BASE_MATURE_SEQUENCE":{"commonName":"miRTarBase Mature Sequence Database","uris":["urn:miriam:mirtarbase"],"homepage":"http://mirtarbase.mbc.nctu.edu.tw/","registryIdentifier":"MIR:00100739"},"CHEMBL_COMPOUND":{"commonName":"ChEMBL","uris":["urn:miriam:chembl.compound"],"homepage":"https://www.ebi.ac.uk/chembldb/","registryIdentifier":"MIR:00000084"},"KEGG_PATHWAY":{"commonName":"Kegg Pathway","uris":["urn:miriam:kegg.pathway"],"homepage":"http://www.genome.jp/kegg/pathway.html","registryIdentifier":"MIR:00000012"},"CAS":{"commonName":"Chemical Abstracts Service","uris":["urn:miriam:cas"],"homepage":"http://commonchemistry.org","registryIdentifier":"MIR:00000237"},"REFSEQ":{"commonName":"RefSeq","uris":["urn:miriam:refseq"],"homepage":"http://www.ncbi.nlm.nih.gov/projects/RefSeq/","registryIdentifier":"MIR:00000039"},"WORM_BASE":{"commonName":"WormBase","uris":["urn:miriam:wormbase"],"homepage":"http://wormbase.bio2rdf.org/fct","registryIdentifier":"MIR:00000027"},"MI_R_BASE_SEQUENCE":{"commonName":"miRBase Sequence Database","uris":["urn:miriam:mirbase"],"homepage":"http://www.mirbase.org/","registryIdentifier":"MIR:00000078"},"TAIR_LOCUS":{"commonName":"TAIR Locus","uris":["urn:miriam:tair.locus"],"homepage":"http://arabidopsis.org/index.jsp","registryIdentifier":"MIR:00000050"},"PHARM":{"commonName":"PharmGKB Pathways","uris":["urn:miriam:pharmgkb.pathways"],"homepage":"http://www.pharmgkb.org/","registryIdentifier":"MIR:00000089"},"PDB":{"commonName":"Protein Data Bank","uris":["urn:miriam:pdb"],"homepage":"http://www.pdbe.org/","registryIdentifier":"MIR:00000020"},"PANTHER":{"commonName":"PANTHER Family","uris":["urn:miriam:panther.family","urn:miriam:panther"],"homepage":"http://www.pantherdb.org/","registryIdentifier":"MIR:00000060"},"TAXONOMY":{"commonName":"Taxonomy","uris":["urn:miriam:taxonomy"],"homepage":"http://www.ncbi.nlm.nih.gov/taxonomy/","registryIdentifier":"MIR:00000006"},"UNIGENE":{"commonName":"UniGene","uris":["urn:miriam:unigene"],"homepage":"http://www.ncbi.nlm.nih.gov/unigene","registryIdentifier":"MIR:00000346"},"HGNC":{"commonName":"HGNC","uris":["urn:miriam:hgnc"],"homepage":"http://www.genenames.org","registryIdentifier":"MIR:00000080"},"STITCH":{"commonName":"STITCH","uris":["urn:miriam:stitch"],"homepage":"http://stitch.embl.de/","registryIdentifier":"MIR:00100343"},"HGNC_SYMBOL":{"commonName":"HGNC Symbol","uris":["urn:miriam:hgnc.symbol"],"homepage":"http://www.genenames.org","registryIdentifier":"MIR:00000362"},"COG":{"commonName":"Clusters of Orthologous Groups","uris":["urn:miriam:cogs"],"homepage":"https://www.ncbi.nlm.nih.gov/COG/","registryIdentifier":"MIR:00000296"},"WIKIPATHWAYS":{"commonName":"WikiPathways","uris":["urn:miriam:wikipathways"],"homepage":"http://www.wikipathways.org/","registryIdentifier":"MIR:00000076"},"HMDB":{"commonName":"HMDB","uris":["urn:miriam:hmdb"],"homepage":"http://www.hmdb.ca/","registryIdentifier":"MIR:00000051"},"CHEMSPIDER":{"commonName":"ChemSpider","uris":["urn:miriam:chemspider"],"homepage":"http://www.chemspider.com//","registryIdentifier":"MIR:00000138"},"ENSEMBL":{"commonName":"Ensembl","uris":["urn:miriam:ensembl"],"homepage":"www.ensembl.org","registryIdentifier":"MIR:00000003"},"GO":{"commonName":"Gene Ontology","uris":["urn:miriam:obo.go","urn:miriam:go"],"homepage":"http://amigo.geneontology.org/amigo","registryIdentifier":"MIR:00000022"},"KEGG_REACTION":{"commonName":"Kegg Reaction","uris":["urn:miriam:kegg.reaction"],"homepage":"http://www.genome.jp/kegg/reaction/","registryIdentifier":"MIR:00000014"},"KEGG_ORTHOLOGY":{"commonName":"KEGG Orthology","uris":["urn:miriam:kegg.orthology"],"homepage":"http://www.genome.jp/kegg/ko.html","registryIdentifier":"MIR:00000116"},"PUBCHEM":{"commonName":"PubChem-compound","uris":["urn:miriam:pubchem.compound"],"homepage":"http://pubchem.ncbi.nlm.nih.gov/","registryIdentifier":"MIR:00000034"},"MESH_2012":{"commonName":"MeSH 2012","uris":["urn:miriam:mesh.2012","urn:miriam:mesh"],"homepage":"http://www.nlm.nih.gov/mesh/","registryIdentifier":"MIR:00000270"},"MGD":{"commonName":"Mouse Genome Database","uris":["urn:miriam:mgd"],"homepage":"http://www.informatics.jax.org/","registryIdentifier":"MIR:00000037"},"ENTREZ":{"commonName":"Entrez Gene","uris":["urn:miriam:ncbigene","urn:miriam:entrez.gene"],"homepage":"http://www.ncbi.nlm.nih.gov/gene","registryIdentifier":"MIR:00000069"},"PUBCHEM_SUBSTANCE":{"commonName":"PubChem-substance","uris":["urn:miriam:pubchem.substance"],"homepage":"http://pubchem.ncbi.nlm.nih.gov/","registryIdentifier":"MIR:00000033"},"CCDS":{"commonName":"Consensus CDS","uris":["urn:miriam:ccds"],"homepage":"http://www.ncbi.nlm.nih.gov/CCDS/","registryIdentifier":"MIR:00000375"},"KEGG_GENES":{"commonName":"Kegg Genes","uris":["urn:miriam:kegg.genes","urn:miriam:kegg.genes:hsa"],"homepage":"http://www.genome.jp/kegg/genes.html","registryIdentifier":"MIR:00000070"},"TOXICOGENOMIC_CHEMICAL":{"commonName":"Toxicogenomic Chemical","uris":["urn:miriam:ctd.chemical"],"homepage":"http://ctdbase.org/","registryIdentifier":"MIR:00000098"},"SGD":{"commonName":"Saccharomyces Genome Database","uris":["urn:miriam:sgd"],"homepage":"http://www.yeastgenome.org/","registryIdentifier":"MIR:00000023"},"KEGG_COMPOUND":{"commonName":"Kegg Compound","uris":["urn:miriam:kegg.compound"],"homepage":"http://www.genome.jp/kegg/ligand.html","registryIdentifier":"MIR:00000013"},"INTERPRO":{"commonName":"InterPro","uris":["urn:miriam:interpro"],"homepage":"http://www.ebi.ac.uk/interpro/","registryIdentifier":"MIR:00000011"},"BRENDA":{"commonName":"BRENDA","uris":["urn:miriam:brenda"],"homepage":"http://www.brenda-enzymes.org","registryIdentifier":"MIR:00100101"},"STRING":{"commonName":"STRING","uris":["urn:miriam:string"],"homepage":"http://string-db.org/","registryIdentifier":"MIR:00000265"},"UNKNOWN":{"commonName":"Unknown","uris":[],"homepage":null,"registryIdentifier":null},"DRUGBANK":{"commonName":"DrugBank","uris":["urn:miriam:drugbank"],"homepage":"http://www.drugbank.ca/","registryIdentifier":"MIR:00000102"},"PUBMED":{"commonName":"PubMed","uris":["urn:miriam:pubmed"],"homepage":"http://www.ncbi.nlm.nih.gov/PubMed/","registryIdentifier":"MIR:00000015"}},"unitTypes":[{"name":"ampere","id":"AMPERE"},{"name":"becquerel","id":"BECQUEREL"},{"name":"candela","id":"CANDELA"},{"name":"coulumb","id":"COULUMB"},{"name":"dimensionless","id":"DIMENSIONLESS"},{"name":"farad","id":"FARAD"},{"name":"gram","id":"GRAM"},{"name":"gray","id":"GRAY"},{"name":"henry","id":"HENRY"},{"name":"hertz","id":"HERTZ"},{"name":"item","id":"ITEM"},{"name":"joule","id":"JOULE"},{"name":"katal","id":"KATAL"},{"name":"kelvin","id":"KELVIN"},{"name":"kilogram","id":"KILOGRAM"},{"name":"litre","id":"LITRE"},{"name":"lumen","id":"LUMEN"},{"name":"lux","id":"LUX"},{"name":"metre","id":"METRE"},{"name":"mole","id":"MOLE"},{"name":"newton","id":"NEWTON"},{"name":"ohm","id":"OHM"},{"name":"pascal","id":"PASCAL"},{"name":"radian","id":"RADIAN"},{"name":"second","id":"SECOND"},{"name":"siemens","id":"SIEMENS"},{"name":"sievert","id":"SIEVERT"},{"name":"steradian","id":"STERADIAN"},{"name":"tesla","id":"TESLA"},{"name":"volt","id":"VOLT"},{"name":"watt","id":"WATT"},{"name":"weber","id":"WEBER"}],"options":[{"idObject":9,"type":"EMAIL_ADDRESS","value":"gawron13@o2.pl","valueType":"EMAIL","commonName":"E-mail address"},{"idObject":10,"type":"EMAIL_LOGIN","value":"gawron13","valueType":"STRING","commonName":"E-mail server login"},{"idObject":11,"type":"EMAIL_PASSWORD","value":"k13liszk!","valueType":"PASSWORD","commonName":"E-mail server password"},{"idObject":13,"type":"EMAIL_IMAP_SERVER","value":"your.imap.domain.com","valueType":"STRING","commonName":"IMAP server"},{"idObject":12,"type":"EMAIL_SMTP_SERVER","value":"poczta.o2.pl","valueType":"STRING","commonName":"SMTP server"},{"idObject":14,"type":"EMAIL_SMTP_PORT","value":"25","valueType":"INTEGER","commonName":"SMTP port"},{"idObject":6,"type":"DEFAULT_MAP","value":"sample","valueType":"STRING","commonName":"Default Project Id"},{"idObject":4,"type":"LOGO_IMG","value":"udl.png","valueType":"URL","commonName":"Logo icon"},{"idObject":3,"type":"LOGO_LINK","value":"http://wwwen.uni.lu/","valueType":"URL","commonName":"Logo link (after click)"},{"idObject":7,"type":"SEARCH_DISTANCE","value":"10","valueType":"DOUBLE","commonName":"Max distance for clicking on element (px)"},{"idObject":1,"type":"REQUEST_ACCOUNT_EMAIL","value":"your.email@domain.com","valueType":"EMAIL","commonName":"Email used for requesting an account"},{"idObject":8,"type":"SEARCH_RESULT_NUMBER","value":"100","valueType":"INTEGER","commonName":"Max number of results in search box. "},{"idObject":2,"type":"GOOGLE_ANALYTICS_IDENTIFIER","value":"","valueType":"STRING","commonName":"Google Analytics tracking ID used for statistics"},{"idObject":5,"type":"LOGO_TEXT","value":"University of Luxembourg","valueType":"STRING","commonName":"Logo description"},{"idObject":56,"type":"X_FRAME_DOMAIN","value":"http://localhost:8080/","valueType":"URL","commonName":"Domain allowed to connect via x-frame technology"},{"idObject":131,"type":"BIG_FILE_STORAGE_DIR","value":"minerva-big/","valueType":"STRING","commonName":"Path to store big files"},{"idObject":138,"type":"LEGEND_FILE_1","value":"resources/images/legend_a.png","valueType":"URL","commonName":"Legend 1 image file"},{"idObject":139,"type":"LEGEND_FILE_2","value":"resources/images/legend_b.png","valueType":"URL","commonName":"Legend 2 image file"},{"idObject":140,"type":"LEGEND_FILE_3","value":"resources/images/legend_c.png","valueType":"URL","commonName":"Legend 3 image file"},{"idObject":141,"type":"LEGEND_FILE_4","value":"resources/images/legend_d.png","valueType":"URL","commonName":"Legend 4 image file"},{"idObject":142,"type":"USER_MANUAL_FILE","value":"resources/other/user_guide.pdf","valueType":"URL","commonName":"User manual file"},{"idObject":205,"type":"MIN_COLOR_VAL","value":"FF0000","valueType":"COLOR","commonName":"Overlay color for negative values"},{"idObject":206,"type":"MAX_COLOR_VAL","value":"fbff00","valueType":"COLOR","commonName":"Overlay color for postive values"},{"idObject":218,"type":"SIMPLE_COLOR_VAL","value":"00ff40","valueType":"COLOR","commonName":"Overlay color when no values are defined"},{"idObject":239,"type":"NEUTRAL_COLOR_VAL","value":"0400ff","valueType":"COLOR","commonName":"Overlay color for value=0"},{"idObject":252,"type":"OVERLAY_OPACITY","value":"0.8","valueType":"DOUBLE","commonName":"Opacity used when drwaing data overlays (value between 0.0-1.0)"},{"idObject":253,"type":"REQUEST_ACCOUNT_DEFAULT_CONTENT","value":"Dear Diseas map team,\n\nI would like to request for an account.\n\nKind regards","valueType":"TEXT","commonName":"Email content used for requesting an account"},{"idObject":266,"type":"DEFAULT_VIEW_PROJECT","value":"true","valueType":"BOOLEAN","commonName":"Default user privilege for: View project"},{"idObject":267,"type":"DEFAULT_EDIT_COMMENTS_PROJECT","value":"true","valueType":"BOOLEAN","commonName":"Default user privilege for: Manage comments"},{"idObject":268,"type":"DEFAULT_LAYOUT_MANAGEMENT","value":"false","valueType":"BOOLEAN","commonName":"Default user privilege for: Manage layouts"}],"privilegeTypes":{"VIEW_PROJECT":{"commonName":"View project","valueType":"boolean","objectType":"Project"},"LAYOUT_MANAGEMENT":{"commonName":"Manage layouts","valueType":"boolean","objectType":"Project"},"PROJECT_MANAGEMENT":{"commonName":"Map management","valueType":"boolean","objectType":null},"CUSTOM_LAYOUTS":{"commonName":"Custom layouts","valueType":"int","objectType":null},"ADD_MAP":{"commonName":"Add project","valueType":"boolean","objectType":null},"LAYOUT_VIEW":{"commonName":"View layout","valueType":"boolean","objectType":"Layout"},"MANAGE_GENOMES":{"commonName":"Manage genomes","valueType":"boolean","objectType":null},"EDIT_COMMENTS_PROJECT":{"commonName":"Manage comments","valueType":"boolean","objectType":"Project"},"CONFIGURATION_MANAGE":{"commonName":"Manage configuration","valueType":"boolean","objectType":null},"USER_MANAGEMENT":{"commonName":"User management","valueType":"boolean","objectType":null}},"overlayTypes":[{"name":"GENERIC"},{"name":"GENETIC_VARIANT"}]} \ No newline at end of file +{"modelFormats":[{"handler":"lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser","extension":"xml","name":"CellDesigner SBML"},{"handler":"lcsb.mapviewer.converter.model.sbgnml.SbgnmlXmlConverter","extension":"sbgn","name":"SBGN-ML"},{"handler":"lcsb.mapviewer.converter.model.sbml.SbmlParser","extension":"xml","name":"SBML"}],"elementTypes":[{"name":"Degraded","className":"lcsb.mapviewer.model.map.species.Degraded","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.IonChannelProtein","parentClass":"lcsb.mapviewer.model.map.species.Protein"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.TopSquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Ion","className":"lcsb.mapviewer.model.map.species.Ion","parentClass":"lcsb.mapviewer.model.map.species.Chemical"},{"name":"Species","className":"lcsb.mapviewer.model.map.species.Species","parentClass":"lcsb.mapviewer.model.map.species.Element"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.RightSquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Drug","className":"lcsb.mapviewer.model.map.species.Drug","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.Protein","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.TruncatedProtein","parentClass":"lcsb.mapviewer.model.map.species.Protein"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.PathwayCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"RNA","className":"lcsb.mapviewer.model.map.species.Rna","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Chemical","className":"lcsb.mapviewer.model.map.species.Chemical","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.Compartment","parentClass":"lcsb.mapviewer.model.map.species.Element"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.OvalCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Compartment","className":"lcsb.mapviewer.model.map.compartment.SquareCompartment","parentClass":"lcsb.mapviewer.model.map.compartment.Compartment"},{"name":"Unknown","className":"lcsb.mapviewer.model.map.species.Unknown","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Element","className":"lcsb.mapviewer.model.map.species.Element","parentClass":"lcsb.mapviewer.model.map.BioEntity"},{"name":"Phenotype","className":"lcsb.mapviewer.model.map.species.Phenotype","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Complex","className":"lcsb.mapviewer.model.map.species.Complex","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Antisense RNA","className":"lcsb.mapviewer.model.map.species.AntisenseRna","parentClass":"lcsb.mapviewer.model.map.species.Species"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.ReceptorProtein","parentClass":"lcsb.mapviewer.model.map.species.Protein"},{"name":"Simple molecule","className":"lcsb.mapviewer.model.map.species.SimpleMolecule","parentClass":"lcsb.mapviewer.model.map.species.Chemical"},{"name":"Protein","className":"lcsb.mapviewer.model.map.species.GenericProtein","parentClass":"lcsb.mapviewer.model.map.species.Protein"},{"name":"Gene","className":"lcsb.mapviewer.model.map.species.Gene","parentClass":"lcsb.mapviewer.model.map.species.Species"}],"modificationStateTypes":{"PHOSPHORYLATED":{"commonName":"phosphorylated","abbreviation":"P"},"METHYLATED":{"commonName":"methylated","abbreviation":"Me"},"PALMYTOYLATED":{"commonName":"palmytoylated","abbreviation":"Pa"},"ACETYLATED":{"commonName":"acetylated","abbreviation":"Ac"},"SULFATED":{"commonName":"sulfated","abbreviation":"S"},"GLYCOSYLATED":{"commonName":"glycosylated","abbreviation":"G"},"PRENYLATED":{"commonName":"prenylated","abbreviation":"Pr"},"UBIQUITINATED":{"commonName":"ubiquitinated","abbreviation":"Ub"},"PROTONATED":{"commonName":"protonated","abbreviation":"H"},"HYDROXYLATED":{"commonName":"hydroxylated","abbreviation":"OH"},"MYRISTOYLATED":{"commonName":"myristoylated","abbreviation":"My"},"UNKNOWN":{"commonName":"unknown","abbreviation":"?"},"EMPTY":{"commonName":"empty","abbreviation":""},"DONT_CARE":{"commonName":"don't care","abbreviation":"*"}},"imageFormats":[{"handler":"lcsb.mapviewer.converter.graphics.PngImageGenerator","extension":"png","name":"PNG image"},{"handler":"lcsb.mapviewer.converter.graphics.PdfImageGenerator","extension":"pdf","name":"PDF"},{"handler":"lcsb.mapviewer.converter.graphics.SvgImageGenerator","extension":"svg","name":"SVG image"}],"plugins":[],"annotators":[{"name":"BRENDA","description":"","className":"lcsb.mapviewer.annotation.services.annotators.BrendaAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://www.brenda-enzymes.org"},{"name":"Biocompendium","description":"","className":"lcsb.mapviewer.annotation.services.annotators.BiocompendiumAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://biocompendium.embl.de/"},{"name":"CAZy","description":"","className":"lcsb.mapviewer.annotation.services.annotators.CazyAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://commonchemistry.org"},{"name":"Chebi","description":"","className":"lcsb.mapviewer.annotation.services.annotators.ChebiAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Chemical"],"url":"http://www.ebi.ac.uk/chebi/"},{"name":"Uniprot","description":"","className":"lcsb.mapviewer.annotation.services.annotators.UniprotAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://www.uniprot.org/"},{"name":"Gene Ontology","description":"","className":"lcsb.mapviewer.annotation.services.annotators.GoAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Phenotype","lcsb.mapviewer.model.map.compartment.Compartment","lcsb.mapviewer.model.map.species.Complex"],"url":"http://amigo.geneontology.org/amigo"},{"name":"HGNC","description":"","className":"lcsb.mapviewer.annotation.services.annotators.HgncAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Rna","lcsb.mapviewer.model.map.species.Gene"],"url":"http://www.genenames.org"},{"name":"KEGG","description":"Annotations extracted from KEGG ENZYME Database based on species EC numbers. Annotation include relevant publications and homologous genes for given EC numbers.","className":"lcsb.mapviewer.annotation.services.annotators.KeggAnnotator","parametersDefinitions":[{"name":"KEGG organism identifier","description":"Space-delimited list of organisms codes for which homologous genes (GENE section in the KEGG enzyme record) should be imported. Currently only ATH (Arabidopsis Thaliana) is supported.","type":"java.lang.String"}],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://www.genome.jp/kegg/"},{"name":"Protein Data Bank","description":"","className":"lcsb.mapviewer.annotation.services.annotators.PdbAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Rna","lcsb.mapviewer.model.map.species.Gene"],"url":"http://www.pdbe.org/"},{"name":"Recon annotator","description":"","className":"lcsb.mapviewer.annotation.services.annotators.ReconAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Chemical","lcsb.mapviewer.model.map.reaction.Reaction"],"url":"http://humanmetabolism.org/"},{"name":"Entrez Gene","description":"","className":"lcsb.mapviewer.annotation.services.annotators.EntrezAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Rna","lcsb.mapviewer.model.map.species.Gene"],"url":"http://www.ncbi.nlm.nih.gov/gene"},{"name":"Ensembl","description":"","className":"lcsb.mapviewer.annotation.services.annotators.EnsemblAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Rna","lcsb.mapviewer.model.map.species.Gene"],"url":"www.ensembl.org"},{"name":"STITCH","description":"","className":"lcsb.mapviewer.annotation.services.annotators.StitchAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.SimpleMolecule"],"url":"http://stitch.embl.de/"},{"name":"STRING","description":"","className":"lcsb.mapviewer.annotation.services.annotators.StringAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://string-db.org/"},{"name":"TAIR","description":"","className":"lcsb.mapviewer.annotation.services.annotators.TairAnnotator","parametersDefinitions":[],"elementClassNames":["lcsb.mapviewer.model.map.species.Protein","lcsb.mapviewer.model.map.species.Gene","lcsb.mapviewer.model.map.species.Rna"],"url":"http://arabidopsis.org/index.jsp"}],"buildDate":"20/02/2018 13:27","reactionTypes":[{"name":"Catalysis","className":"lcsb.mapviewer.model.map.reaction.type.CatalysisReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown positive influence","className":"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Generic Reaction","className":"lcsb.mapviewer.model.map.reaction.Reaction","parentClass":"lcsb.mapviewer.model.map.BioEntity"},{"name":"Known transition omitted","className":"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Reduced modulation","className":"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Translation","className":"lcsb.mapviewer.model.map.reaction.type.TranslationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Heterodimer association","className":"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Transcription","className":"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown reduced trigger","className":"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown negative influence","className":"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Truncation","className":"lcsb.mapviewer.model.map.reaction.type.TruncationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Transport","className":"lcsb.mapviewer.model.map.reaction.type.TransportReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown catalysis","className":"lcsb.mapviewer.model.map.reaction.type.UnknownCatalysisReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Reduced trigger","className":"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"State transition","className":"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Physical stimulation","className":"lcsb.mapviewer.model.map.reaction.type.PhysicalStimulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Boolean logic gate","className":"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Dissociation","className":"lcsb.mapviewer.model.map.reaction.type.DissociationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Inhibition","className":"lcsb.mapviewer.model.map.reaction.type.InhibitionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Reduced physical stimulation","className":"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Negative influence","className":"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown inhibition","className":"lcsb.mapviewer.model.map.reaction.type.UnknownInhibitionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Modulation","className":"lcsb.mapviewer.model.map.reaction.type.ModulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Positive influence","className":"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown reduced physical stimulation","className":"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown reduced modulation","className":"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Unknown transition","className":"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"},{"name":"Trigger","className":"lcsb.mapviewer.model.map.reaction.type.TriggerReaction","parentClass":"lcsb.mapviewer.model.map.reaction.Reaction"}],"version":"12.0.0","mapTypes":[{"name":"Downstream targets","id":"DOWNSTREAM_TARGETS"},{"name":"Pathway","id":"PATHWAY"},{"name":"Unknown","id":"UNKNOWN"}],"miriamTypes":{"CAZY":{"commonName":"CAZy","uris":["urn:miriam:cazy"],"homepage":"http://commonchemistry.org","registryIdentifier":"MIR:00000195"},"CHEMBL_TARGET":{"commonName":"ChEMBL target","uris":["urn:miriam:chembl.target"],"homepage":"https://www.ebi.ac.uk/chembldb/","registryIdentifier":"MIR:00000085"},"UNIPROT":{"commonName":"Uniprot","uris":["urn:miriam:uniprot"],"homepage":"http://www.uniprot.org/","registryIdentifier":"MIR:00000005"},"MI_R_BASE_MATURE_SEQUENCE":{"commonName":"miRBase Mature Sequence Database","uris":["urn:miriam:mirbase.mature"],"homepage":"http://www.mirbase.org/","registryIdentifier":"MIR:00000235"},"PFAM":{"commonName":"Protein Family Database","uris":["urn:miriam:pfam"],"homepage":"http://pfam.xfam.org//","registryIdentifier":"MIR:00000028"},"ENSEMBL_PLANTS":{"commonName":"Ensembl Plants","uris":["urn:miriam:ensembl.plant"],"homepage":"http://plants.ensembl.org/","registryIdentifier":"MIR:00000205"},"WIKIPEDIA":{"commonName":"Wikipedia (English)","uris":["urn:miriam:wikipedia.en"],"homepage":"http://en.wikipedia.org/wiki/Main_Page","registryIdentifier":"MIR:00000384"},"CHEBI":{"commonName":"Chebi","uris":["urn:miriam:obo.chebi","urn:miriam:chebi"],"homepage":"http://www.ebi.ac.uk/chebi/","registryIdentifier":"MIR:00000002"},"WIKIDATA":{"commonName":"Wikidata","uris":["urn:miriam:wikidata"],"homepage":"https://www.wikidata.org/","registryIdentifier":"MIR:00000549"},"REACTOME":{"commonName":"Reactome","uris":["urn:miriam:reactome"],"homepage":"http://www.reactome.org/","registryIdentifier":"MIR:00000018"},"EC":{"commonName":"Enzyme Nomenclature","uris":["urn:miriam:ec-code"],"homepage":"http://www.enzyme-database.org/","registryIdentifier":"MIR:00000004"},"DOI":{"commonName":"Digital Object Identifier","uris":["urn:miriam:doi"],"homepage":"http://www.doi.org/","registryIdentifier":"MIR:00000019"},"UNIPROT_ISOFORM":{"commonName":"UniProt Isoform","uris":["urn:miriam:uniprot.isoform"],"homepage":"http://www.uniprot.org/","registryIdentifier":"MIR:00000388"},"OMIM":{"commonName":"Online Mendelian Inheritance in Man","uris":["urn:miriam:omim"],"homepage":"http://omim.org/","registryIdentifier":"MIR:00000016"},"DRUGBANK_TARGET_V4":{"commonName":"DrugBank Target v4","uris":["urn:miriam:drugbankv4.target"],"homepage":"http://www.drugbank.ca/targets","registryIdentifier":"MIR:00000528"},"MIR_TAR_BASE_MATURE_SEQUENCE":{"commonName":"miRTarBase Mature Sequence Database","uris":["urn:miriam:mirtarbase"],"homepage":"http://mirtarbase.mbc.nctu.edu.tw/","registryIdentifier":"MIR:00100739"},"CHEMBL_COMPOUND":{"commonName":"ChEMBL","uris":["urn:miriam:chembl.compound"],"homepage":"https://www.ebi.ac.uk/chembldb/","registryIdentifier":"MIR:00000084"},"KEGG_PATHWAY":{"commonName":"Kegg Pathway","uris":["urn:miriam:kegg.pathway"],"homepage":"http://www.genome.jp/kegg/pathway.html","registryIdentifier":"MIR:00000012"},"CAS":{"commonName":"Chemical Abstracts Service","uris":["urn:miriam:cas"],"homepage":"http://commonchemistry.org","registryIdentifier":"MIR:00000237"},"REFSEQ":{"commonName":"RefSeq","uris":["urn:miriam:refseq"],"homepage":"http://www.ncbi.nlm.nih.gov/projects/RefSeq/","registryIdentifier":"MIR:00000039"},"WORM_BASE":{"commonName":"WormBase","uris":["urn:miriam:wormbase"],"homepage":"http://wormbase.bio2rdf.org/fct","registryIdentifier":"MIR:00000027"},"MI_R_BASE_SEQUENCE":{"commonName":"miRBase Sequence Database","uris":["urn:miriam:mirbase"],"homepage":"http://www.mirbase.org/","registryIdentifier":"MIR:00000078"},"TAIR_LOCUS":{"commonName":"TAIR Locus","uris":["urn:miriam:tair.locus"],"homepage":"http://arabidopsis.org/index.jsp","registryIdentifier":"MIR:00000050"},"PHARM":{"commonName":"PharmGKB Pathways","uris":["urn:miriam:pharmgkb.pathways"],"homepage":"http://www.pharmgkb.org/","registryIdentifier":"MIR:00000089"},"PDB":{"commonName":"Protein Data Bank","uris":["urn:miriam:pdb"],"homepage":"http://www.pdbe.org/","registryIdentifier":"MIR:00000020"},"PANTHER":{"commonName":"PANTHER Family","uris":["urn:miriam:panther.family","urn:miriam:panther"],"homepage":"http://www.pantherdb.org/","registryIdentifier":"MIR:00000060"},"TAXONOMY":{"commonName":"Taxonomy","uris":["urn:miriam:taxonomy"],"homepage":"http://www.ncbi.nlm.nih.gov/taxonomy/","registryIdentifier":"MIR:00000006"},"UNIGENE":{"commonName":"UniGene","uris":["urn:miriam:unigene"],"homepage":"http://www.ncbi.nlm.nih.gov/unigene","registryIdentifier":"MIR:00000346"},"HGNC":{"commonName":"HGNC","uris":["urn:miriam:hgnc"],"homepage":"http://www.genenames.org","registryIdentifier":"MIR:00000080"},"STITCH":{"commonName":"STITCH","uris":["urn:miriam:stitch"],"homepage":"http://stitch.embl.de/","registryIdentifier":"MIR:00100343"},"HGNC_SYMBOL":{"commonName":"HGNC Symbol","uris":["urn:miriam:hgnc.symbol"],"homepage":"http://www.genenames.org","registryIdentifier":"MIR:00000362"},"COG":{"commonName":"Clusters of Orthologous Groups","uris":["urn:miriam:cogs"],"homepage":"https://www.ncbi.nlm.nih.gov/COG/","registryIdentifier":"MIR:00000296"},"WIKIPATHWAYS":{"commonName":"WikiPathways","uris":["urn:miriam:wikipathways"],"homepage":"http://www.wikipathways.org/","registryIdentifier":"MIR:00000076"},"HMDB":{"commonName":"HMDB","uris":["urn:miriam:hmdb"],"homepage":"http://www.hmdb.ca/","registryIdentifier":"MIR:00000051"},"CHEMSPIDER":{"commonName":"ChemSpider","uris":["urn:miriam:chemspider"],"homepage":"http://www.chemspider.com//","registryIdentifier":"MIR:00000138"},"ENSEMBL":{"commonName":"Ensembl","uris":["urn:miriam:ensembl"],"homepage":"www.ensembl.org","registryIdentifier":"MIR:00000003"},"GO":{"commonName":"Gene Ontology","uris":["urn:miriam:obo.go","urn:miriam:go"],"homepage":"http://amigo.geneontology.org/amigo","registryIdentifier":"MIR:00000022"},"KEGG_REACTION":{"commonName":"Kegg Reaction","uris":["urn:miriam:kegg.reaction"],"homepage":"http://www.genome.jp/kegg/reaction/","registryIdentifier":"MIR:00000014"},"KEGG_ORTHOLOGY":{"commonName":"KEGG Orthology","uris":["urn:miriam:kegg.orthology"],"homepage":"http://www.genome.jp/kegg/ko.html","registryIdentifier":"MIR:00000116"},"PUBCHEM":{"commonName":"PubChem-compound","uris":["urn:miriam:pubchem.compound"],"homepage":"http://pubchem.ncbi.nlm.nih.gov/","registryIdentifier":"MIR:00000034"},"MESH_2012":{"commonName":"MeSH 2012","uris":["urn:miriam:mesh.2012","urn:miriam:mesh"],"homepage":"http://www.nlm.nih.gov/mesh/","registryIdentifier":"MIR:00000270"},"MGD":{"commonName":"Mouse Genome Database","uris":["urn:miriam:mgd"],"homepage":"http://www.informatics.jax.org/","registryIdentifier":"MIR:00000037"},"ENTREZ":{"commonName":"Entrez Gene","uris":["urn:miriam:ncbigene","urn:miriam:entrez.gene"],"homepage":"http://www.ncbi.nlm.nih.gov/gene","registryIdentifier":"MIR:00000069"},"PUBCHEM_SUBSTANCE":{"commonName":"PubChem-substance","uris":["urn:miriam:pubchem.substance"],"homepage":"http://pubchem.ncbi.nlm.nih.gov/","registryIdentifier":"MIR:00000033"},"CCDS":{"commonName":"Consensus CDS","uris":["urn:miriam:ccds"],"homepage":"http://www.ncbi.nlm.nih.gov/CCDS/","registryIdentifier":"MIR:00000375"},"KEGG_GENES":{"commonName":"Kegg Genes","uris":["urn:miriam:kegg.genes","urn:miriam:kegg.genes:hsa"],"homepage":"http://www.genome.jp/kegg/genes.html","registryIdentifier":"MIR:00000070"},"TOXICOGENOMIC_CHEMICAL":{"commonName":"Toxicogenomic Chemical","uris":["urn:miriam:ctd.chemical"],"homepage":"http://ctdbase.org/","registryIdentifier":"MIR:00000098"},"SGD":{"commonName":"Saccharomyces Genome Database","uris":["urn:miriam:sgd"],"homepage":"http://www.yeastgenome.org/","registryIdentifier":"MIR:00000023"},"KEGG_COMPOUND":{"commonName":"Kegg Compound","uris":["urn:miriam:kegg.compound"],"homepage":"http://www.genome.jp/kegg/ligand.html","registryIdentifier":"MIR:00000013"},"INTERPRO":{"commonName":"InterPro","uris":["urn:miriam:interpro"],"homepage":"http://www.ebi.ac.uk/interpro/","registryIdentifier":"MIR:00000011"},"BRENDA":{"commonName":"BRENDA","uris":["urn:miriam:brenda"],"homepage":"http://www.brenda-enzymes.org","registryIdentifier":"MIR:00100101"},"STRING":{"commonName":"STRING","uris":["urn:miriam:string"],"homepage":"http://string-db.org/","registryIdentifier":"MIR:00000265"},"UNKNOWN":{"commonName":"Unknown","uris":[],"homepage":null,"registryIdentifier":null},"DRUGBANK":{"commonName":"DrugBank","uris":["urn:miriam:drugbank"],"homepage":"http://www.drugbank.ca/","registryIdentifier":"MIR:00000102"},"PUBMED":{"commonName":"PubMed","uris":["urn:miriam:pubmed"],"homepage":"http://www.ncbi.nlm.nih.gov/PubMed/","registryIdentifier":"MIR:00000015"}},"gitHash":"bd52c45a5b81ea63121a80e6d3d36d46c4a248fe","unitTypes":[{"name":"ampere","id":"AMPERE"},{"name":"becquerel","id":"BECQUEREL"},{"name":"candela","id":"CANDELA"},{"name":"coulumb","id":"COULUMB"},{"name":"dimensionless","id":"DIMENSIONLESS"},{"name":"farad","id":"FARAD"},{"name":"gram","id":"GRAM"},{"name":"gray","id":"GRAY"},{"name":"henry","id":"HENRY"},{"name":"hertz","id":"HERTZ"},{"name":"item","id":"ITEM"},{"name":"joule","id":"JOULE"},{"name":"katal","id":"KATAL"},{"name":"kelvin","id":"KELVIN"},{"name":"kilogram","id":"KILOGRAM"},{"name":"litre","id":"LITRE"},{"name":"lumen","id":"LUMEN"},{"name":"lux","id":"LUX"},{"name":"metre","id":"METRE"},{"name":"mole","id":"MOLE"},{"name":"newton","id":"NEWTON"},{"name":"ohm","id":"OHM"},{"name":"pascal","id":"PASCAL"},{"name":"radian","id":"RADIAN"},{"name":"second","id":"SECOND"},{"name":"siemens","id":"SIEMENS"},{"name":"sievert","id":"SIEVERT"},{"name":"steradian","id":"STERADIAN"},{"name":"tesla","id":"TESLA"},{"name":"volt","id":"VOLT"},{"name":"watt","id":"WATT"},{"name":"weber","id":"WEBER"}],"options":[{"idObject":9,"type":"EMAIL_ADDRESS","value":"gawron13@o2.pl","valueType":"EMAIL","commonName":"E-mail address"},{"idObject":10,"type":"EMAIL_LOGIN","value":"gawron13","valueType":"STRING","commonName":"E-mail server login"},{"idObject":11,"type":"EMAIL_PASSWORD","value":"k13liszk!","valueType":"PASSWORD","commonName":"E-mail server password"},{"idObject":13,"type":"EMAIL_IMAP_SERVER","value":"your.imap.domain.com","valueType":"STRING","commonName":"IMAP server"},{"idObject":12,"type":"EMAIL_SMTP_SERVER","value":"poczta.o2.pl","valueType":"STRING","commonName":"SMTP server"},{"idObject":14,"type":"EMAIL_SMTP_PORT","value":"25","valueType":"INTEGER","commonName":"SMTP port"},{"idObject":6,"type":"DEFAULT_MAP","value":"sample","valueType":"STRING","commonName":"Default Project Id"},{"idObject":4,"type":"LOGO_IMG","value":"udl.png","valueType":"URL","commonName":"Logo icon"},{"idObject":3,"type":"LOGO_LINK","value":"http://wwwen.uni.lu/","valueType":"URL","commonName":"Logo link (after click)"},{"idObject":7,"type":"SEARCH_DISTANCE","value":"10","valueType":"DOUBLE","commonName":"Max distance for clicking on element (px)"},{"idObject":1,"type":"REQUEST_ACCOUNT_EMAIL","value":"your.email@domain.com","valueType":"EMAIL","commonName":"Email used for requesting an account"},{"idObject":8,"type":"SEARCH_RESULT_NUMBER","value":"100","valueType":"INTEGER","commonName":"Max number of results in search box. "},{"idObject":2,"type":"GOOGLE_ANALYTICS_IDENTIFIER","value":"","valueType":"STRING","commonName":"Google Analytics tracking ID used for statistics"},{"idObject":5,"type":"LOGO_TEXT","value":"University of Luxembourg","valueType":"STRING","commonName":"Logo description"},{"idObject":56,"type":"X_FRAME_DOMAIN","value":"http://localhost:8080/","valueType":"URL","commonName":"Domain allowed to connect via x-frame technology"},{"idObject":131,"type":"BIG_FILE_STORAGE_DIR","value":"minerva-big/","valueType":"STRING","commonName":"Path to store big files"},{"idObject":138,"type":"LEGEND_FILE_1","value":"resources/images/legend_a.png","valueType":"URL","commonName":"Legend 1 image file"},{"idObject":139,"type":"LEGEND_FILE_2","value":"resources/images/legend_b.png","valueType":"URL","commonName":"Legend 2 image file"},{"idObject":140,"type":"LEGEND_FILE_3","value":"resources/images/legend_c.png","valueType":"URL","commonName":"Legend 3 image file"},{"idObject":141,"type":"LEGEND_FILE_4","value":"resources/images/legend_d.png","valueType":"URL","commonName":"Legend 4 image file"},{"idObject":142,"type":"USER_MANUAL_FILE","value":"resources/other/user_guide.pdf","valueType":"URL","commonName":"User manual file"},{"idObject":205,"type":"MIN_COLOR_VAL","value":"FF0000","valueType":"COLOR","commonName":"Overlay color for negative values"},{"idObject":206,"type":"MAX_COLOR_VAL","value":"fbff00","valueType":"COLOR","commonName":"Overlay color for postive values"},{"idObject":218,"type":"SIMPLE_COLOR_VAL","value":"00ff40","valueType":"COLOR","commonName":"Overlay color when no values are defined"},{"idObject":239,"type":"NEUTRAL_COLOR_VAL","value":"0400ff","valueType":"COLOR","commonName":"Overlay color for value=0"},{"idObject":252,"type":"OVERLAY_OPACITY","value":"0.8","valueType":"DOUBLE","commonName":"Opacity used when drwaing data overlays (value between 0.0-1.0)"},{"idObject":253,"type":"REQUEST_ACCOUNT_DEFAULT_CONTENT","value":"Dear Diseas map team,\n\nI would like to request for an account.\n\nKind regards","valueType":"TEXT","commonName":"Email content used for requesting an account"},{"idObject":266,"type":"DEFAULT_VIEW_PROJECT","value":"true","valueType":"BOOLEAN","commonName":"Default user privilege for: View project"},{"idObject":267,"type":"DEFAULT_EDIT_COMMENTS_PROJECT","value":"true","valueType":"BOOLEAN","commonName":"Default user privilege for: Manage comments"},{"idObject":268,"type":"DEFAULT_LAYOUT_MANAGEMENT","value":"false","valueType":"BOOLEAN","commonName":"Default user privilege for: Manage layouts"}],"privilegeTypes":{"VIEW_PROJECT":{"commonName":"View project","valueType":"boolean","objectType":"Project"},"LAYOUT_MANAGEMENT":{"commonName":"Manage layouts","valueType":"boolean","objectType":"Project"},"PROJECT_MANAGEMENT":{"commonName":"Map management","valueType":"boolean","objectType":null},"CUSTOM_LAYOUTS":{"commonName":"Custom layouts","valueType":"int","objectType":null},"ADD_MAP":{"commonName":"Add project","valueType":"boolean","objectType":null},"LAYOUT_VIEW":{"commonName":"View layout","valueType":"boolean","objectType":"Layout"},"MANAGE_GENOMES":{"commonName":"Manage genomes","valueType":"boolean","objectType":null},"EDIT_COMMENTS_PROJECT":{"commonName":"Manage comments","valueType":"boolean","objectType":"Project"},"CONFIGURATION_MANAGE":{"commonName":"Manage configuration","valueType":"boolean","objectType":null},"USER_MANAGEMENT":{"commonName":"User management","valueType":"boolean","objectType":null}},"overlayTypes":[{"name":"GENERIC"},{"name":"GENETIC_VARIANT"}]} \ No newline at end of file diff --git a/frontend-js/testFiles/apiCalls/doLogin/POST_login=anonymous& b/frontend-js/testFiles/apiCalls/doLogin/POST_login=anonymous&token=MOCK_TOKEN_ID& similarity index 100% rename from frontend-js/testFiles/apiCalls/doLogin/POST_login=anonymous& rename to frontend-js/testFiles/apiCalls/doLogin/POST_login=anonymous&token=MOCK_TOKEN_ID& diff --git a/frontend-js/testFiles/apiCalls/projects/sample/comments/models/all/token=ADMIN_TOKEN_ID& b/frontend-js/testFiles/apiCalls/projects/sample/comments/models/all/token=ADMIN_TOKEN_ID& new file mode 100644 index 0000000000000000000000000000000000000000..69c32f9cf85a86d25e20b3dc55932d97025c2278 --- /dev/null +++ b/frontend-js/testFiles/apiCalls/projects/sample/comments/models/all/token=ADMIN_TOKEN_ID& @@ -0,0 +1 @@ +[{"elementId":"322.43,28.04","pinned":false,"modelId":15781,"author":"qwe","icon":"icons/comment.png","title":"Comment (coord: 322.43, 28.04)","type":"POINT","content":"","coord":{"x":322.4267578125,"y":28.037109374991598},"removed":false,"removeReason":"","id":4512,"email":"asd"},{"elementId":"1108.74,525.06","pinned":false,"modelId":15781,"author":"qwe","icon":"icons/comment.png","title":"Comment (coord: 1108.74, 525.06)","type":"POINT","content":"","coord":{"x":1108.740234375,"y":525.0585937499997},"removed":false,"removeReason":"","id":4513,"email":"asdxzf"},{"elementId":329166,"pinned":false,"modelId":15781,"author":"cnc","icon":"icons/comment.png","title":"CNC","type":"ALIAS","content":"cnc","coord":{"x":70.0,"y":269.0},"removed":false,"removeReason":"","id":4515,"email":"cnc"},{"elementId":329173,"pinned":false,"modelId":15781,"author":"s1","icon":"icons/comment.png","title":"s1","type":"ALIAS","content":"s1","coord":{"x":52.0,"y":26.0},"removed":false,"removeReason":"","id":4516,"email":""},{"elementId":329175,"pinned":false,"modelId":15781,"author":"","icon":"icons/comment.png","title":"s13","type":"ALIAS","content":"s13","coord":{"x":416.0,"y":250.0},"removed":false,"removeReason":"","id":4517,"email":"s13"},{"elementId":"241.01,372.35","pinned":true,"modelId":15781,"author":"","icon":"icons/comment.png","title":"Comment (coord: 241.01, 372.35)","type":"POINT","content":"","coord":{"x":241.00605157081114,"y":372.34797385543044},"removed":true,"removeReason":"","id":4290,"email":""},{"elementId":"216.65,370.00","pinned":false,"modelId":15781,"author":"","icon":"icons/comment.png","title":"Comment (coord: 216.65, 370.00)","type":"POINT","content":"","coord":{"x":216.65,"y":370.0},"removed":false,"removeReason":"","id":4671,"email":""},{"elementId":"214.10,368.00","pinned":true,"modelId":15781,"author":"a","icon":"icons/comment.png","title":"Comment (coord: 214.10, 368.00)","type":"POINT","content":"","coord":{"x":214.1,"y":368.0},"removed":false,"removeReason":"","id":4672,"email":"z"},{"elementId":"82.84,598.00","pinned":true,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 82.84, 598.00)","type":"POINT","content":"cont","coord":{"x":82.84,"y":598.0},"removed":true,"removeReason":"","id":4946,"email":"piotr.gawron@uni.lu"},{"elementId":"219.20,112.00","pinned":true,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 219.20, 112.00)","type":"POINT","content":"cont","coord":{"x":219.2,"y":112.0},"removed":true,"removeReason":"","id":4945,"email":"piotr.gawron@uni.lu"},{"elementId":"386.15,494.00","pinned":false,"modelId":15781,"author":"x","icon":"icons/comment.png","title":"Comment (coord: 386.15, 494.00)","type":"POINT","content":"","coord":{"x":386.15,"y":494.0},"removed":true,"removeReason":"","id":4944,"email":""},{"elementId":"497.02,465.00","pinned":false,"modelId":15781,"author":"x","icon":"icons/comment.png","title":"Comment (coord: 497.02, 465.00)","type":"POINT","content":"","coord":{"x":497.02,"y":465.0},"removed":true,"removeReason":"","id":4943,"email":""},{"elementId":"457.51,472.00","pinned":true,"modelId":15781,"author":"xxx3","icon":"icons/comment.png","title":"Comment (coord: 457.51, 472.00)","type":"POINT","content":"","coord":{"x":457.51,"y":472.0},"removed":true,"removeReason":"","id":4942,"email":""},{"elementId":"681.81,523.00","pinned":true,"modelId":15781,"author":"xxx3","icon":"icons/comment.png","title":"Comment (coord: 681.81, 523.00)","type":"POINT","content":"","coord":{"x":681.81,"y":523.0},"removed":true,"removeReason":"","id":4941,"email":""},{"elementId":"737.89,405.00","pinned":true,"modelId":15781,"author":"xxx3","icon":"icons/comment.png","title":"Comment (coord: 737.89, 405.00)","type":"POINT","content":"","coord":{"x":737.89,"y":405.0},"removed":true,"removeReason":"","id":4940,"email":""},{"elementId":"484.28,583.00","pinned":true,"modelId":15781,"author":"xxx2","icon":"icons/comment.png","title":"Comment (coord: 484.28, 583.00)","type":"POINT","content":"","coord":{"x":484.28,"y":583.0},"removed":true,"removeReason":"","id":4939,"email":""},{"elementId":"144.01,518.00","pinned":true,"modelId":15781,"author":"xxx","icon":"icons/comment.png","title":"Comment (coord: 144.01, 518.00)","type":"POINT","content":"","coord":{"x":144.01,"y":518.0},"removed":true,"removeReason":"","id":4938,"email":""},{"elementId":153503,"pinned":true,"modelId":15781,"author":"1","icon":"icons/comment.png","title":"Reaction re27","type":"REACTION","content":"","coord":{"x":888.3333333333334,"y":66.9999999999998},"removed":true,"removeReason":"","id":4674,"email":"2"},{"elementId":329178,"pinned":true,"modelId":15781,"author":"","icon":"icons/comment.png","title":"s23","type":"ALIAS","content":"","coord":{"x":735.0,"y":259.0},"removed":true,"removeReason":"","id":4673,"email":""},{"elementId":"224.30,556.00","pinned":false,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 224.30, 556.00)","type":"POINT","content":"x","coord":{"x":224.3,"y":556.0},"removed":false,"removeReason":"","id":4947,"email":"piotr.gawron@uni.lu"},{"elementId":"291.84,559.00","pinned":false,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 291.84, 559.00)","type":"POINT","content":"x","coord":{"x":291.84,"y":559.0},"removed":false,"removeReason":"","id":4948,"email":"piotr.gawron@uni.lu"},{"elementId":"345.37,546.00","pinned":false,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 345.37, 546.00)","type":"POINT","content":"y","coord":{"x":345.37,"y":546.0},"removed":false,"removeReason":"","id":4949,"email":"piotr.gawron@uni.lu"},{"elementId":"458.79,598.00","pinned":false,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 458.79, 598.00)","type":"POINT","content":"z","coord":{"x":458.79,"y":598.0},"removed":false,"removeReason":"","id":4950,"email":"piotr.gawron@uni.lu"},{"elementId":"786.31,586.00","pinned":false,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 786.31, 586.00)","type":"POINT","content":"q","coord":{"x":786.31,"y":586.0},"removed":false,"removeReason":"","id":4951,"email":"piotr.gawron@uni.lu"},{"elementId":"570.94,474.00","pinned":true,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 570.94, 474.00)","type":"POINT","content":"p","coord":{"x":570.94,"y":474.0},"removed":false,"removeReason":"","id":4952,"email":"piotr.gawron@uni.lu"},{"elementId":"607.90,463.00","pinned":true,"modelId":15781,"author":" s","icon":"icons/comment.png","title":"Comment (coord: 607.90, 463.00)","type":"POINT","content":"","coord":{"x":607.9,"y":463.0},"removed":false,"removeReason":"","id":4956,"email":""},{"elementId":"607.90,463.00","pinned":true,"modelId":15781,"author":" s","icon":"icons/comment.png","title":"Comment (coord: 607.90, 463.00)","type":"POINT","content":"","coord":{"x":607.9,"y":463.0},"removed":false,"removeReason":"","id":4957,"email":""},{"elementId":"607.90,463.00","pinned":true,"modelId":15781,"author":" s","icon":"icons/comment.png","title":"Comment (coord: 607.90, 463.00)","type":"POINT","content":"asd","coord":{"x":607.9,"y":463.0},"removed":false,"removeReason":"","id":4958,"email":""},{"elementId":"71.37,36.00","pinned":false,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 71.37, 36.00)","type":"POINT","content":"test","coord":{"x":71.37,"y":36.0},"removed":false,"removeReason":"","id":4961,"email":"piotr.gawron@uni.lu"},{"elementId":329173,"pinned":false,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"s1","type":"ALIAS","content":"test","coord":{"x":52.0,"y":26.0},"removed":false,"removeReason":"","id":4962,"email":""},{"elementId":329179,"pinned":false,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"s2","type":"ALIAS","content":"test2","coord":{"x":205.0,"y":68.0},"removed":false,"removeReason":"","id":4963,"email":""},{"elementId":329157,"pinned":true,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"s3","type":"ALIAS","content":"test3","coord":{"x":329.0,"y":59.0},"removed":false,"removeReason":"","id":4964,"email":"piotr.gawron@uni.lu"},{"elementId":153510,"pinned":false,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Reaction re5","type":"REACTION","content":"xxx","coord":{"x":128.5,"y":47.0},"removed":false,"removeReason":"","id":4965,"email":"piotr.gawron@uni.lu"},{"elementId":"477.91,184.00","pinned":false,"modelId":15781,"author":"","icon":"icons/comment.png","title":"Comment (coord: 477.91, 184.00)","type":"POINT","content":"","coord":{"x":477.91,"y":184.0},"removed":false,"removeReason":"","id":4966,"email":""},{"elementId":"1.00,200.00","pinned":true,"modelId":15781,"author":"test","icon":"icons/comment.png","title":"Comment (coord: 1.00, 200.00)","type":"POINT","content":"hal","coord":{"x":1.0,"y":200.0},"removed":true,"removeReason":"","id":4506,"email":"email"},{"elementId":329158,"pinned":false,"modelId":15781,"author":"complex12","icon":"icons/comment.png","title":"s12","type":"ALIAS","content":"complex12","coord":{"x":321.5,"y":289.0},"removed":true,"removeReason":"","id":4514,"email":""},{"elementId":"643.96,144.09","pinned":true,"modelId":15781,"author":"admin ","icon":"icons/comment.png","title":"Comment (coord: 643.96, 144.09)","type":"POINT","content":"dfgfdgdf","coord":{"x":643.9579684828551,"y":144.0935652248765},"removed":true,"removeReason":"","id":4291,"email":""},{"elementId":"100.00,200.00","pinned":true,"modelId":15781,"author":"test","icon":"icons/comment.png","title":"Comment (coord: 100.00, 200.00)","type":"POINT","content":"hal","coord":{"x":100.0,"y":200.0},"removed":true,"removeReason":"","id":4507,"email":"email"},{"elementId":"1.00,200.00","pinned":true,"modelId":15781,"author":"test","icon":"icons/comment.png","title":"Comment (coord: 1.00, 200.00)","type":"POINT","content":"hal","coord":{"x":1.0,"y":200.0},"removed":true,"removeReason":"","id":4508,"email":"email"},{"elementId":"1.00,200.00","pinned":true,"modelId":15781,"author":"test","icon":"icons/comment.png","title":"Comment (coord: 1.00, 200.00)","type":"POINT","content":"hal","coord":{"x":1.0,"y":200.0},"removed":true,"removeReason":"","id":4509,"email":"email"},{"elementId":"883.81,380.41","pinned":true,"modelId":15781,"author":"xxx","icon":"icons/comment.png","title":"Comment (coord: 883.81, 380.41)","type":"POINT","content":"","coord":{"x":883.81,"y":380.41},"removed":true,"removeReason":"","id":4518,"email":"xxx"},{"elementId":"1.00,200.00","pinned":true,"modelId":15781,"author":"test","icon":"icons/comment.png","title":"Comment (coord: 1.00, 200.00)","type":"POINT","content":"halo","coord":{"x":1.0,"y":200.0},"removed":true,"removeReason":"","id":4510,"email":"email"},{"elementId":"1199.22,26.00","pinned":true,"modelId":15781,"author":" x","icon":"icons/comment.png","title":"Comment (coord: 1199.22, 26.00)","type":"POINT","content":"","coord":{"x":1199.22,"y":26.0},"removed":true,"removeReason":"some reasone","id":4959,"email":""},{"elementId":"2.00,12.00","pinned":false,"modelId":15781,"author":"","icon":"icons/comment.png","title":"Comment (coord: 2.00, 12.00)","type":"POINT","content":"","coord":{"x":2.0,"y":12.0},"removed":true,"removeReason":"xxx","id":4511,"email":""}] \ No newline at end of file diff --git a/frontend-js/testFiles/apiCalls/projects/sample/models/all/token=ADMIN_TOKEN_ID& b/frontend-js/testFiles/apiCalls/projects/sample/models/all/token=ADMIN_TOKEN_ID& new file mode 100644 index 0000000000000000000000000000000000000000..ffb8ec95f2a609c97a1b0d277e0062d9dea90941 --- /dev/null +++ b/frontend-js/testFiles/apiCalls/projects/sample/models/all/token=ADMIN_TOKEN_ID& @@ -0,0 +1 @@ +[{"version":null,"name":"UNKNOWN DISEASE MAP","idObject":15781,"tileSize":256,"width":1305,"height":473,"minZoom":2,"maxZoom":5,"layouts":[{"idObject":14081,"modelId":15781,"name":"Pathways and compartments","description":"","status":"Not available","progress":"0.00","directory":"5e8ff9bf55ba3508199d22e984129be6/_nested0","creator":"","inputDataAvailable":"false"},{"idObject":14082,"modelId":15781,"name":"Network","description":"","status":"Not available","progress":"0.00","directory":"5e8ff9bf55ba3508199d22e984129be6/_normal0","creator":"","inputDataAvailable":"false"},{"idObject":14083,"modelId":15781,"name":"Empty","description":"","status":"Not available","progress":"0.00","directory":"5e8ff9bf55ba3508199d22e984129be6/_empty0","creator":"","inputDataAvailable":"false"},{"idObject":18076,"modelId":15781,"name":"C:\\fakepath\\test.txt","description":"xxx","status":"OK","progress":"0.00","directory":"5e8ff9bf55ba3508199d22e984129be6/.18076","creator":"","inputDataAvailable":"true"},{"idObject":18077,"modelId":15781,"name":"xxx","description":"yyy","status":"OK","progress":"0.00","directory":"5e8ff9bf55ba3508199d22e984129be6/.18077","creator":"","inputDataAvailable":"true"}],"submodels":[],"centerLatLng":{"lat":79.18277721779353,"lng":-135.06093781915757},"topLeftLatLng":{"lat":85.05112877980659,"lng":-180.0},"bottomRightLatLng":{"lat":81.26928406550978,"lng":-90.0},"submodelType":"UNKNOWN"}] \ No newline at end of file diff --git a/frontend-js/testFiles/apiCalls/projects/sample/overlays/creator=admin&publicOverlay=false&token=ADMIN_TOKEN_ID& b/frontend-js/testFiles/apiCalls/projects/sample/overlays/creator=admin&publicOverlay=false&token=ADMIN_TOKEN_ID& new file mode 100644 index 0000000000000000000000000000000000000000..0637a088a01e8ddab3bf3fa98dbe804cbde1a0dc --- /dev/null +++ b/frontend-js/testFiles/apiCalls/projects/sample/overlays/creator=admin&publicOverlay=false&token=ADMIN_TOKEN_ID& @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/frontend-js/testFiles/apiCalls/projects/sample/token=ADMIN_TOKEN_ID& b/frontend-js/testFiles/apiCalls/projects/sample/token=ADMIN_TOKEN_ID& new file mode 100644 index 0000000000000000000000000000000000000000..38a0f6c48b9bb9bae48eb8c0a38f18777a7dc1af --- /dev/null +++ b/frontend-js/testFiles/apiCalls/projects/sample/token=ADMIN_TOKEN_ID& @@ -0,0 +1 @@ +{"version":"0","disease":{"resource":"D010300","link":"http://bioportal.bioontology.org/ontologies/1351?p=terms&conceptid=D010300","id":1104479,"type":"MESH_2012"},"organism":{"resource":"1570291","link":"http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=1570291","id":1104480,"type":"TAXONOMY"},"idObject":14898,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"sample","overviewImageViews":[],"topOverviewImage":null} \ No newline at end of file diff --git a/frontend-js/testFiles/apiCalls/projects/token=ADMIN_TOKEN_ID& b/frontend-js/testFiles/apiCalls/projects/token=ADMIN_TOKEN_ID& new file mode 100644 index 0000000000000000000000000000000000000000..fe4e68c75f98207df6f8eaf0124d21933d41e91a --- /dev/null +++ b/frontend-js/testFiles/apiCalls/projects/token=ADMIN_TOKEN_ID& @@ -0,0 +1 @@ +[{"version":"","disease":null,"organism":null,"idObject":16668,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"PD_150625_3","overviewImageViews":[],"topOverviewImage":null},{"version":"","disease":null,"organism":null,"idObject":15763,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"complex_model_with_submaps","overviewImageViews":[],"topOverviewImage":null},{"version":"","disease":null,"organism":null,"idObject":15764,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"pdmap_jun16_test","overviewImageViews":[],"topOverviewImage":null},{"version":"piotr.gawron@uni.lu","disease":null,"organism":null,"idObject":19184,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"restricted_sample","overviewImageViews":[],"topOverviewImage":null},{"version":"","disease":{"resource":"D010300","annotatorClassName":"","descriptionByTypeRelation":"","descriptionByType":"","link":"http://bioportal.bioontology.org/ontologies/1351?p=terms&conceptid=D010300","id":1097678,"type":"MESH_2012"},"organism":{"resource":"9606","annotatorClassName":"","descriptionByTypeRelation":"","descriptionByType":"","link":"http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=9606","id":1097679,"type":"TAXONOMY"},"idObject":18039,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"pdmap_jan17","overviewImageViews":[{"idObject":1246,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_apoptosis.png","width":5776,"height":4040,"links":[{"idObject":2315,"polygon":[{"x":5188.0,"y":107.0},{"x":5536.0,"y":107.0},{"x":5536.0,"y":245.0},{"x":5188.0,"y":245.0}],"zoomLevel":5,"latLng":{"lat":81.15295271480684,"lng":-149.45919107818048},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2316,"polygon":[{"x":2570.0,"y":842.0},{"x":3180.0,"y":842.0},{"x":3180.0,"y":1057.0},{"x":2570.0,"y":1057.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1247,"query":null,"type":"OverviewImageLink"},{"idObject":2323,"polygon":[{"x":4462.0,"y":107.0},{"x":4786.0,"y":107.0},{"x":4786.0,"y":245.0},{"x":4462.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2333,"polygon":[{"x":4852.0,"y":107.0},{"x":5125.0,"y":107.0},{"x":5125.0,"y":245.0},{"x":4852.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1252,"query":null,"type":"OverviewImageLink"}]},{"idObject":1247,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_autophagy.png","width":5776,"height":4040,"links":[{"idObject":2317,"polygon":[{"x":4852.0,"y":107.0},{"x":5125.0,"y":107.0},{"x":5125.0,"y":245.0},{"x":4852.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1246,"query":null,"type":"OverviewImageLink"},{"idObject":2318,"polygon":[{"x":5188.0,"y":107.0},{"x":5536.0,"y":107.0},{"x":5536.0,"y":245.0},{"x":5188.0,"y":245.0}],"zoomLevel":5,"latLng":{"lat":82.71201888475206,"lng":-127.60455257227972},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2324,"polygon":[{"x":4462.0,"y":107.0},{"x":4786.0,"y":107.0},{"x":4786.0,"y":245.0},{"x":4462.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"}]},{"idObject":1248,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_calcium.png","width":5776,"height":4040,"links":[{"idObject":2319,"polygon":[{"x":5188.0,"y":107.0},{"x":5536.0,"y":107.0},{"x":5536.0,"y":245.0},{"x":5188.0,"y":245.0}],"zoomLevel":6,"latLng":{"lat":84.66755120013883,"lng":-151.22598632700607},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2321,"polygon":[{"x":4462.0,"y":107.0},{"x":4786.0,"y":107.0},{"x":4786.0,"y":245.0},{"x":4462.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2334,"polygon":[{"x":4852.0,"y":107.0},{"x":5125.0,"y":107.0},{"x":5125.0,"y":245.0},{"x":4852.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1252,"query":null,"type":"OverviewImageLink"}]},{"idObject":1249,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_fission_fusion.png","width":5776,"height":4040,"links":[{"idObject":2320,"polygon":[{"x":5188.0,"y":107.0},{"x":5536.0,"y":107.0},{"x":5536.0,"y":245.0},{"x":5188.0,"y":245.0}],"zoomLevel":6,"latLng":{"lat":81.82366828255081,"lng":-147.1974181720964},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2322,"polygon":[{"x":4462.0,"y":107.0},{"x":4786.0,"y":107.0},{"x":4786.0,"y":245.0},{"x":4462.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2332,"polygon":[{"x":4852.0,"y":107.0},{"x":5125.0,"y":107.0},{"x":5125.0,"y":245.0},{"x":4852.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1252,"query":null,"type":"OverviewImageLink"},{"idObject":2342,"polygon":[{"x":4480.0,"y":3602.0},{"x":5092.0,"y":3602.0},{"x":5092.0,"y":3818.0},{"x":4480.0,"y":3818.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1253,"query":null,"type":"OverviewImageLink"},{"idObject":2347,"polygon":[{"x":3724.0,"y":3602.0},{"x":4336.0,"y":3602.0},{"x":4336.0,"y":3818.0},{"x":3724.0,"y":3818.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1254,"query":null,"type":"OverviewImageLink"}]},{"idObject":1250,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_main.png","width":5776,"height":4040,"links":[{"idObject":2325,"polygon":[{"x":515.0,"y":2187.0},{"x":1073.0,"y":2187.0},{"x":1073.0,"y":2520.0},{"x":515.0,"y":2520.0}],"zoomLevel":4,"latLng":{"lat":82.96608629587611,"lng":-168.0621013634801},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2326,"polygon":[{"x":2830.0,"y":497.0},{"x":3256.0,"y":497.0},{"x":3256.0,"y":832.0},{"x":2830.0,"y":832.0}],"zoomLevel":5,"latLng":{"lat":84.66946754404263,"lng":-152.22281633120727},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2327,"polygon":[{"x":4205.0,"y":761.0},{"x":4625.0,"y":761.0},{"x":4625.0,"y":1102.0},{"x":4205.0,"y":1102.0}],"zoomLevel":5,"latLng":{"lat":79.86247529282691,"lng":-154.2611618225566},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2331,"polygon":[{"x":2410.0,"y":1360.0},{"x":2692.0,"y":1360.0},{"x":2692.0,"y":1570.0},{"x":2410.0,"y":1570.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1252,"query":null,"type":"OverviewImageLink"},{"idObject":2349,"polygon":[{"x":3232.0,"y":2259.0},{"x":3520.0,"y":2259.0},{"x":3520.0,"y":2456.0},{"x":3232.0,"y":2456.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1254,"query":null,"type":"OverviewImageLink"},{"idObject":2356,"polygon":[{"x":4960.0,"y":1971.0},{"x":5241.0,"y":1971.0},{"x":5241.0,"y":2163.0},{"x":4960.0,"y":2163.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1255,"query":null,"type":"OverviewImageLink"}]},{"idObject":1251,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_main_root.png","width":5776,"height":4040,"links":[{"idObject":2328,"polygon":[{"x":515.0,"y":2187.0},{"x":1073.0,"y":2187.0},{"x":1073.0,"y":2520.0},{"x":515.0,"y":2520.0}],"zoomLevel":4,"latLng":{"lat":82.96608629587611,"lng":-168.0621013634801},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2329,"polygon":[{"x":2830.0,"y":497.0},{"x":3256.0,"y":497.0},{"x":3256.0,"y":832.0},{"x":2830.0,"y":832.0}],"zoomLevel":5,"latLng":{"lat":84.66946754404263,"lng":-152.22281633120727},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2330,"polygon":[{"x":4205.0,"y":761.0},{"x":4625.0,"y":761.0},{"x":4625.0,"y":1102.0},{"x":4205.0,"y":1102.0}],"zoomLevel":5,"latLng":{"lat":79.86247529282691,"lng":-154.2611618225566},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2335,"polygon":[{"x":2410.0,"y":1360.0},{"x":2692.0,"y":1360.0},{"x":2692.0,"y":1570.0},{"x":2410.0,"y":1570.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1252,"query":null,"type":"OverviewImageLink"},{"idObject":2348,"polygon":[{"x":3232.0,"y":2259.0},{"x":3520.0,"y":2259.0},{"x":3520.0,"y":2456.0},{"x":3232.0,"y":2456.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1254,"query":null,"type":"OverviewImageLink"},{"idObject":2357,"polygon":[{"x":4960.0,"y":1971.0},{"x":5241.0,"y":1971.0},{"x":5241.0,"y":2163.0},{"x":4960.0,"y":2163.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1255,"query":null,"type":"OverviewImageLink"}]},{"idObject":1252,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_mitochondrion.png","width":5776,"height":4040,"links":[{"idObject":2336,"polygon":[{"x":4462.0,"y":107.0},{"x":4786.0,"y":107.0},{"x":4786.0,"y":245.0},{"x":4462.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2337,"polygon":[{"x":4852.0,"y":107.0},{"x":5125.0,"y":107.0},{"x":5125.0,"y":245.0},{"x":4852.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2338,"polygon":[{"x":5188.0,"y":107.0},{"x":5536.0,"y":107.0},{"x":5536.0,"y":245.0},{"x":5188.0,"y":245.0}],"zoomLevel":5,"latLng":{"lat":82.8877844915633,"lng":-148.79922086850246},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2339,"polygon":[{"x":2453.0,"y":107.0},{"x":3178.0,"y":107.0},{"x":3178.0,"y":329.0},{"x":2453.0,"y":329.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1246,"query":null,"type":"OverviewImageLink"},{"idObject":2340,"polygon":[{"x":1049.0,"y":3716.0},{"x":1835.0,"y":3716.0},{"x":1835.0,"y":3932.0},{"x":1049.0,"y":3932.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1249,"query":null,"type":"OverviewImageLink"},{"idObject":2341,"polygon":[{"x":221.0,"y":1804.0},{"x":1097.0,"y":1804.0},{"x":1097.0,"y":2014.0},{"x":221.0,"y":2014.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1248,"query":null,"type":"OverviewImageLink"},{"idObject":2343,"polygon":[{"x":4876.0,"y":1804.0},{"x":5542.0,"y":1804.0},{"x":5542.0,"y":2014.0},{"x":4876.0,"y":2014.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1253,"query":null,"type":"OverviewImageLink"},{"idObject":2350,"polygon":[{"x":4144.0,"y":3716.0},{"x":4816.0,"y":3716.0},{"x":4816.0,"y":3932.0},{"x":4144.0,"y":3932.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1254,"query":null,"type":"OverviewImageLink"}]},{"idObject":1253,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_mitophagy.png","width":5776,"height":4040,"links":[{"idObject":2344,"polygon":[{"x":4462.0,"y":107.0},{"x":4786.0,"y":107.0},{"x":4786.0,"y":245.0},{"x":4462.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2345,"polygon":[{"x":4852.0,"y":107.0},{"x":5125.0,"y":107.0},{"x":5125.0,"y":245.0},{"x":4852.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1252,"query":null,"type":"OverviewImageLink"},{"idObject":2346,"polygon":[{"x":5188.0,"y":107.0},{"x":5536.0,"y":107.0},{"x":5536.0,"y":245.0},{"x":5188.0,"y":245.0}],"zoomLevel":6,"latLng":{"lat":82.23724412618809,"lng":-133.40335332085704},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"}]},{"idObject":1254,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_motility.png","width":5776,"height":4040,"links":[{"idObject":2351,"polygon":[{"x":4462.0,"y":107.0},{"x":4786.0,"y":107.0},{"x":4786.0,"y":245.0},{"x":4462.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2352,"polygon":[{"x":4852.0,"y":107.0},{"x":5125.0,"y":107.0},{"x":5125.0,"y":245.0},{"x":4852.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1252,"query":null,"type":"OverviewImageLink"},{"idObject":2353,"polygon":[{"x":5188.0,"y":107.0},{"x":5536.0,"y":107.0},{"x":5536.0,"y":245.0},{"x":5188.0,"y":245.0}],"zoomLevel":5,"latLng":{"lat":84.3906903162654,"lng":-127.5186189512279},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2354,"polygon":[{"x":311.0,"y":1234.0},{"x":935.0,"y":1234.0},{"x":935.0,"y":1462.0},{"x":311.0,"y":1462.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2355,"polygon":[{"x":4894.0,"y":2283.0},{"x":5512.0,"y":2283.0},{"x":5512.0,"y":2511.0},{"x":4894.0,"y":2511.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1255,"query":null,"type":"OverviewImageLink"}]},{"idObject":1255,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_synapse.png","width":5776,"height":4040,"links":[{"idObject":2358,"polygon":[{"x":4462.0,"y":107.0},{"x":4786.0,"y":107.0},{"x":4786.0,"y":245.0},{"x":4462.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2359,"polygon":[{"x":4852.0,"y":107.0},{"x":5125.0,"y":107.0},{"x":5125.0,"y":245.0},{"x":4852.0,"y":245.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1250,"query":null,"type":"OverviewImageLink"},{"idObject":2360,"polygon":[{"x":5188.0,"y":107.0},{"x":5536.0,"y":107.0},{"x":5536.0,"y":245.0},{"x":5188.0,"y":245.0}],"zoomLevel":5,"latLng":{"lat":82.66652910471382,"lng":-104.28904250849789},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2361,"polygon":[{"x":3352.0,"y":107.0},{"x":3970.0,"y":107.0},{"x":3970.0,"y":335.0},{"x":3352.0,"y":335.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1254,"query":null,"type":"OverviewImageLink"}]}],"topOverviewImage":{"idObject":1251,"filename":"a74b75289e6162e9cd1d41104797e361/biolayout_main_root.png","width":5776,"height":4040,"links":[{"idObject":2328,"polygon":[{"x":515.0,"y":2187.0},{"x":1073.0,"y":2187.0},{"x":1073.0,"y":2520.0},{"x":515.0,"y":2520.0}],"zoomLevel":4,"latLng":{"lat":82.96608629587611,"lng":-168.0621013634801},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2329,"polygon":[{"x":2830.0,"y":497.0},{"x":3256.0,"y":497.0},{"x":3256.0,"y":832.0},{"x":2830.0,"y":832.0}],"zoomLevel":5,"latLng":{"lat":84.66946754404263,"lng":-152.22281633120727},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2330,"polygon":[{"x":4205.0,"y":761.0},{"x":4625.0,"y":761.0},{"x":4625.0,"y":1102.0},{"x":4205.0,"y":1102.0}],"zoomLevel":5,"latLng":{"lat":79.86247529282691,"lng":-154.2611618225566},"modelLinkId":19308,"imageLinkId":null,"query":null,"type":"OverviewModelLink"},{"idObject":2335,"polygon":[{"x":2410.0,"y":1360.0},{"x":2692.0,"y":1360.0},{"x":2692.0,"y":1570.0},{"x":2410.0,"y":1570.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1252,"query":null,"type":"OverviewImageLink"},{"idObject":2348,"polygon":[{"x":3232.0,"y":2259.0},{"x":3520.0,"y":2259.0},{"x":3520.0,"y":2456.0},{"x":3232.0,"y":2456.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1254,"query":null,"type":"OverviewImageLink"},{"idObject":2357,"polygon":[{"x":4960.0,"y":1971.0},{"x":5241.0,"y":1971.0},{"x":5241.0,"y":2163.0},{"x":4960.0,"y":2163.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1255,"query":null,"type":"OverviewImageLink"}]}},{"version":"","disease":null,"organism":null,"idObject":18115,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"complex_model_with_images","overviewImageViews":[{"idObject":1261,"filename":"fbdbe43de73fe38f62889b89cb863adb/sub_image.png","width":963,"height":639,"links":[{"idObject":2369,"polygon":[{"x":200.0,"y":200.0},{"x":200.0,"y":400.0},{"x":400.0,"y":400.0},{"x":400.0,"y":200.0}],"zoomLevel":1,"latLng":{"lat":84.89177465079632,"lng":-161.8181818181818},"modelLinkId":19397,"imageLinkId":null,"query":null,"type":"OverviewModelLink"}]},{"idObject":1262,"filename":"fbdbe43de73fe38f62889b89cb863adb/test.png","width":963,"height":639,"links":[{"idObject":2370,"polygon":[{"x":10.0,"y":10.0},{"x":100.0,"y":10.0},{"x":100.0,"y":100.0},{"x":10.0,"y":100.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1261,"query":null,"type":"OverviewImageLink"},{"idObject":2371,"polygon":[{"x":200.0,"y":200.0},{"x":200.0,"y":400.0},{"x":400.0,"y":400.0},{"x":400.0,"y":200.0}],"zoomLevel":0,"latLng":{"lat":84.89177465079632,"lng":-178.1818181818182},"modelLinkId":19397,"imageLinkId":null,"query":null,"type":"OverviewModelLink"}]}],"topOverviewImage":{"idObject":1262,"filename":"fbdbe43de73fe38f62889b89cb863adb/test.png","width":963,"height":639,"links":[{"idObject":2370,"polygon":[{"x":10.0,"y":10.0},{"x":100.0,"y":10.0},{"x":100.0,"y":100.0},{"x":10.0,"y":100.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1261,"query":null,"type":"OverviewImageLink"},{"idObject":2371,"polygon":[{"x":200.0,"y":200.0},{"x":200.0,"y":400.0},{"x":400.0,"y":400.0},{"x":400.0,"y":200.0}],"zoomLevel":0,"latLng":{"lat":84.89177465079632,"lng":-178.1818181818182},"modelLinkId":19397,"imageLinkId":null,"query":null,"type":"OverviewModelLink"}]}},{"version":"","disease":{"resource":"D010300","annotatorClassName":"","descriptionByTypeRelation":"","descriptionByType":"","link":"http://bioportal.bioontology.org/ontologies/1351?p=terms&conceptid=D010300","id":933416,"type":"MESH_2012"},"organism":null,"idObject":17051,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"GSTP1_subnetwork_220214","overviewImageViews":[],"topOverviewImage":null},{"version":"","disease":null,"organism":null,"idObject":19103,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"CDlayerin_v2-semantic","overviewImageViews":[],"topOverviewImage":null},{"version":"piotr.gawron@uni.lu","disease":null,"organism":{"resource":"9606","annotatorClassName":"","descriptionByTypeRelation":"","descriptionByType":"","link":"http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=9606","id":1104514,"type":"TAXONOMY"},"idObject":19186,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"drug_target_sample","overviewImageViews":[],"topOverviewImage":null},{"version":"piotr.gawron@uni.lu","disease":null,"organism":null,"idObject":19187,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"empty","overviewImageViews":[],"topOverviewImage":null},{"version":"23","disease":{"resource":"D000544","annotatorClassName":"","descriptionByTypeRelation":"","descriptionByType":"","link":"http://bioportal.bioontology.org/ontologies/1351?p=terms&conceptid=D000544","id":1113075,"type":"MESH_2012"},"organism":{"resource":"9606","annotatorClassName":"","descriptionByTypeRelation":"","descriptionByType":"","link":"http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=9606","id":1113076,"type":"TAXONOMY"},"idObject":19102,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"xxx","projectId":"CDlayerin_v2","overviewImageViews":[],"topOverviewImage":null},{"version":null,"disease":null,"organism":null,"idObject":20604,"status":"Ok","progress":100.0,"notifyEmail":null,"warnings":true,"errors":false,"name":"test","projectId":"xxx","overviewImageViews":[],"topOverviewImage":null},{"version":null,"disease":null,"organism":null,"idObject":20603,"status":"Ok","progress":100.0,"notifyEmail":null,"warnings":true,"errors":false,"name":"test","projectId":"xxxy","overviewImageViews":[],"topOverviewImage":null},{"version":null,"disease":null,"organism":null,"idObject":20620,"status":"Ok","progress":100.0,"notifyEmail":"piotr.gawron@uni.lu","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"complex_model_with_layouts","overviewImageViews":[],"topOverviewImage":null},{"version":"0","disease":{"resource":"D010300","annotatorClassName":"","descriptionByTypeRelation":"","descriptionByType":"","link":"http://bioportal.bioontology.org/ontologies/1351?p=terms&conceptid=D010300","id":1104479,"type":"MESH_2012"},"organism":{"resource":"1570291","annotatorClassName":"","descriptionByTypeRelation":"","descriptionByType":"","link":"http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=1570291","id":1104480,"type":"TAXONOMY"},"idObject":14898,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"sample","overviewImageViews":[],"topOverviewImage":null},{"version":null,"disease":null,"organism":null,"idObject":20812,"status":"Ok","progress":100.0,"notifyEmail":"piotr.gawron@uni.lu","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"images","overviewImageViews":[{"idObject":1396,"filename":"6c06cbfd0b675f7b5ab0dd188d3ff4ef/sub_image.png","width":963,"height":639,"links":[{"idObject":2565,"polygon":[{"x":200.0,"y":200.0},{"x":200.0,"y":400.0},{"x":400.0,"y":400.0},{"x":400.0,"y":200.0}],"zoomLevel":1,"latLng":{"lat":84.89177465079632,"lng":-161.8181818181818},"modelLinkId":22341,"imageLinkId":null,"query":null,"type":"OverviewModelLink"}]},{"idObject":1397,"filename":"6c06cbfd0b675f7b5ab0dd188d3ff4ef/test.png","width":963,"height":639,"links":[{"idObject":2566,"polygon":[{"x":10.0,"y":10.0},{"x":100.0,"y":10.0},{"x":100.0,"y":100.0},{"x":10.0,"y":100.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1396,"query":null,"type":"OverviewImageLink"},{"idObject":2567,"polygon":[{"x":200.0,"y":200.0},{"x":200.0,"y":400.0},{"x":400.0,"y":400.0},{"x":400.0,"y":200.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":null,"query":"s1","type":"OverviewSearchLink"}]}],"topOverviewImage":{"idObject":1397,"filename":"6c06cbfd0b675f7b5ab0dd188d3ff4ef/test.png","width":963,"height":639,"links":[{"idObject":2566,"polygon":[{"x":10.0,"y":10.0},{"x":100.0,"y":10.0},{"x":100.0,"y":100.0},{"x":10.0,"y":100.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":1396,"query":null,"type":"OverviewImageLink"},{"idObject":2567,"polygon":[{"x":200.0,"y":200.0},{"x":200.0,"y":400.0},{"x":400.0,"y":400.0},{"x":400.0,"y":200.0}],"zoomLevel":null,"latLng":null,"modelLinkId":null,"imageLinkId":null,"query":"s1","type":"OverviewSearchLink"}]}},{"version":null,"disease":null,"organism":null,"idObject":21113,"status":"Ok","progress":100.0,"notifyEmail":"piotr.gawron@uni.lu","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"doi","overviewImageViews":[],"topOverviewImage":null},{"version":null,"disease":null,"organism":null,"idObject":21417,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":false,"errors":false,"name":"","projectId":"parameter","overviewImageViews":[],"topOverviewImage":null},{"version":null,"disease":null,"organism":null,"idObject":21424,"status":"Ok","progress":100.0,"notifyEmail":"piotr.gawron@uni.lu","warnings":false,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"kinteics_test","overviewImageViews":[],"topOverviewImage":null},{"version":"","disease":null,"organism":null,"idObject":21966,"status":"Ok","progress":100.0,"notifyEmail":"piotr.gawron@uni.lu","warnings":false,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"c","overviewImageViews":[],"topOverviewImage":null},{"version":"","disease":null,"organism":null,"idObject":21968,"status":"Ok","progress":100.0,"notifyEmail":"piotr.gawron@uni.lu","warnings":true,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"ASTHMA_V40_Test9x","overviewImageViews":[],"topOverviewImage":null},{"version":"","disease":null,"organism":{"resource":"9606","annotatorClassName":"","descriptionByTypeRelation":"","descriptionByType":"","link":"http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=9606","id":1119594,"type":"TAXONOMY"},"idObject":21430,"status":"Ok","progress":100.0,"notifyEmail":"piotr.gawron@uni.lu","warnings":false,"errors":false,"name":"UNKNOWN DISEASE MAP","projectId":"ASTHMA_V40_Test9","overviewImageViews":[],"topOverviewImage":null},{"version":null,"disease":null,"organism":null,"idObject":21432,"status":"Ok","progress":100.0,"notifyEmail":"","warnings":false,"errors":false,"name":"","projectId":"species_with_boundary_cond","overviewImageViews":[],"topOverviewImage":null}] \ No newline at end of file diff --git a/frontend-js/testFiles/apiCalls/users/admin b/frontend-js/testFiles/apiCalls/users/admin deleted file mode 100644 index 7a0b8dd1ba308982491eb54f25b8e0c27708a0c2..0000000000000000000000000000000000000000 --- a/frontend-js/testFiles/apiCalls/users/admin +++ /dev/null @@ -1 +0,0 @@ -{"simpleColor":null,"privileges":[{"type":"VIEW_PROJECT","value":1,"objectId":14898},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19103},{"type":"ADD_MAP","value":1},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":15764},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19184},{"type":"VIEW_PROJECT","value":1,"objectId":6},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":17051},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19102},{"type":"VIEW_PROJECT","value":1,"objectId":21113},{"type":"VIEW_PROJECT","value":1,"objectId":19187},{"type":"VIEW_PROJECT","value":1,"objectId":16668},{"type":"VIEW_PROJECT","value":1,"objectId":18115},{"type":"VIEW_PROJECT","value":1,"objectId":18039},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":14898},{"type":"VIEW_PROJECT","value":1,"objectId":20},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":6},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15763},{"type":"VIEW_PROJECT","value":1,"objectId":20620},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":14898},{"type":"VIEW_PROJECT","value":1,"objectId":19},{"type":"CUSTOM_LAYOUTS","value":100},{"type":"MANAGE_GENOMES","value":1},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20812},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":10},{"type":"VIEW_PROJECT","value":1,"objectId":21417},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21},{"type":"VIEW_PROJECT","value":1,"objectId":22},{"type":"VIEW_PROJECT","value":1,"objectId":20605},{"type":"VIEW_PROJECT","value":1,"objectId":9},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21113},{"type":"VIEW_PROJECT","value":1,"objectId":17},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18039},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19186},{"type":"USER_MANAGEMENT","value":1},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":11},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20603},{"type":"VIEW_PROJECT","value":1,"objectId":1},{"type":"VIEW_PROJECT","value":1,"objectId":18},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21424},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19103},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21432},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20603},{"type":"VIEW_PROJECT","value":1,"objectId":15764},{"type":"VIEW_PROJECT","value":1,"objectId":19103},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21417},{"type":"VIEW_PROJECT","value":1,"objectId":15763},{"type":"PROJECT_MANAGEMENT","value":1},{"type":"VIEW_PROJECT","value":1,"objectId":21424},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21430},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":16668},{"type":"VIEW_PROJECT","value":1,"objectId":11},{"type":"VIEW_PROJECT","value":1,"objectId":17051},{"type":"CONFIGURATION_MANAGE","value":1},{"type":"VIEW_PROJECT","value":1,"objectId":21},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":19187},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":22},{"type":"VIEW_PROJECT","value":1,"objectId":10},{"type":"VIEW_PROJECT","value":1,"objectId":20812},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":1},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20620},{"type":"VIEW_PROJECT","value":1,"objectId":21430},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20620},{"type":"VIEW_PROJECT","value":1,"objectId":8},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15764},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":7},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21430},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":18},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21424},{"type":"VIEW_PROJECT","value":1,"objectId":20603},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20812},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":18115},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20605},{"type":"VIEW_PROJECT","value":1,"objectId":20604},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21432},{"type":"VIEW_PROJECT","value":1,"objectId":21432},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":16668},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":9},{"type":"VIEW_PROJECT","value":1,"objectId":7},{"type":"VIEW_PROJECT","value":1,"objectId":19184},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19186},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":18039},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":8},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20604},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":17051},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21417},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20605},{"type":"VIEW_PROJECT","value":1,"objectId":19186},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":19102},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19184},{"type":"VIEW_PROJECT","value":1,"objectId":19102},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20604},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21113},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18115},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":15763},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19187},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":17},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20},{"type":"VIEW_PROJECT","value":1,"objectId":null},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":null},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":null},{"type":"CUSTOM_LAYOUTS_AVAILABLE","value":86}],"preferences":{"element-required-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Chemical":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM","PUBCHEM_SUBSTANCE"]},"lcsb.mapviewer.model.map.species.Degraded":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.PathwayCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.SimpleMolecule":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM","PUBCHEM_SUBSTANCE"]},"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.ReceptorProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Gene":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.compartment.OvalCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Protein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.BioEntity":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.GenericProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.TransportReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.IonChannelProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Phenotype":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Drug":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Element":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.SquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Ion":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM","PUBCHEM_SUBSTANCE"]},"lcsb.mapviewer.model.map.reaction.Reaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.AntisenseRna":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Complex":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Unknown":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.TruncatedProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL","CHEMBL_COMPOUND"]},"lcsb.mapviewer.model.map.compartment.Compartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Species":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Rna":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]}},"element-valid-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Chemical":["CHEBI","HMDB","KEGG_COMPOUND","PUBCHEM","PUBCHEM_SUBSTANCE","PUBMED"],"lcsb.mapviewer.model.map.species.Degraded":["PUBMED"],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["CHEBI","HMDB","KEGG_COMPOUND","PUBCHEM","PUBCHEM_SUBSTANCE","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.ReceptorProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Gene":["ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Protein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM","CHEMBL_COMPOUND"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.BioEntity":["PUBMED"],"lcsb.mapviewer.model.map.species.GenericProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.IonChannelProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Phenotype":["GO","MESH_2012","OMIM","PUBMED"],"lcsb.mapviewer.model.map.species.Drug":["CHEBI","CHEMBL_COMPOUND","DRUGBANK","HMDB","PUBMED"],"lcsb.mapviewer.model.map.species.Element":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.Ion":["CHEBI","HMDB","KEGG_COMPOUND","PUBCHEM","PUBCHEM_SUBSTANCE","PUBMED"],"lcsb.mapviewer.model.map.reaction.Reaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.AntisenseRna":["PUBMED"],"lcsb.mapviewer.model.map.species.Complex":["CHEMBL_TARGET","EC","GO","INTERPRO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.Unknown":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.TruncatedProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM","CHEMBL_COMPOUND"],"lcsb.mapviewer.model.map.compartment.Compartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.Species":["PUBMED"],"lcsb.mapviewer.model.map.species.Rna":["ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"]},"element-annotators":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":[],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.species.Chemical":["Chebi"],"lcsb.mapviewer.model.map.species.Degraded":[],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["Chebi"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":[],"lcsb.mapviewer.model.map.species.ReceptorProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":[],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":[],"lcsb.mapviewer.model.map.species.Gene":["HGNC"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":[],"lcsb.mapviewer.model.map.species.Protein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.BioEntity":[],"lcsb.mapviewer.model.map.species.GenericProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":[],"lcsb.mapviewer.model.map.species.IonChannelProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.Phenotype":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Drug":[],"lcsb.mapviewer.model.map.species.Element":[],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":[],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Ion":["Chebi"],"lcsb.mapviewer.model.map.reaction.Reaction":[],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":[],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":[],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.AntisenseRna":[],"lcsb.mapviewer.model.map.species.Complex":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Unknown":[],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":[],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.species.TruncatedProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.compartment.Compartment":["Gene Ontology"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Species":[],"lcsb.mapviewer.model.map.species.Rna":["HGNC"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":[],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":[]},"project-upload":{"auto-resize":true,"sbgn":false,"cache-data":false,"semantic-zooming":false,"annotate-model":false,"validate-miriam":true}},"removed":false,"surname":"","minColor":null,"name":"admin","neutralColor":null,"maxColor":null,"id":1,"login":"admin","email":"piotr.gawron@uni.lu"} \ No newline at end of file diff --git a/frontend-js/testFiles/apiCalls/users/admin.updatePreferences/PATCH_preferences.project-upload.cache-data=false& b/frontend-js/testFiles/apiCalls/users/admin.updatePreferences/PATCH_preferences.project-upload.cache-data=false&token=ADMIN_TOKEN_ID& similarity index 100% rename from frontend-js/testFiles/apiCalls/users/admin.updatePreferences/PATCH_preferences.project-upload.cache-data=false& rename to frontend-js/testFiles/apiCalls/users/admin.updatePreferences/PATCH_preferences.project-upload.cache-data=false&token=ADMIN_TOKEN_ID& diff --git a/frontend-js/testFiles/apiCalls/users/admin.updatePreferences/PATCH_preferences.project-upload.cache-data=true& b/frontend-js/testFiles/apiCalls/users/admin.updatePreferences/PATCH_preferences.project-upload.cache-data=true&token=ADMIN_TOKEN_ID& similarity index 100% rename from frontend-js/testFiles/apiCalls/users/admin.updatePreferences/PATCH_preferences.project-upload.cache-data=true& rename to frontend-js/testFiles/apiCalls/users/admin.updatePreferences/PATCH_preferences.project-upload.cache-data=true&token=ADMIN_TOKEN_ID& diff --git a/frontend-js/testFiles/apiCalls/users/admin/token=ADMIN_TOKEN_ID& b/frontend-js/testFiles/apiCalls/users/admin/token=ADMIN_TOKEN_ID& new file mode 100644 index 0000000000000000000000000000000000000000..80096aa952929921481b9b13e84284e6836695d7 --- /dev/null +++ b/frontend-js/testFiles/apiCalls/users/admin/token=ADMIN_TOKEN_ID& @@ -0,0 +1 @@ +{"simpleColor":null,"privileges":[{"type":"VIEW_PROJECT","value":1,"objectId":21424},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21432},{"type":"VIEW_PROJECT","value":1,"objectId":21432},{"type":"VIEW_PROJECT","value":1,"objectId":21113},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":7},{"type":"VIEW_PROJECT","value":1,"objectId":6},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19186},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21424},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":15764},{"type":"PROJECT_MANAGEMENT","value":1},{"type":"ADD_MAP","value":1},{"type":"VIEW_PROJECT","value":1,"objectId":15764},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21113},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19103},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15763},{"type":"VIEW_PROJECT","value":1,"objectId":19186},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":6},{"type":"VIEW_PROJECT","value":1,"objectId":1},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21968},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21968},{"type":"VIEW_PROJECT","value":1,"objectId":9},{"type":"VIEW_PROJECT","value":1,"objectId":17051},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":19187},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19184},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21424},{"type":"VIEW_PROJECT","value":1,"objectId":21417},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18039},{"type":"VIEW_PROJECT","value":1,"objectId":10},{"type":"VIEW_PROJECT","value":1,"objectId":19184},{"type":"VIEW_PROJECT","value":1,"objectId":20604},{"type":"VIEW_PROJECT","value":1,"objectId":21},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19187},{"type":"VIEW_PROJECT","value":1,"objectId":19103},{"type":"VIEW_PROJECT","value":1,"objectId":20},{"type":"VIEW_PROJECT","value":1,"objectId":21430},{"type":"VIEW_PROJECT","value":1,"objectId":20812},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19184},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21432},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":17},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20620},{"type":"VIEW_PROJECT","value":1,"objectId":19},{"type":"VIEW_PROJECT","value":1,"objectId":22},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":1},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21},{"type":"VIEW_PROJECT","value":1,"objectId":19102},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20603},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20620},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21966},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":19102},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":18115},{"type":"VIEW_PROJECT","value":1,"objectId":8},{"type":"VIEW_PROJECT","value":1,"objectId":15763},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15764},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":9},{"type":"CONFIGURATION_MANAGE","value":1},{"type":"VIEW_PROJECT","value":1,"objectId":21968},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":18039},{"type":"VIEW_PROJECT","value":1,"objectId":11},{"type":"VIEW_PROJECT","value":1,"objectId":18},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20812},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":11},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":14898},{"type":"VIEW_PROJECT","value":1,"objectId":21966},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":17051},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20812},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":17051},{"type":"VIEW_PROJECT","value":1,"objectId":17},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21417},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21113},{"type":"USER_MANAGEMENT","value":1},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":22},{"type":"VIEW_PROJECT","value":1,"objectId":16668},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21430},{"type":"VIEW_PROJECT","value":1,"objectId":14898},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20604},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19103},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":8},{"type":"VIEW_PROJECT","value":1,"objectId":19187},{"type":"CUSTOM_LAYOUTS","value":100},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21430},{"type":"VIEW_PROJECT","value":1,"objectId":18115},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":18},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":16668},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18115},{"type":"VIEW_PROJECT","value":1,"objectId":20620},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20603},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20604},{"type":"MANAGE_GENOMES","value":1},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":14898},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":16668},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21966},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21417},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19186},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":15763},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":10},{"type":"VIEW_PROJECT","value":1,"objectId":18039},{"type":"VIEW_PROJECT","value":1,"objectId":7},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19102},{"type":"VIEW_PROJECT","value":1,"objectId":20603},{"type":"VIEW_PROJECT","value":1,"objectId":null},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":null},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":null},{"type":"CUSTOM_LAYOUTS_AVAILABLE","value":86}],"preferences":{"element-required-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Chemical":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM","PUBCHEM_SUBSTANCE"]},"lcsb.mapviewer.model.map.species.Degraded":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.PathwayCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.SimpleMolecule":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM","PUBCHEM_SUBSTANCE"]},"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.ReceptorProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Gene":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.compartment.OvalCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Protein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.BioEntity":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.GenericProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.TransportReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.IonChannelProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Phenotype":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Drug":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Element":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.SquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Ion":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM","PUBCHEM_SUBSTANCE"]},"lcsb.mapviewer.model.map.reaction.Reaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.AntisenseRna":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Complex":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Unknown":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.TruncatedProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL","CHEMBL_COMPOUND"]},"lcsb.mapviewer.model.map.compartment.Compartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Species":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Rna":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]}},"element-valid-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Chemical":["CHEBI","HMDB","KEGG_COMPOUND","PUBCHEM","PUBCHEM_SUBSTANCE","PUBMED"],"lcsb.mapviewer.model.map.species.Degraded":["PUBMED"],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["CHEBI","HMDB","KEGG_COMPOUND","PUBCHEM","PUBCHEM_SUBSTANCE","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.ReceptorProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Gene":["ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Protein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM","CHEMBL_COMPOUND"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.BioEntity":["PUBMED"],"lcsb.mapviewer.model.map.species.GenericProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.IonChannelProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Phenotype":["GO","MESH_2012","OMIM","PUBMED"],"lcsb.mapviewer.model.map.species.Drug":["CHEBI","CHEMBL_COMPOUND","DRUGBANK","HMDB","PUBMED"],"lcsb.mapviewer.model.map.species.Element":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.Ion":["CHEBI","HMDB","KEGG_COMPOUND","PUBCHEM","PUBCHEM_SUBSTANCE","PUBMED"],"lcsb.mapviewer.model.map.reaction.Reaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.AntisenseRna":["PUBMED"],"lcsb.mapviewer.model.map.species.Complex":["CHEMBL_TARGET","EC","GO","INTERPRO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.Unknown":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.TruncatedProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM","CHEMBL_COMPOUND"],"lcsb.mapviewer.model.map.compartment.Compartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.Species":["PUBMED"],"lcsb.mapviewer.model.map.species.Rna":["ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"]},"element-annotators":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":[],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.species.Chemical":["Chebi"],"lcsb.mapviewer.model.map.species.Degraded":[],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["Chebi"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":[],"lcsb.mapviewer.model.map.species.ReceptorProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":[],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":[],"lcsb.mapviewer.model.map.species.Gene":["HGNC"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":[],"lcsb.mapviewer.model.map.species.Protein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.BioEntity":[],"lcsb.mapviewer.model.map.species.GenericProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":[],"lcsb.mapviewer.model.map.species.IonChannelProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.Phenotype":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Drug":[],"lcsb.mapviewer.model.map.species.Element":[],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":[],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Ion":["Chebi"],"lcsb.mapviewer.model.map.reaction.Reaction":[],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":[],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":[],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.AntisenseRna":[],"lcsb.mapviewer.model.map.species.Complex":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Unknown":[],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":[],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.species.TruncatedProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.compartment.Compartment":["Gene Ontology"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Species":[],"lcsb.mapviewer.model.map.species.Rna":["HGNC"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":[],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":[]},"project-upload":{"auto-resize":true,"sbgn":false,"cache-data":false,"semantic-zooming":false,"annotate-model":false,"validate-miriam":true},"annotators-parameters":{}},"removed":false,"surname":"","minColor":null,"name":"admin","neutralColor":null,"maxColor":null,"id":1,"login":"admin","email":"piotr.gawron@uni.lu"} \ No newline at end of file diff --git a/frontend-js/testFiles/apiCalls/users/token=ADMIN_TOKEN_ID& b/frontend-js/testFiles/apiCalls/users/token=ADMIN_TOKEN_ID& new file mode 100644 index 0000000000000000000000000000000000000000..276e2108f44e6b7001d1f44197a64847a012ff39 --- /dev/null +++ b/frontend-js/testFiles/apiCalls/users/token=ADMIN_TOKEN_ID& @@ -0,0 +1 @@ +[{"simpleColor":null,"privileges":[{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19184},{"type":"VIEW_PROJECT","value":0,"objectId":19184},{"type":"VIEW_PROJECT","value":1,"objectId":21432},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21968},{"type":"VIEW_PROJECT","value":1,"objectId":16668},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":18039},{"type":"VIEW_PROJECT","value":1,"objectId":18},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":17051},{"type":"USER_MANAGEMENT","value":0},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19102},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21966},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":16668},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19187},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19103},{"type":"VIEW_PROJECT","value":1,"objectId":19103},{"type":"VIEW_PROJECT","value":1,"objectId":19},{"type":"VIEW_PROJECT","value":1,"objectId":21113},{"type":"ADD_MAP","value":0},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":21968},{"type":"VIEW_PROJECT","value":1,"objectId":9},{"type":"VIEW_PROJECT","value":1,"objectId":11},{"type":"CUSTOM_LAYOUTS","value":0},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":14898},{"type":"VIEW_PROJECT","value":1,"objectId":20812},{"type":"VIEW_PROJECT","value":1,"objectId":7},{"type":"CONFIGURATION_MANAGE","value":0},{"type":"MANAGE_GENOMES","value":1},{"type":"VIEW_PROJECT","value":1,"objectId":21417},{"type":"VIEW_PROJECT","value":1,"objectId":20},{"type":"VIEW_PROJECT","value":1,"objectId":22},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19102},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18039},{"type":"VIEW_PROJECT","value":1,"objectId":14898},{"type":"VIEW_PROJECT","value":1,"objectId":21},{"type":"VIEW_PROJECT","value":1,"objectId":10},{"type":"VIEW_PROJECT","value":1,"objectId":20604},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15764},{"type":"VIEW_PROJECT","value":1,"objectId":1},{"type":"VIEW_PROJECT","value":1,"objectId":17051},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":15763},{"type":"VIEW_PROJECT","value":1,"objectId":21424},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":16668},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19186},{"type":"VIEW_PROJECT","value":1,"objectId":8},{"type":"VIEW_PROJECT","value":1,"objectId":19102},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19184},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":17051},{"type":"VIEW_PROJECT","value":1,"objectId":15763},{"type":"VIEW_PROJECT","value":1,"objectId":18305},{"type":"VIEW_PROJECT","value":1,"objectId":18115},{"type":"VIEW_PROJECT","value":1,"objectId":20620},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":18115},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":15764},{"type":"VIEW_PROJECT","value":1,"objectId":18039},{"type":"VIEW_PROJECT","value":1,"objectId":19187},{"type":"PROJECT_MANAGEMENT","value":0},{"type":"VIEW_PROJECT","value":1,"objectId":21430},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19186},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15763},{"type":"VIEW_PROJECT","value":1,"objectId":17},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19187},{"type":"VIEW_PROJECT","value":1,"objectId":19186},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":14898},{"type":"VIEW_PROJECT","value":1,"objectId":6},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":21966},{"type":"VIEW_PROJECT","value":1,"objectId":21968},{"type":"VIEW_PROJECT","value":1,"objectId":15764},{"type":"VIEW_PROJECT","value":1,"objectId":20603},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18115},{"type":"VIEW_PROJECT","value":1,"objectId":21966},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19103},{"type":"VIEW_PROJECT","value":1,"objectId":null},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":null},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":null},{"type":"CUSTOM_LAYOUTS_AVAILABLE","value":0}],"preferences":{"element-required-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Chemical":{"require-at-least-one":true,"annotation-list":["PUBCHEM_SUBSTANCE","PUBCHEM","CHEBI"]},"lcsb.mapviewer.model.map.species.Degraded":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.PathwayCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.SimpleMolecule":{"require-at-least-one":true,"annotation-list":["PUBCHEM_SUBSTANCE","PUBCHEM","CHEBI"]},"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.ReceptorProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Gene":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.compartment.OvalCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Protein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.BioEntity":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.GenericProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.TransportReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.IonChannelProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Phenotype":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Drug":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Element":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.SquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Ion":{"require-at-least-one":true,"annotation-list":["PUBCHEM_SUBSTANCE","PUBCHEM","CHEBI"]},"lcsb.mapviewer.model.map.reaction.Reaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.AntisenseRna":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Complex":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Unknown":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.TruncatedProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.compartment.Compartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Species":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Rna":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]}},"element-valid-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["PUBMED","GO","MESH_2012"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.species.Chemical":["PUBCHEM_SUBSTANCE","PUBMED","PUBCHEM","HMDB","CHEBI","KEGG_COMPOUND"],"lcsb.mapviewer.model.map.species.Degraded":["PUBMED"],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["PUBMED","GO","MESH_2012"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["PUBCHEM_SUBSTANCE","PUBMED","PUBCHEM","HMDB","CHEBI","KEGG_COMPOUND"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.species.ReceptorProtein":["KEGG_GENES","INTERPRO","HGNC_SYMBOL","UNIPROT","CHEMBL_TARGET","ENSEMBL","PANTHER","EC","REFSEQ","PUBMED","HGNC","ENTREZ","MGD","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.species.Gene":["KEGG_GENES","REFSEQ","PUBMED","HGNC","HGNC_SYMBOL","UNIPROT","ENSEMBL","PANTHER","ENTREZ","MGD"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["PUBMED","GO","MESH_2012"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.species.Protein":["KEGG_GENES","INTERPRO","HGNC_SYMBOL","UNIPROT","CHEMBL_TARGET","ENSEMBL","PANTHER","EC","REFSEQ","PUBMED","HGNC","ENTREZ","MGD","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.BioEntity":["PUBMED"],"lcsb.mapviewer.model.map.species.GenericProtein":["KEGG_GENES","INTERPRO","HGNC_SYMBOL","UNIPROT","CHEMBL_TARGET","ENSEMBL","PANTHER","EC","REFSEQ","PUBMED","HGNC","ENTREZ","MGD","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.species.IonChannelProtein":["KEGG_GENES","INTERPRO","HGNC_SYMBOL","UNIPROT","CHEMBL_TARGET","ENSEMBL","PANTHER","EC","REFSEQ","PUBMED","HGNC","ENTREZ","MGD","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.species.Phenotype":["PUBMED","OMIM","GO","MESH_2012"],"lcsb.mapviewer.model.map.species.Drug":["CHEMBL_COMPOUND","DRUGBANK","PUBMED","HMDB","CHEBI"],"lcsb.mapviewer.model.map.species.Element":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["PUBMED","GO","MESH_2012"],"lcsb.mapviewer.model.map.species.Ion":["PUBCHEM_SUBSTANCE","PUBMED","PUBCHEM","HMDB","CHEBI","KEGG_COMPOUND"],"lcsb.mapviewer.model.map.reaction.Reaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["PUBMED","GO","MESH_2012"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.species.AntisenseRna":["PUBMED"],"lcsb.mapviewer.model.map.species.Complex":["EC","PUBMED","INTERPRO","CHEMBL_TARGET","GO","MESH_2012"],"lcsb.mapviewer.model.map.species.Unknown":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["PUBMED","GO","MESH_2012"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.species.TruncatedProtein":["KEGG_GENES","INTERPRO","HGNC_SYMBOL","UNIPROT","CHEMBL_TARGET","ENSEMBL","PANTHER","EC","REFSEQ","PUBMED","HGNC","ENTREZ","MGD","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.compartment.Compartment":["PUBMED","GO","MESH_2012"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["PUBMED","GO","MESH_2012"],"lcsb.mapviewer.model.map.species.Species":["PUBMED"],"lcsb.mapviewer.model.map.species.Rna":["KEGG_GENES","REFSEQ","PUBMED","HGNC","HGNC_SYMBOL","UNIPROT","ENSEMBL","PANTHER","ENTREZ","MGD"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":["PUBMED","COG","KEGG_REACTION","REACTOME","KEGG_PATHWAY"]},"element-annotators":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":[],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.species.Chemical":["Chebi"],"lcsb.mapviewer.model.map.species.Degraded":[],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["Chebi"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":[],"lcsb.mapviewer.model.map.species.ReceptorProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":[],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":[],"lcsb.mapviewer.model.map.species.Gene":["HGNC"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":[],"lcsb.mapviewer.model.map.species.Protein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.BioEntity":[],"lcsb.mapviewer.model.map.species.GenericProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":[],"lcsb.mapviewer.model.map.species.IonChannelProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.Phenotype":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Drug":[],"lcsb.mapviewer.model.map.species.Element":[],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":[],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Ion":["Chebi"],"lcsb.mapviewer.model.map.reaction.Reaction":[],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":[],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":[],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.AntisenseRna":[],"lcsb.mapviewer.model.map.species.Complex":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Unknown":[],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":[],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.species.TruncatedProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.compartment.Compartment":["Gene Ontology"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Species":[],"lcsb.mapviewer.model.map.species.Rna":["HGNC"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":[],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":[]},"project-upload":{"auto-resize":true,"sbgn":false,"cache-data":false,"semantic-zooming":false,"annotate-model":false,"validate-miriam":false},"annotators-parameters":{}},"removed":false,"surname":"","minColor":null,"name":"","neutralColor":null,"maxColor":null,"id":3,"login":"anonymous","email":""},{"simpleColor":null,"privileges":[{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":10},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":6},{"type":"VIEW_PROJECT","value":1,"objectId":10},{"type":"USER_MANAGEMENT","value":1},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":18},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":14898},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20603},{"type":"VIEW_PROJECT","value":1,"objectId":18115},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20812},{"type":"VIEW_PROJECT","value":1,"objectId":21432},{"type":"VIEW_PROJECT","value":1,"objectId":15764},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":17051},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":7},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15763},{"type":"VIEW_PROJECT","value":1,"objectId":9},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21417},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19103},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21432},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21966},{"type":"VIEW_PROJECT","value":1,"objectId":19187},{"type":"VIEW_PROJECT","value":1,"objectId":20812},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19187},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20604},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21430},{"type":"VIEW_PROJECT","value":1,"objectId":17},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":20620},{"type":"VIEW_PROJECT","value":1,"objectId":19186},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19102},{"type":"CUSTOM_LAYOUTS","value":100},{"type":"VIEW_PROJECT","value":1,"objectId":19103},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20620},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21113},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":19187},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":16668},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19186},{"type":"VIEW_PROJECT","value":1,"objectId":21},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15764},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19103},{"type":"VIEW_PROJECT","value":1,"objectId":20603},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19184},{"type":"VIEW_PROJECT","value":1,"objectId":19102},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":1},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":9},{"type":"CONFIGURATION_MANAGE","value":1},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21417},{"type":"MANAGE_GENOMES","value":1},{"type":"VIEW_PROJECT","value":1,"objectId":18039},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20812},{"type":"VIEW_PROJECT","value":1,"objectId":21968},{"type":"VIEW_PROJECT","value":1,"objectId":14898},{"type":"VIEW_PROJECT","value":1,"objectId":20},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":18039},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":19102},{"type":"VIEW_PROJECT","value":1,"objectId":21966},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":17},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21113},{"type":"PROJECT_MANAGEMENT","value":1},{"type":"VIEW_PROJECT","value":1,"objectId":21417},{"type":"VIEW_PROJECT","value":1,"objectId":6},{"type":"VIEW_PROJECT","value":1,"objectId":19},{"type":"VIEW_PROJECT","value":1,"objectId":19184},{"type":"VIEW_PROJECT","value":1,"objectId":21424},{"type":"VIEW_PROJECT","value":1,"objectId":22},{"type":"VIEW_PROJECT","value":1,"objectId":18},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":14898},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":15763},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":17051},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21424},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":11},{"type":"VIEW_PROJECT","value":1,"objectId":20604},{"type":"VIEW_PROJECT","value":1,"objectId":15763},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21430},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":15764},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18115},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21},{"type":"ADD_MAP","value":1},{"type":"VIEW_PROJECT","value":1,"objectId":21430},{"type":"VIEW_PROJECT","value":1,"objectId":1},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19186},{"type":"VIEW_PROJECT","value":1,"objectId":16668},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":16668},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21432},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21966},{"type":"VIEW_PROJECT","value":1,"objectId":7},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":22},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20603},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":8},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21424},{"type":"VIEW_PROJECT","value":1,"objectId":21113},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":19184},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":18115},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21968},{"type":"VIEW_PROJECT","value":1,"objectId":17051},{"type":"VIEW_PROJECT","value":1,"objectId":20620},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":20604},{"type":"LAYOUT_MANAGEMENT","value":1,"objectId":21968},{"type":"VIEW_PROJECT","value":1,"objectId":11},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18039},{"type":"VIEW_PROJECT","value":1,"objectId":8},{"type":"VIEW_PROJECT","value":1,"objectId":null},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":null},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":null},{"type":"CUSTOM_LAYOUTS_AVAILABLE","value":94}],"preferences":{"element-required-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Chemical":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM","PUBCHEM_SUBSTANCE"]},"lcsb.mapviewer.model.map.species.Degraded":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.PathwayCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.SimpleMolecule":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM","PUBCHEM_SUBSTANCE"]},"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.ReceptorProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Gene":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.compartment.OvalCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Protein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.BioEntity":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.GenericProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.TransportReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.IonChannelProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Phenotype":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Drug":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Element":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.SquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Ion":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM","PUBCHEM_SUBSTANCE"]},"lcsb.mapviewer.model.map.reaction.Reaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.AntisenseRna":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Complex":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Unknown":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.TruncatedProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL","CHEMBL_COMPOUND"]},"lcsb.mapviewer.model.map.compartment.Compartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Species":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Rna":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]}},"element-valid-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Chemical":["CHEBI","HMDB","KEGG_COMPOUND","PUBCHEM","PUBCHEM_SUBSTANCE","PUBMED"],"lcsb.mapviewer.model.map.species.Degraded":["PUBMED"],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["CHEBI","HMDB","KEGG_COMPOUND","PUBCHEM","PUBCHEM_SUBSTANCE","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.ReceptorProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Gene":["ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Protein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM","CHEMBL_COMPOUND"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.BioEntity":["PUBMED"],"lcsb.mapviewer.model.map.species.GenericProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.IonChannelProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.Phenotype":["GO","MESH_2012","OMIM","PUBMED"],"lcsb.mapviewer.model.map.species.Drug":["CHEBI","CHEMBL_COMPOUND","DRUGBANK","HMDB","PUBMED"],"lcsb.mapviewer.model.map.species.Element":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.Ion":["CHEBI","HMDB","KEGG_COMPOUND","PUBCHEM","PUBCHEM_SUBSTANCE","PUBMED"],"lcsb.mapviewer.model.map.reaction.Reaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.AntisenseRna":["PUBMED"],"lcsb.mapviewer.model.map.species.Complex":["CHEMBL_TARGET","EC","GO","INTERPRO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.Unknown":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.species.TruncatedProtein":["CHEMBL_TARGET","EC","ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","INTERPRO","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT","UNIPROT_ISOFORM","CHEMBL_COMPOUND"],"lcsb.mapviewer.model.map.compartment.Compartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["GO","MESH_2012","PUBMED"],"lcsb.mapviewer.model.map.species.Species":["PUBMED"],"lcsb.mapviewer.model.map.species.Rna":["ENSEMBL","ENTREZ","HGNC","HGNC_SYMBOL","KEGG_GENES","MGD","PANTHER","PUBMED","REFSEQ","UNIPROT"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":["KEGG_PATHWAY","KEGG_REACTION","PUBMED","REACTOME"]},"element-annotators":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":[],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.species.Chemical":["Chebi"],"lcsb.mapviewer.model.map.species.Degraded":[],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["Chebi"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":[],"lcsb.mapviewer.model.map.species.ReceptorProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":[],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":[],"lcsb.mapviewer.model.map.species.Gene":["HGNC"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":[],"lcsb.mapviewer.model.map.species.Protein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.BioEntity":[],"lcsb.mapviewer.model.map.species.GenericProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":[],"lcsb.mapviewer.model.map.species.IonChannelProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.Phenotype":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Drug":[],"lcsb.mapviewer.model.map.species.Element":[],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":[],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Ion":["Chebi"],"lcsb.mapviewer.model.map.reaction.Reaction":[],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":[],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":[],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.AntisenseRna":[],"lcsb.mapviewer.model.map.species.Complex":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Unknown":[],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":[],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.species.TruncatedProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.compartment.Compartment":["Gene Ontology"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Species":[],"lcsb.mapviewer.model.map.species.Rna":["HGNC"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":[],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":[]},"project-upload":{"auto-resize":true,"sbgn":false,"cache-data":false,"semantic-zooming":false,"annotate-model":false,"validate-miriam":true},"annotators-parameters":{}},"removed":false,"surname":"","minColor":null,"name":"admin","neutralColor":null,"maxColor":null,"id":1,"login":"admin","email":"piotr.gawron@uni.lu"},{"simpleColor":null,"privileges":[{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":21968},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19187},{"type":"PROJECT_MANAGEMENT","value":0},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":17051},{"type":"USER_MANAGEMENT","value":0},{"type":"VIEW_PROJECT","value":0,"objectId":19186},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":21966},{"type":"MANAGE_GENOMES","value":0},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":14898},{"type":"VIEW_PROJECT","value":0,"objectId":17051},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":null},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19186},{"type":"VIEW_PROJECT","value":1,"objectId":21968},{"type":"CONFIGURATION_MANAGE","value":0},{"type":"VIEW_PROJECT","value":0,"objectId":18115},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":18039},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19187},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15764},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":16668},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":null},{"type":"VIEW_PROJECT","value":0,"objectId":16668},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19103},{"type":"CUSTOM_LAYOUTS","value":1},{"type":"VIEW_PROJECT","value":0,"objectId":15764},{"type":"VIEW_PROJECT","value":0,"objectId":19184},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19102},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":16668},{"type":"VIEW_PROJECT","value":0,"objectId":15763},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":14898},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":21966},{"type":"VIEW_PROJECT","value":1,"objectId":null},{"type":"VIEW_PROJECT","value":0,"objectId":14898},{"type":"VIEW_PROJECT","value":1,"objectId":21430},{"type":"VIEW_PROJECT","value":1,"objectId":19103},{"type":"EDIT_COMMENTS_PROJECT","value":1,"objectId":21430},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18115},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":17051},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":15763},{"type":"ADD_MAP","value":0},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19103},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19184},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19184},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":15763},{"type":"VIEW_PROJECT","value":0,"objectId":18039},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":19186},{"type":"VIEW_PROJECT","value":1,"objectId":21966},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":19102},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":18039},{"type":"LAYOUT_MANAGEMENT","value":0,"objectId":21968},{"type":"VIEW_PROJECT","value":0,"objectId":19187},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":15764},{"type":"VIEW_PROJECT","value":1,"objectId":19102},{"type":"EDIT_COMMENTS_PROJECT","value":0,"objectId":18115},{"type":"CUSTOM_LAYOUTS_AVAILABLE","value":1}],"preferences":{"element-required-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Chemical":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM_SUBSTANCE","PUBCHEM"]},"lcsb.mapviewer.model.map.species.Degraded":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.PathwayCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.SimpleMolecule":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM_SUBSTANCE","PUBCHEM"]},"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.ReceptorProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Gene":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.compartment.OvalCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Protein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.BioEntity":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.GenericProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.TransportReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.IonChannelProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.Phenotype":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Drug":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Element":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.SquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Ion":{"require-at-least-one":true,"annotation-list":["CHEBI","PUBCHEM_SUBSTANCE","PUBCHEM"]},"lcsb.mapviewer.model.map.reaction.Reaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.AntisenseRna":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Complex":{"require-at-least-one":true,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Unknown":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.species.TruncatedProtein":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.compartment.Compartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Species":{"require-at-least-one":false,"annotation-list":[]},"lcsb.mapviewer.model.map.species.Rna":{"require-at-least-one":true,"annotation-list":["HGNC","HGNC_SYMBOL"]},"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]},"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":{"require-at-least-one":true,"annotation-list":["PUBMED"]}},"element-valid-annotations":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["MESH_2012","PUBMED","GO"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.species.Chemical":["KEGG_COMPOUND","PUBMED","CHEBI","HMDB","PUBCHEM_SUBSTANCE","PUBCHEM"],"lcsb.mapviewer.model.map.species.Degraded":["PUBMED"],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["MESH_2012","PUBMED","GO"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["KEGG_COMPOUND","PUBMED","CHEBI","HMDB","PUBCHEM_SUBSTANCE","PUBCHEM"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.species.ReceptorProtein":["HGNC","KEGG_GENES","REFSEQ","INTERPRO","MGD","PUBMED","CHEMBL_TARGET","UNIPROT_ISOFORM","ENTREZ","HGNC_SYMBOL","ENSEMBL","PANTHER","EC","UNIPROT"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.species.Gene":["HGNC","KEGG_GENES","ENTREZ","REFSEQ","MGD","PUBMED","HGNC_SYMBOL","ENSEMBL","PANTHER","UNIPROT"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["MESH_2012","PUBMED","GO"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.species.Protein":["HGNC","KEGG_GENES","REFSEQ","INTERPRO","MGD","PUBMED","CHEMBL_TARGET","UNIPROT_ISOFORM","ENTREZ","HGNC_SYMBOL","ENSEMBL","PANTHER","EC","UNIPROT"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.BioEntity":["PUBMED"],"lcsb.mapviewer.model.map.species.GenericProtein":["HGNC","KEGG_GENES","REFSEQ","INTERPRO","MGD","PUBMED","CHEMBL_TARGET","UNIPROT_ISOFORM","ENTREZ","HGNC_SYMBOL","ENSEMBL","PANTHER","EC","UNIPROT"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.species.IonChannelProtein":["HGNC","KEGG_GENES","REFSEQ","INTERPRO","MGD","PUBMED","CHEMBL_TARGET","UNIPROT_ISOFORM","ENTREZ","HGNC_SYMBOL","ENSEMBL","PANTHER","EC","UNIPROT"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.species.Phenotype":["MESH_2012","PUBMED","OMIM","GO"],"lcsb.mapviewer.model.map.species.Drug":["CHEMBL_COMPOUND","DRUGBANK","PUBMED","CHEBI","HMDB"],"lcsb.mapviewer.model.map.species.Element":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["MESH_2012","PUBMED","GO"],"lcsb.mapviewer.model.map.species.Ion":["KEGG_COMPOUND","PUBMED","CHEBI","HMDB","PUBCHEM_SUBSTANCE","PUBCHEM"],"lcsb.mapviewer.model.map.reaction.Reaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["MESH_2012","PUBMED","GO"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.species.AntisenseRna":["PUBMED"],"lcsb.mapviewer.model.map.species.Complex":["INTERPRO","MESH_2012","PUBMED","EC","CHEMBL_TARGET","GO"],"lcsb.mapviewer.model.map.species.Unknown":["PUBMED"],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["MESH_2012","PUBMED","GO"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.species.TruncatedProtein":["HGNC","KEGG_GENES","REFSEQ","INTERPRO","MGD","PUBMED","CHEMBL_TARGET","UNIPROT_ISOFORM","ENTREZ","HGNC_SYMBOL","ENSEMBL","PANTHER","EC","UNIPROT"],"lcsb.mapviewer.model.map.compartment.Compartment":["MESH_2012","PUBMED","GO"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["MESH_2012","PUBMED","GO"],"lcsb.mapviewer.model.map.species.Species":["PUBMED"],"lcsb.mapviewer.model.map.species.Rna":["HGNC","KEGG_GENES","ENTREZ","REFSEQ","MGD","PUBMED","HGNC_SYMBOL","ENSEMBL","PANTHER","UNIPROT"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":["KEGG_REACTION","PUBMED","COG","KEGG_PATHWAY","REACTOME"]},"element-annotators":{"lcsb.mapviewer.model.map.reaction.type.UnknownReducedTriggerReaction":[],"lcsb.mapviewer.model.map.compartment.BottomSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.ReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.species.Chemical":["Chebi"],"lcsb.mapviewer.model.map.species.Degraded":[],"lcsb.mapviewer.model.map.compartment.PathwayCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.SimpleMolecule":["Chebi"],"lcsb.mapviewer.model.map.reaction.type.BooleanLogicGateReaction":[],"lcsb.mapviewer.model.map.species.ReceptorProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownTransitionReaction":[],"lcsb.mapviewer.model.map.reaction.type.TranscriptionReaction":[],"lcsb.mapviewer.model.map.species.Gene":["HGNC"],"lcsb.mapviewer.model.map.compartment.OvalCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.PositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedTriggerReaction":[],"lcsb.mapviewer.model.map.species.Protein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedPhysicalStimulationReaction":[],"lcsb.mapviewer.model.map.BioEntity":[],"lcsb.mapviewer.model.map.species.GenericProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.TransportReaction":[],"lcsb.mapviewer.model.map.species.IonChannelProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.reaction.type.UnknownReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.Phenotype":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Drug":[],"lcsb.mapviewer.model.map.species.Element":[],"lcsb.mapviewer.model.map.reaction.type.DissociationReaction":[],"lcsb.mapviewer.model.map.compartment.SquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Ion":["Chebi"],"lcsb.mapviewer.model.map.reaction.Reaction":[],"lcsb.mapviewer.model.map.reaction.type.HeterodimerAssociationReaction":[],"lcsb.mapviewer.model.map.compartment.RightSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.TranslationReaction":[],"lcsb.mapviewer.model.map.reaction.type.UnknownPositiveInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.ReducedModulationReaction":[],"lcsb.mapviewer.model.map.species.AntisenseRna":[],"lcsb.mapviewer.model.map.species.Complex":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Unknown":[],"lcsb.mapviewer.model.map.reaction.type.TruncationReaction":[],"lcsb.mapviewer.model.map.compartment.LeftSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.reaction.type.UnknownNegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.reaction.type.NegativeInfluenceReaction":[],"lcsb.mapviewer.model.map.species.TruncatedProtein":["Biocompendium","HGNC"],"lcsb.mapviewer.model.map.compartment.Compartment":["Gene Ontology"],"lcsb.mapviewer.model.map.compartment.TopSquareCompartment":["Gene Ontology"],"lcsb.mapviewer.model.map.species.Species":[],"lcsb.mapviewer.model.map.species.Rna":["HGNC"],"lcsb.mapviewer.model.map.reaction.type.KnownTransitionOmittedReaction":[],"lcsb.mapviewer.model.map.reaction.type.StateTransitionReaction":[]},"project-upload":{"auto-resize":true,"sbgn":false,"cache-data":false,"semantic-zooming":false,"annotate-model":false,"validate-miriam":false},"annotators-parameters":{}},"removed":false,"surname":"","minColor":null,"name":"","neutralColor":null,"maxColor":null,"id":16736,"login":"t.t","email":""}] \ No newline at end of file diff --git a/model-command/src/main/java/lcsb/mapviewer/commands/ColorModelCommand.java b/model-command/src/main/java/lcsb/mapviewer/commands/ColorModelCommand.java index bda5fc3e6191d9ff22e3140cced9ad3e2439d081..dc51d7bd73453defe5766ff822ca1c53d2f436fa 100644 --- a/model-command/src/main/java/lcsb/mapviewer/commands/ColorModelCommand.java +++ b/model-command/src/main/java/lcsb/mapviewer/commands/ColorModelCommand.java @@ -4,22 +4,17 @@ import java.awt.Color; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; import org.apache.log4j.Logger; -import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.comparator.StringComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.ArrowTypeData; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.compartment.Compartment; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java index 4f6be19fe04c2a0c97e866f15a4a5b9adca02104..7d0d731afd3c9ca331c41b0b6391db033ca863e3 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/ColorModelCommandTest.java @@ -16,7 +16,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; -import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.model.map.BioEntity; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; @@ -88,15 +87,15 @@ public class ColorModelCommandTest extends CommandTestFunctions { Model model = getModelForFile("testFiles/coloring_model.xml", true); Collection<ColorSchema> schemas = new ArrayList<>(); ColorSchema schema = new GenericColorSchema(); - schema.addMiriamData(new MiriamData(MiriamType.HGNC,"11138")); + schema.addMiriamData(new MiriamData(MiriamType.HGNC, "11138")); schema.setValue(1.0); schemas.add(schema); schema = new GenericColorSchema(); - schema.addMiriamData(new MiriamData(MiriamType.CHEBI,"CHEBI:15377")); + schema.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:15377")); schema.setValue(1.0); schemas.add(schema); schema = new GenericColorSchema(); - schema.addMiriamData(new MiriamData(MiriamType.CHEBI,"CHEBI:15376")); + schema.addMiriamData(new MiriamData(MiriamType.CHEBI, "CHEBI:15376")); schema.setValue(1.0); schemas.add(schema); @@ -365,7 +364,7 @@ public class ColorModelCommandTest extends CommandTestFunctions { public void testReactionMatchWithProteinMiriamData() throws Exception { try { GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL,"SNCA")); + colorSchema.addMiriamData(new MiriamData(MiriamType.HGNC_SYMBOL, "SNCA")); Reaction reaction = new Reaction(); @@ -387,7 +386,7 @@ public class ColorModelCommandTest extends CommandTestFunctions { public void testReactionMatchWithMiriamData() throws Exception { try { GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED,"1234")); + colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); Reaction reaction = new Reaction(); reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); @@ -496,7 +495,6 @@ public class ColorModelCommandTest extends CommandTestFunctions { } } - public void testAliasColoringWithUnknownElementSourceId() throws Exception { try { Model model = getModelForFile("testFiles/sample.xml", false); @@ -543,12 +541,12 @@ public class ColorModelCommandTest extends CommandTestFunctions { try { Reaction reaction = new Reaction(); reaction.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); - + Model model = new ModelFullIndexed(null); model.addReaction(reaction); GenericColorSchema colorSchema = new GenericColorSchema(); - colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED,"1234")); + colorSchema.addMiriamData(new MiriamData(MiriamType.PUBMED, "1234")); List<ColorSchema> schemas = new ArrayList<>(); schemas.add(colorSchema); @@ -564,6 +562,4 @@ public class ColorModelCommandTest extends CommandTestFunctions { } - - } diff --git a/model-command/src/test/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommandTest.java b/model-command/src/test/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommandTest.java index c3769d731b998c3339971e190b5ab781c29aba4d..4acc6bcc88e6ef41daa2d37e6f04068bfe1a0f31 100644 --- a/model-command/src/test/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommandTest.java +++ b/model-command/src/test/java/lcsb/mapviewer/commands/layout/ApplySimpleLayoutModelCommandTest.java @@ -5,7 +5,6 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import java.awt.Dimension; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; import java.util.ArrayList; @@ -215,7 +214,8 @@ public class ApplySimpleLayoutModelCommandTest { elements.add(p2); p2.addElement(p1); - layoutModelCommand.modifyElementLocation(elements, null, new Point2D.Double(100, 100), new DoubleDimension(200, 200)); + layoutModelCommand.modifyElementLocation(elements, null, new Point2D.Double(100, 100), + new DoubleDimension(200, 200)); assertTrue(p1.getX() >= 100); assertTrue(p1.getY() >= 100); @@ -241,20 +241,21 @@ public class ApplySimpleLayoutModelCommandTest { Compartment compartmentToLayout = new SquareCompartment("comp-id2"); compartmentToLayout.addElement(protein); - + staticCompartment.addElement(compartmentToLayout); - + Set<Element> elements = new HashSet<>(); elements.add(protein); elements.add(compartmentToLayout); - layoutModelCommand.modifyElementLocation(elements, null, new Point2D.Double(1000, 1000), new DoubleDimension(2000, 2000)); + layoutModelCommand.modifyElementLocation(elements, null, new Point2D.Double(1000, 1000), + new DoubleDimension(2000, 2000)); assertFalse(protein.getX() >= 1000); assertFalse(protein.getY() >= 1000); assertTrue(staticCompartment.contains(protein)); - + assertFalse(compartmentToLayout.getX() >= 1000); assertFalse(compartmentToLayout.getY() >= 1000); diff --git a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLinkComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLinkComparator.java index eeb7f3ba0b7034a88c3e7d53267000ce567c70c9..8ffff6767c9e95d01eeed4f7499c63c2cb1636e0 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLinkComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/OverviewImageLinkComparator.java @@ -16,6 +16,7 @@ public class OverviewImageLinkComparator extends Comparator<OverviewImageLink> { /** * Default class logger. */ + @SuppressWarnings("unused") private static Logger logger = Logger.getLogger(OverviewImageLinkComparator.class); /** diff --git a/model/src/main/java/lcsb/mapviewer/model/map/compartment/CompartmentComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/compartment/CompartmentComparator.java index 80b2870b9c6a0b29da4ff7ae0d151efb291a8048..524cbddb45191a9c22e43d36a5ff0677b85a2b0d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/compartment/CompartmentComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/compartment/CompartmentComparator.java @@ -11,7 +11,6 @@ import lcsb.mapviewer.common.comparator.DoubleComparator; import lcsb.mapviewer.common.comparator.IntegerComparator; import lcsb.mapviewer.common.comparator.PointComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.reaction.AbstractNodeComparator; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.ElementComparator; @@ -45,11 +44,10 @@ public class CompartmentComparator extends Comparator<Compartment> { super(Compartment.class); this.epsilon = epsilon; } - + protected Comparator<?> getParentComparator() { return new ElementComparator(epsilon); } - /** * Default constructor. diff --git a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlParameter.java b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlParameter.java index aa27e7764a28f7785541895744b03ba06ece5dfb..aba446815c1434e856483c04bcf6c9e29310d353 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlParameter.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/kinetics/SbmlParameter.java @@ -4,7 +4,6 @@ import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; -import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @@ -50,7 +49,7 @@ public class SbmlParameter implements Serializable, SbmlArgument { private String name; private Double value; - + @ManyToOne() private SbmlUnit units; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparator.java index 8f842708acea2ad329ecb5f37d235c8c8dfc32c2..222ab0a8f79baea9a4bdedca9617e92ad9811ef8 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/layout/graphics/LayerComparator.java @@ -7,7 +7,6 @@ import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.comparator.BooleanComparator; import lcsb.mapviewer.common.comparator.IntegerComparator; import lcsb.mapviewer.common.comparator.StringComparator; -import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.graphics.PolylineDataComparator; /** diff --git a/model/src/main/java/lcsb/mapviewer/model/map/modifier/Inhibition.java b/model/src/main/java/lcsb/mapviewer/model/map/modifier/Inhibition.java index a7ee536523dbf4998c754959648c4d273503759d..9079867dce885899418baaa0261f7846ec587fd0 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/modifier/Inhibition.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/modifier/Inhibition.java @@ -6,7 +6,6 @@ import javax.persistence.Entity; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.reaction.Modifier; import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; /** * This class defines inhibition modifier in the reaction. @@ -18,45 +17,45 @@ import lcsb.mapviewer.model.map.species.Species; @DiscriminatorValue("INHIBITION_MODIFIER") public class Inhibition extends Modifier { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public Inhibition() { - super(); - } - - /** - * Constructor that creates inhibition modifier for given element. - * - * @param element - * element object to which this modifier is assigned - */ - public Inhibition(Element element) { - super(element); - } - - /** - * Constructor that creates object with data taken from parameter inhibition. - * - * @param inhibition - * object from which data are initialized - */ - public Inhibition(Inhibition inhibition) { - super(inhibition); - } - - @Override - public Inhibition copy() { - if (this.getClass() == Inhibition.class) { - return new Inhibition(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public Inhibition() { + super(); + } + + /** + * Constructor that creates inhibition modifier for given element. + * + * @param element + * element object to which this modifier is assigned + */ + public Inhibition(Element element) { + super(element); + } + + /** + * Constructor that creates object with data taken from parameter inhibition. + * + * @param inhibition + * object from which data are initialized + */ + public Inhibition(Inhibition inhibition) { + super(inhibition); + } + + @Override + public Inhibition copy() { + if (this.getClass() == Inhibition.class) { + return new Inhibition(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/modifier/Modulation.java b/model/src/main/java/lcsb/mapviewer/model/map/modifier/Modulation.java index b909f91c2a7216c30bebd4b408bebd9141c73b79..6b29c11ffbbcd647d7390d16ad058a68a0138abf 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/modifier/Modulation.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/modifier/Modulation.java @@ -6,7 +6,6 @@ import javax.persistence.Entity; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.reaction.Modifier; import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; /** * This class defines modulation modifier in the reaction. @@ -18,45 +17,45 @@ import lcsb.mapviewer.model.map.species.Species; @DiscriminatorValue("MODULATION_MODIFIER") public class Modulation extends Modifier { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public Modulation() { - super(); - } - - /** - * Constructor that creates modulation modifier for given element. - * - * @param element - * element object to which this modifier is assigned - */ - public Modulation(Element element) { - super(element); - } - - /** - * Constructor that creates object with data taken from parameter modulation. - * - * @param modulation - * object from which data are initialized - */ - public Modulation(Modulation modulation) { - super(modulation); - } - - @Override - public Modulation copy() { - if (this.getClass() == Modulation.class) { - return new Modulation(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public Modulation() { + super(); + } + + /** + * Constructor that creates modulation modifier for given element. + * + * @param element + * element object to which this modifier is assigned + */ + public Modulation(Element element) { + super(element); + } + + /** + * Constructor that creates object with data taken from parameter modulation. + * + * @param modulation + * object from which data are initialized + */ + public Modulation(Modulation modulation) { + super(modulation); + } + + @Override + public Modulation copy() { + if (this.getClass() == Modulation.class) { + return new Modulation(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulation.java b/model/src/main/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulation.java index 40114e8b15a710cebf3433bbc14083f0b7aa8d47..f7e40ddc459f3cd8efb315a186d040f8bf7aa8a6 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulation.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/modifier/PhysicalStimulation.java @@ -6,7 +6,6 @@ import javax.persistence.Entity; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.reaction.Modifier; import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; /** * This class defines physical stimulation modifier in the reaction. @@ -18,46 +17,46 @@ import lcsb.mapviewer.model.map.species.Species; @DiscriminatorValue("PHYSICAL_STIMULATION_MODIFIER") public class PhysicalStimulation extends Modifier { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public PhysicalStimulation() { - super(); - } - - /** - * Constructor that creates physical stimulation modifier for given element. - * - * @param element - * element object to which this modifier is assigned - */ - public PhysicalStimulation(Element element) { - super(element); - } - - /** - * Constructor that creates object with data taken from parameter physical - * stimulation. - * - * @param physicalStimulation - * object from which data are initialized - */ - public PhysicalStimulation(PhysicalStimulation physicalStimulation) { - super(physicalStimulation); - } - - @Override - public PhysicalStimulation copy() { - if (this.getClass() == PhysicalStimulation.class) { - return new PhysicalStimulation(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public PhysicalStimulation() { + super(); + } + + /** + * Constructor that creates physical stimulation modifier for given element. + * + * @param element + * element object to which this modifier is assigned + */ + public PhysicalStimulation(Element element) { + super(element); + } + + /** + * Constructor that creates object with data taken from parameter physical + * stimulation. + * + * @param physicalStimulation + * object from which data are initialized + */ + public PhysicalStimulation(PhysicalStimulation physicalStimulation) { + super(physicalStimulation); + } + + @Override + public PhysicalStimulation copy() { + if (this.getClass() == PhysicalStimulation.class) { + return new PhysicalStimulation(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/modifier/Trigger.java b/model/src/main/java/lcsb/mapviewer/model/map/modifier/Trigger.java index 99baa3f051259bb52019dadfd9b0861e4ecdc735..66f653d6d5c537b71c3cc3bd1c1f122ae75bab7e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/modifier/Trigger.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/modifier/Trigger.java @@ -6,7 +6,6 @@ import javax.persistence.Entity; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.reaction.Modifier; import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; /** * This class defines trigger modifier in the reaction. @@ -18,45 +17,45 @@ import lcsb.mapviewer.model.map.species.Species; @DiscriminatorValue("TRIGGER_MODIFIER") public class Trigger extends Modifier { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public Trigger() { - super(); - } - - /** - * Constructor that creates trigger modifier for given element. - * - * @param element - * element object to which this modifier is assigned - */ - public Trigger(Element element) { - super(element); - } - - /** - * Constructor that creates object with data taken from parameter trigger. - * - * @param trigger - * object from which data are initialized - */ - public Trigger(Trigger trigger) { - super(trigger); - } - - @Override - public Trigger copy() { - if (this.getClass() == Trigger.class) { - return new Trigger(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public Trigger() { + super(); + } + + /** + * Constructor that creates trigger modifier for given element. + * + * @param element + * element object to which this modifier is assigned + */ + public Trigger(Element element) { + super(element); + } + + /** + * Constructor that creates object with data taken from parameter trigger. + * + * @param trigger + * object from which data are initialized + */ + public Trigger(Trigger trigger) { + super(trigger); + } + + @Override + public Trigger copy() { + if (this.getClass() == Trigger.class) { + return new Trigger(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysis.java b/model/src/main/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysis.java index 6fd309245365e3b0fd6eb5efb4453b6fabec25dc..fd299cb37800047faa3cdff2799066d8ce79019e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysis.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/modifier/UnknownCatalysis.java @@ -6,7 +6,6 @@ import javax.persistence.Entity; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.reaction.Modifier; import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; /** * This class defines unknown catalysis modifier in the reaction. @@ -18,46 +17,46 @@ import lcsb.mapviewer.model.map.species.Species; @DiscriminatorValue("UNKNOWN_CATALYSIS_MODIFIER") public class UnknownCatalysis extends Modifier { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public UnknownCatalysis() { - super(); - } - - /** - * Constructor that creates unknown catalysis modifier for given element. - * - * @param element - * element object to which this modifier is assigned - */ - public UnknownCatalysis(Element element) { - super(element); - } - - /** - * Constructor that creates object with data taken from parameter unknown - * catalysis. - * - * @param unknownCatalysis - * object from which data are initialized - */ - public UnknownCatalysis(UnknownCatalysis unknownCatalysis) { - super(unknownCatalysis); - } - - @Override - public UnknownCatalysis copy() { - if (this.getClass() == UnknownCatalysis.class) { - return new UnknownCatalysis(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public UnknownCatalysis() { + super(); + } + + /** + * Constructor that creates unknown catalysis modifier for given element. + * + * @param element + * element object to which this modifier is assigned + */ + public UnknownCatalysis(Element element) { + super(element); + } + + /** + * Constructor that creates object with data taken from parameter unknown + * catalysis. + * + * @param unknownCatalysis + * object from which data are initialized + */ + public UnknownCatalysis(UnknownCatalysis unknownCatalysis) { + super(unknownCatalysis); + } + + @Override + public UnknownCatalysis copy() { + if (this.getClass() == UnknownCatalysis.class) { + return new UnknownCatalysis(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/modifier/UnknownInhibition.java b/model/src/main/java/lcsb/mapviewer/model/map/modifier/UnknownInhibition.java index 05c76708f7b050c11e6acdb5edbcdc330ae65b7b..65d97ab6563135e02b672664d820fd208acf590e 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/modifier/UnknownInhibition.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/modifier/UnknownInhibition.java @@ -6,7 +6,6 @@ import javax.persistence.Entity; import lcsb.mapviewer.common.exception.NotImplementedException; import lcsb.mapviewer.model.map.reaction.Modifier; import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Species; /** * This class defines unknown inhibition modifier in the reaction. @@ -18,47 +17,46 @@ import lcsb.mapviewer.model.map.species.Species; @DiscriminatorValue("UNKNOWN_INHIBITION_MODIFIER") public class UnknownInhibition extends Modifier { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public UnknownInhibition() { - super(); - } - - /** - * Constructor that creates unknown inhibition modifier for given and - * element. - * - * @param element - * element object to which this modifier is assigned - */ - public UnknownInhibition(Element element) { - super(element); - } - - /** - * Constructor that creates object with data taken from parameter unknown - * inhibition. - * - * @param unknownInhibition - * object from which data are initialized - */ - public UnknownInhibition(UnknownInhibition unknownInhibition) { - super(unknownInhibition); - } - - @Override - public UnknownInhibition copy() { - if (this.getClass() == UnknownInhibition.class) { - return new UnknownInhibition(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public UnknownInhibition() { + super(); + } + + /** + * Constructor that creates unknown inhibition modifier for given and element. + * + * @param element + * element object to which this modifier is assigned + */ + public UnknownInhibition(Element element) { + super(element); + } + + /** + * Constructor that creates object with data taken from parameter unknown + * inhibition. + * + * @param unknownInhibition + * object from which data are initialized + */ + public UnknownInhibition(UnknownInhibition unknownInhibition) { + super(unknownInhibition); + } + + @Override + public UnknownInhibition copy() { + if (this.getClass() == UnknownInhibition.class) { + return new UnknownInhibition(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } } diff --git a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparator.java index 693855bee60c6b07afb6e7f559f8c58aac4dc2b4..b68812bfd90f773158a405bba08c9553c7f2047d 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/reaction/AbstractNodeComparator.java @@ -1,13 +1,11 @@ package lcsb.mapviewer.model.map.reaction; -import lcsb.mapviewer.common.Comparator; +import org.apache.log4j.Logger; +import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.exception.InvalidClassException; import lcsb.mapviewer.model.graphics.PolylineDataComparator; -import org.apache.log4j.Logger; - /** * This class implements comparator interface for AbstractNode. It also handles * comparison of subclasses of AbstractNode class. diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/ElementComparator.java b/model/src/main/java/lcsb/mapviewer/model/map/species/ElementComparator.java index 098c7d1f679bea0fb9e0d617ad77d2e4dd745f09..7a985fc597c75eb016511b6d7bf0d73d6a31c2e7 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/ElementComparator.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/ElementComparator.java @@ -9,7 +9,6 @@ import lcsb.mapviewer.common.Comparator; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.comparator.ColorComparator; import lcsb.mapviewer.common.comparator.DoubleComparator; -import lcsb.mapviewer.common.comparator.IntegerComparator; import lcsb.mapviewer.common.comparator.StringComparator; import lcsb.mapviewer.common.comparator.StringListComparator; import lcsb.mapviewer.common.comparator.StringSetComparator; diff --git a/model/src/main/java/lcsb/mapviewer/model/map/species/field/Structure.java b/model/src/main/java/lcsb/mapviewer/model/map/species/field/Structure.java index 5d92fdcce29dc318a40493139f49ec71c037cd57..97f37f09a2f391ba422522baf11af158ca9ef567 100644 --- a/model/src/main/java/lcsb/mapviewer/model/map/species/field/Structure.java +++ b/model/src/main/java/lcsb/mapviewer/model/map/species/field/Structure.java @@ -1,8 +1,8 @@ package lcsb.mapviewer.model.map.species.field; import java.io.Serializable; -import java.util.Map; import java.util.HashMap; +import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; @@ -14,350 +14,359 @@ import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; -import org.apache.commons.collections.map.HashedMap; - import lcsb.mapviewer.common.exception.NotImplementedException; /** - * This class stores structure information as obtained from the SIFTS API - * (https://www.ebi.ac.uk/pdbe/api/doc/sifts.html best_structures), which provides - * the following fields - * pdb_id: the PDB ID which maps to the UniProt ID - * chain_id: the specific chain of the PDB which maps to the UniProt ID - * coverage: the percent coverage of the entire UniProt sequence - * resolution: the resolution of the structure - * start: the structure residue number which maps to the start of the mapped sequence - * unp_start: the sequence residue number which maps to the structure start - * end: the structure residue number which maps to the end of the mapped sequence - * unp_end: the sequence residue number which maps to the structure end - * experimental_method: type of experiment used to determine structure - * tax_id: taxonomic ID of the protein's original organism + * This class stores structure information as obtained from the SIFTS API + * (https://www.ebi.ac.uk/pdbe/api/doc/sifts.html best_structures), which + * provides the following fields pdb_id: the PDB ID which maps to the UniProt ID + * chain_id: the specific chain of the PDB which maps to the UniProt ID + * coverage: the percent coverage of the entire UniProt sequence resolution: the + * resolution of the structure start: the structure residue number which maps to + * the start of the mapped sequence unp_start: the sequence residue number which + * maps to the structure start end: the structure residue number which maps to + * the end of the mapped sequence unp_end: the sequence residue number which + * maps to the structure end experimental_method: type of experiment used to + * determine structure tax_id: taxonomic ID of the protein's original organism * * @author David Hoksza * */ @Entity @Table(name = "structure_table") -//@org.hibernate.annotations.GenericGenerator(name = "test-increment-strategy", strategy = "increment") +// @org.hibernate.annotations.GenericGenerator(name = "test-increment-strategy", +// strategy = "increment") public class Structure implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - - /** - * Unique identifier in the database. - */ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "iddb", unique = true, nullable = false) - private int id; - - /** - * Uniprot record to which this structure belongs to. - */ - @ManyToOne(fetch = FetchType.EAGER) - @JoinColumn(name = "uniprot_id", nullable = false) - private UniprotRecord uniprot; - - /** - * the PDB ID which maps to the UniProt ID - */ - @Column(name = "pdb_id") - private String pdbId = null; - - /** - * the specific chain of the PDB which maps to the UniProt ID - */ - @Column(name = "chain_id") - private String chainId = null; - - /** - * the percent coverage of the entire UniProt sequence - */ - @Column(name = "coverage") - private Double coverage = null; - - /** - * the resolution of the structure - */ - @Column(name = "resolution") - private Double resolution = null; - - /** - * the structure residue number which maps to the start of the mapped sequence - */ - @Column(name = "struct_start") - private Integer structStart = null; - - /** - * the structure residue number which maps to the end of the mapped sequence - */ - @Column(name = "struct_end") - private Integer structEnd = null; - - /** - * the sequence residue number which maps to the structure start - */ - @Column(name = "unp_start") - private Integer unpStart = null; - - /** - * the sequence residue number which maps to the structure end - */ - @Column(name = "unp_end") - private Integer unpEnd = null; - - /** - * type of experiment used to determine structure - */ - @Column(name = "experimental_method") - private String experimentalMethod = null; - - /** - * taxonomic ID of the protein's original organism - */ - @Column(name = "tax_id") - private Integer taxId = null; - - /** - * Default constructor. - */ - public Structure() { - } - - /** - * Constructor that initialize object with the data taken from the parameter. - * - * @param s - * original object from which data is taken - */ - public Structure(Structure s) { - this.id = s.id; - this.uniprot = s.uniprot; - this.pdbId = s.pdbId; - this.chainId = s.chainId; - this.coverage = s.coverage; - this.resolution = s.resolution; - this.structStart = s.structStart; - this.structEnd = s.structEnd; - this.unpStart = s.unpStart; - this.unpEnd = s.unpEnd; - this.experimentalMethod = s.experimentalMethod; - this.taxId = s.taxId; - } - - /** - * Creates copy of the object. - * - * @return copy of the object. - */ - public Structure copy() { - if (this.getClass() == Structure.class) { - return new Structure(this); - } else { - throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); - } - } - - /** - * @return the idModificationResidue - * @see #id - */ - public int getId() { - return id; - } - - /** - * @param id - * the id to set - * @see #id - */ - public void setId(int id) { - this.id = id; - } - - /** - * @return the uniprot - */ - public UniprotRecord getUniprot() { - return uniprot; - } - - /** - * @param uniprot the uniprot to set - */ - public void setUniprot(UniprotRecord uniprot) { - this.uniprot = uniprot; - } - - /** - * @return the pdbId - */ - public String getPdbId() { - return pdbId; - } - - /** - * @param pdbId the pdbId to set - */ - public void setPdbId(String pdbId) { - this.pdbId = pdbId; - } - - /** - * @return the chainId - */ - public String getChainId() { - return chainId; - } - - /** - * @param chainId the chainId to set - */ - public void setChainId(String chainId) { - this.chainId = chainId; - } - - /** - * @return the coverage - */ - public Double getCoverage() { - return coverage; - } - - /** - * @param coverage the coverage to set - */ - public void setCoverage(Double coverage) { - this.coverage = coverage; - } - - /** - * @return the resolution - */ - public Double getResolution() { - return resolution; - } - - /** - * @param resolution the resolution to set - */ - public void setResolution(Double resolution) { - this.resolution = resolution; - } - - /** - * @return the structStart - */ - public Integer getStructStart() { - return structStart; - } - - /** - * @param structStart the structStart to set - */ - public void setStructStart(Integer structStart) { - this.structStart = structStart; - } - - /** - * @return the structEnd - */ - public Integer getStructEnd() { - return structEnd; - } - - /** - * @param structEnd the structEnd to set - */ - public void setStructEnd(Integer structEnd) { - this.structEnd = structEnd; - } - - /** - * @return the unpStart - */ - public Integer getUnpStart() { - return unpStart; - } - - /** - * @param unpStart the unpStart to set - */ - public void setUnpStart(Integer unpStart) { - this.unpStart = unpStart; - } - - /** - * @return the unpEnd - */ - public Integer getUnpEnd() { - return unpEnd; - } - - /** - * @param unpEnd the unpEnd to set - */ - public void setUnpEnd(Integer unpEnd) { - this.unpEnd = unpEnd; - } - - /** - * @return the experimentalMethod - */ - public String getExperimentalMethod() { - return experimentalMethod; - } - - /** - * @param experimentalMethod the experimentalMethod to set - */ - public void setExperimentalMethod(String experimentalMethod) { - this.experimentalMethod = experimentalMethod; - } - - /** - * @return the taxId - */ - public Integer getTaxId() { - return taxId; - } - - /** - * @param taxId the taxId to set - */ - public void setTaxId(Integer taxId) { - this.taxId = taxId; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "Structure [pdbId=" + pdbId + ", chainId=" + chainId + ", coverage=" + coverage + ", resolution=" - + resolution + ", structStart=" + structStart + ", structEnd=" + structEnd + ", unpStart=" + unpStart - + ", unpEnd=" + unpEnd + ", experimentalMethod=" + experimentalMethod + ", taxId=" + taxId + "]"; - } - - public Map<String, Object> toMap() { - Map<String, Object> result = new HashMap<>(); - - result.put("pdbId", this.pdbId); - result.put("chainId", this.chainId); - result.put("coverage", this.coverage); - result.put("resolution", this.resolution); - result.put("structStart", this.structStart); - result.put("structEnd", this.structEnd); - result.put("unpStart", this.unpStart); - result.put("unpEnd", this.unpEnd); - result.put("experimentalMethod", this.experimentalMethod); - result.put("taxId", this.taxId); - - return result; - } + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Unique identifier in the database. + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "iddb", unique = true, nullable = false) + private int id; + + /** + * Uniprot record to which this structure belongs to. + */ + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "uniprot_id", nullable = false) + private UniprotRecord uniprot; + + /** + * the PDB ID which maps to the UniProt ID + */ + @Column(name = "pdb_id") + private String pdbId = null; + + /** + * the specific chain of the PDB which maps to the UniProt ID + */ + @Column(name = "chain_id") + private String chainId = null; + + /** + * the percent coverage of the entire UniProt sequence + */ + @Column(name = "coverage") + private Double coverage = null; + + /** + * the resolution of the structure + */ + @Column(name = "resolution") + private Double resolution = null; + + /** + * the structure residue number which maps to the start of the mapped sequence + */ + @Column(name = "struct_start") + private Integer structStart = null; + + /** + * the structure residue number which maps to the end of the mapped sequence + */ + @Column(name = "struct_end") + private Integer structEnd = null; + + /** + * the sequence residue number which maps to the structure start + */ + @Column(name = "unp_start") + private Integer unpStart = null; + + /** + * the sequence residue number which maps to the structure end + */ + @Column(name = "unp_end") + private Integer unpEnd = null; + + /** + * type of experiment used to determine structure + */ + @Column(name = "experimental_method") + private String experimentalMethod = null; + + /** + * taxonomic ID of the protein's original organism + */ + @Column(name = "tax_id") + private Integer taxId = null; + + /** + * Default constructor. + */ + public Structure() { + } + + /** + * Constructor that initialize object with the data taken from the parameter. + * + * @param s + * original object from which data is taken + */ + public Structure(Structure s) { + this.id = s.id; + this.uniprot = s.uniprot; + this.pdbId = s.pdbId; + this.chainId = s.chainId; + this.coverage = s.coverage; + this.resolution = s.resolution; + this.structStart = s.structStart; + this.structEnd = s.structEnd; + this.unpStart = s.unpStart; + this.unpEnd = s.unpEnd; + this.experimentalMethod = s.experimentalMethod; + this.taxId = s.taxId; + } + + /** + * Creates copy of the object. + * + * @return copy of the object. + */ + public Structure copy() { + if (this.getClass() == Structure.class) { + return new Structure(this); + } else { + throw new NotImplementedException("Method copy() should be overriden in class " + this.getClass()); + } + } + + /** + * @return the idModificationResidue + * @see #id + */ + public int getId() { + return id; + } + + /** + * @param id + * the id to set + * @see #id + */ + public void setId(int id) { + this.id = id; + } + + /** + * @return the uniprot + */ + public UniprotRecord getUniprot() { + return uniprot; + } + + /** + * @param uniprot + * the uniprot to set + */ + public void setUniprot(UniprotRecord uniprot) { + this.uniprot = uniprot; + } + + /** + * @return the pdbId + */ + public String getPdbId() { + return pdbId; + } + + /** + * @param pdbId + * the pdbId to set + */ + public void setPdbId(String pdbId) { + this.pdbId = pdbId; + } + + /** + * @return the chainId + */ + public String getChainId() { + return chainId; + } + + /** + * @param chainId + * the chainId to set + */ + public void setChainId(String chainId) { + this.chainId = chainId; + } + + /** + * @return the coverage + */ + public Double getCoverage() { + return coverage; + } + + /** + * @param coverage + * the coverage to set + */ + public void setCoverage(Double coverage) { + this.coverage = coverage; + } + + /** + * @return the resolution + */ + public Double getResolution() { + return resolution; + } + + /** + * @param resolution + * the resolution to set + */ + public void setResolution(Double resolution) { + this.resolution = resolution; + } + + /** + * @return the structStart + */ + public Integer getStructStart() { + return structStart; + } + + /** + * @param structStart + * the structStart to set + */ + public void setStructStart(Integer structStart) { + this.structStart = structStart; + } + + /** + * @return the structEnd + */ + public Integer getStructEnd() { + return structEnd; + } + + /** + * @param structEnd + * the structEnd to set + */ + public void setStructEnd(Integer structEnd) { + this.structEnd = structEnd; + } + + /** + * @return the unpStart + */ + public Integer getUnpStart() { + return unpStart; + } + + /** + * @param unpStart + * the unpStart to set + */ + public void setUnpStart(Integer unpStart) { + this.unpStart = unpStart; + } + + /** + * @return the unpEnd + */ + public Integer getUnpEnd() { + return unpEnd; + } + + /** + * @param unpEnd + * the unpEnd to set + */ + public void setUnpEnd(Integer unpEnd) { + this.unpEnd = unpEnd; + } + + /** + * @return the experimentalMethod + */ + public String getExperimentalMethod() { + return experimentalMethod; + } + + /** + * @param experimentalMethod + * the experimentalMethod to set + */ + public void setExperimentalMethod(String experimentalMethod) { + this.experimentalMethod = experimentalMethod; + } + + /** + * @return the taxId + */ + public Integer getTaxId() { + return taxId; + } + + /** + * @param taxId + * the taxId to set + */ + public void setTaxId(Integer taxId) { + this.taxId = taxId; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "Structure [pdbId=" + pdbId + ", chainId=" + chainId + ", coverage=" + coverage + ", resolution=" + + resolution + ", structStart=" + structStart + ", structEnd=" + structEnd + ", unpStart=" + unpStart + + ", unpEnd=" + unpEnd + ", experimentalMethod=" + experimentalMethod + ", taxId=" + taxId + "]"; + } + + public Map<String, Object> toMap() { + Map<String, Object> result = new HashMap<>(); + + result.put("pdbId", this.pdbId); + result.put("chainId", this.chainId); + result.put("coverage", this.coverage); + result.put("resolution", this.resolution); + result.put("structStart", this.structStart); + result.put("structEnd", this.structEnd); + result.put("unpStart", this.unpStart); + result.put("unpEnd", this.unpEnd); + result.put("experimentalMethod", this.experimentalMethod); + result.put("taxId", this.taxId); + + return result; + } } diff --git a/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/ComplexAndEntityWithAccessionedSequenceComparator.java b/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/ComplexAndEntityWithAccessionedSequenceComparator.java index 63c7a068134698742aea17f2b81b7131b16bd5a2..5eb802095fdd92b87ba839456ede93c491ac89d4 100644 --- a/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/ComplexAndEntityWithAccessionedSequenceComparator.java +++ b/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/ComplexAndEntityWithAccessionedSequenceComparator.java @@ -5,6 +5,7 @@ import java.util.Set; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.species.Complex; import lcsb.mapviewer.reactome.model.ReactomeEntityWithAccessionedSequence; import lcsb.mapviewer.reactome.model.ReactomeReferenceEntity; @@ -19,40 +20,42 @@ import lcsb.mapviewer.reactome.utils.ComparatorException; * @author Piotr Gawron * */ -public class ComplexAndEntityWithAccessionedSequenceComparator extends ANodeComparator<Complex, ReactomeEntityWithAccessionedSequence> { +public class ComplexAndEntityWithAccessionedSequenceComparator + extends ANodeComparator<Complex, ReactomeEntityWithAccessionedSequence> { - /** - * Default constructor. - */ - public ComplexAndEntityWithAccessionedSequenceComparator() { - super(Complex.class, ReactomeEntityWithAccessionedSequence.class); - } + /** + * Default constructor. + */ + public ComplexAndEntityWithAccessionedSequenceComparator() { + super(Complex.class, ReactomeEntityWithAccessionedSequence.class); + } - @Override - public boolean compareNodes(Complex complex, ReactomeEntityWithAccessionedSequence entity) throws ComparatorException { - Set<MiriamData> complex1Ids; - try { - complex1Ids = getRcu().getIdsForComplex(complex); - } catch (Exception e) { - throw new ComparatorException(e); - } - Set<String> uniprotIds2 = new HashSet<String>(); + @Override + public boolean compareNodes(Complex complex, ReactomeEntityWithAccessionedSequence entity) + throws ComparatorException { + Set<MiriamData> complex1Ids; + try { + complex1Ids = getRcu().getIdsForComplex(complex); + } catch (Exception e) { + throw new ComparatorException(e); + } + Set<String> uniprotIds2 = new HashSet<String>(); - ReactomeReferenceEntity reference = entity.getReferenceEntity(); - if (reference instanceof ReactomeReferenceGeneProduct) { - uniprotIds2.add(reference.getIdentifier()); - } else { - throw new InvalidArgumentException("Unknown class type (" + reference.getClass() + "). Don't know what to do"); - } - if (complex1Ids.size() != uniprotIds2.size()) { - return false; - } - for (String string : uniprotIds2) { - if (!complex1Ids.contains(string)) { - return false; - } - } - return true; - } + ReactomeReferenceEntity reference = entity.getReferenceEntity(); + if (reference instanceof ReactomeReferenceGeneProduct) { + uniprotIds2.add(reference.getIdentifier()); + } else { + throw new InvalidArgumentException("Unknown class type (" + reference.getClass() + "). Don't know what to do"); + } + if (complex1Ids.size() != uniprotIds2.size()) { + return false; + } + for (String string : uniprotIds2) { + if (!complex1Ids.contains(new MiriamData(MiriamType.UNIPROT, string))) { + return false; + } + } + return true; + } } diff --git a/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/ComplexAndSimpleEntityComparator.java b/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/ComplexAndSimpleEntityComparator.java index dd7761548c7c4250482dd48e3afd9b2c4ef445e4..d1ef82927a970a8fae87aac3e7974a45b442830c 100644 --- a/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/ComplexAndSimpleEntityComparator.java +++ b/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/ComplexAndSimpleEntityComparator.java @@ -21,43 +21,43 @@ import lcsb.mapviewer.reactome.utils.ComparatorException; */ public class ComplexAndSimpleEntityComparator extends ANodeComparator<Complex, ReactomeSimpleEntity> { - /** - * Default constructor. - */ - public ComplexAndSimpleEntityComparator() { - super(Complex.class, ReactomeSimpleEntity.class); - } - - @Override - public boolean compareNodes(Complex complex, ReactomeSimpleEntity simpleEntity) throws ComparatorException { - Set<MiriamData> complex1Ids; - try { - complex1Ids = getRcu().getIdsForComplex(complex); - } catch (Exception e) { - throw new ComparatorException(e); - } - - Set<MiriamData> entityIds2 = new HashSet<MiriamData>(); - - for (ReactomeReferenceEntity reference : simpleEntity.getReferenceEntities()) { - if (reference instanceof ReactomeReferenceMolecule) { - boolean isChebi = false; - if (reference.getReferenceDatabase() != null) { - for (String name : reference.getReferenceDatabase().getNames()) { - if (name.equalsIgnoreCase("ChEBI")) { - isChebi = true; - } - } - } - if (isChebi) { - String chebi = "CHEBI:" + reference.getIdentifier(); - if (complex1Ids.contains(chebi)) { - entityIds2.add(new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, MiriamType.CHEBI, chebi)); - } - } - } - } - return compareSets(complex1Ids, entityIds2); - } + /** + * Default constructor. + */ + public ComplexAndSimpleEntityComparator() { + super(Complex.class, ReactomeSimpleEntity.class); + } + + @Override + public boolean compareNodes(Complex complex, ReactomeSimpleEntity simpleEntity) throws ComparatorException { + Set<MiriamData> complex1Ids; + try { + complex1Ids = getRcu().getIdsForComplex(complex); + } catch (Exception e) { + throw new ComparatorException(e); + } + + Set<MiriamData> entityIds2 = new HashSet<MiriamData>(); + + for (ReactomeReferenceEntity reference : simpleEntity.getReferenceEntities()) { + if (reference instanceof ReactomeReferenceMolecule) { + boolean isChebi = false; + if (reference.getReferenceDatabase() != null) { + for (String name : reference.getReferenceDatabase().getNames()) { + if (name.equalsIgnoreCase("ChEBI")) { + isChebi = true; + } + } + } + if (isChebi) { + MiriamData chebi = new MiriamData(MiriamType.CHEBI, "CHEBI:" + reference.getIdentifier()); + if (complex1Ids.contains(chebi)) { + entityIds2.add(chebi); + } + } + } + } + return compareSets(complex1Ids, entityIds2); + } } diff --git a/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/IonAndComplexComparator.java b/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/IonAndComplexComparator.java index 2c3efb25414290f5c9251f6a3eea51ec5f1f7595..051f549e9e710152c53dd416a3edee75781120ec 100644 --- a/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/IonAndComplexComparator.java +++ b/reactome/src/main/java/lcsb/mapviewer/reactome/utils/comparators/IonAndComplexComparator.java @@ -5,6 +5,7 @@ import java.util.List; import lcsb.mapviewer.annotation.services.annotators.ChebiSearchException; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; +import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.species.Ion; import lcsb.mapviewer.reactome.model.ReactomeComplex; import lcsb.mapviewer.reactome.model.ReactomeDefinedSet; @@ -16,75 +17,75 @@ import lcsb.mapviewer.reactome.model.ReactomeSimpleEntity; import lcsb.mapviewer.reactome.utils.ComparatorException; /** - * This class allows to compare {@link Ion} element (internal - * representation) and {@link ReactomeComplex} (reactome model). + * This class allows to compare {@link Ion} element (internal representation) + * and {@link ReactomeComplex} (reactome model). * * @author Piotr Gawron * */ public class IonAndComplexComparator extends ANodeComparator<Ion, ReactomeComplex> { - /** - * Default constructor. - */ - public IonAndComplexComparator() { - super(Ion.class, ReactomeComplex.class); - } + /** + * Default constructor. + */ + public IonAndComplexComparator() { + super(Ion.class, ReactomeComplex.class); + } - @Override - public boolean compareNodes(Ion species, ReactomeComplex entity) throws ComparatorException { - try { - List<MiriamData> chebi1 = getChebiBackend().getOntologyChebiIdsForChebiName(species.getName()); - String chebi2 = null; - if (chebi1.size() == 0) { // if we don't have id then return false (even - // with - // two null values we cannot claim that they are - // equal) - return false; - } - int matched = 0; - for (ReactomePhysicalEntity entity2 : entity.getHasComponents()) { - if (entity2 instanceof ReactomeSimpleEntity) { - for (ReactomeReferenceEntity reference : ((ReactomeSimpleEntity) entity2).getReferenceEntities()) { - if (reference instanceof ReactomeReferenceMolecule) { - boolean isChebi = false; - if (reference.getReferenceDatabase() != null) { - for (String name : reference.getReferenceDatabase().getNames()) { - if (name.equalsIgnoreCase("ChEBI")) { - isChebi = true; - } - } - } - if (isChebi) { - chebi2 = "CHEBI:" + reference.getIdentifier(); - if (chebi1.contains(chebi2)) { - matched++; - } // in other case we cannot claim that there are different - // (maybe - // there are more molecule references and other is going to - // point to correct chebi id) - } - } - } - } else if (entity2 instanceof ReactomeDefinedSet) { - if (getGlobalComparator().compareNodes(species, (ReactomeDefinedSet) entity2)) { - matched++; - } - } else if (entity2 instanceof ReactomeComplex) { - if (getGlobalComparator().compareNodes(species, (ReactomeComplex) entity2)) { - matched++; - } - } else if (entity2 instanceof ReactomeEntityWithAccessionedSequence) { - return false; - } else { - throw new InvalidArgumentException( - "Cannot determine the way of comparison for provided class types: " + species.getClass() + ", " + entity2.getClass()); - } - } - return matched == entity.getHasComponents().size(); - } catch (ChebiSearchException e) { - throw new ComparatorException(e); - } - } + @Override + public boolean compareNodes(Ion species, ReactomeComplex entity) throws ComparatorException { + try { + List<MiriamData> chebi1 = getChebiBackend().getOntologyChebiIdsForChebiName(species.getName()); + String chebi2 = null; + if (chebi1.size() == 0) { // if we don't have id then return false (even + // with + // two null values we cannot claim that they are + // equal) + return false; + } + int matched = 0; + for (ReactomePhysicalEntity entity2 : entity.getHasComponents()) { + if (entity2 instanceof ReactomeSimpleEntity) { + for (ReactomeReferenceEntity reference : ((ReactomeSimpleEntity) entity2).getReferenceEntities()) { + if (reference instanceof ReactomeReferenceMolecule) { + boolean isChebi = false; + if (reference.getReferenceDatabase() != null) { + for (String name : reference.getReferenceDatabase().getNames()) { + if (name.equalsIgnoreCase("ChEBI")) { + isChebi = true; + } + } + } + if (isChebi) { + chebi2 = "CHEBI:" + reference.getIdentifier(); + if (chebi1.contains(new MiriamData(MiriamType.CHEBI, chebi2))) { + matched++; + } // in other case we cannot claim that there are different + // (maybe + // there are more molecule references and other is going to + // point to correct chebi id) + } + } + } + } else if (entity2 instanceof ReactomeDefinedSet) { + if (getGlobalComparator().compareNodes(species, (ReactomeDefinedSet) entity2)) { + matched++; + } + } else if (entity2 instanceof ReactomeComplex) { + if (getGlobalComparator().compareNodes(species, (ReactomeComplex) entity2)) { + matched++; + } + } else if (entity2 instanceof ReactomeEntityWithAccessionedSequence) { + return false; + } else { + throw new InvalidArgumentException("Cannot determine the way of comparison for provided class types: " + + species.getClass() + ", " + entity2.getClass()); + } + } + return matched == entity.getHasComponents().size(); + } catch (ChebiSearchException e) { + throw new ComparatorException(e); + } + } } 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/ConfigurationController.java b/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationController.java index b036c514cb74d0fbbf3ab9dea0a3f9d43f1f86a5..274113cab04dc62e791e574d5e7cdc783b3c40d9 100644 --- a/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationController.java +++ b/rest-api/src/main/java/lcsb/mapviewer/api/configuration/ConfigurationController.java @@ -41,7 +41,7 @@ public class ConfigurationController extends BaseController { @RequestMapping(value = "/configuration/", method = { RequestMethod.GET }, produces = { MediaType.APPLICATION_JSON_VALUE }) - public Map<String, Object> getOverlayTypes(@CookieValue(value = Configuration.AUTH_TOKEN) String token) + public Map<String, Object> getConfiguration(@CookieValue(value = Configuration.AUTH_TOKEN) String token) throws SecurityException { Map<String, Object> result = new HashMap<>(); result.put("options", configurationController.getAllValues(token)); @@ -57,6 +57,7 @@ public class ConfigurationController extends BaseController { result.put("privilegeTypes", configurationController.getPrivilegeTypes(token)); result.put("version", configurationService.getSystemSvnVersion(context.getRealPath("/"))); result.put("buildDate", configurationService.getSystemBuild(context.getRealPath("/"))); + result.put("gitHash", configurationService.getSystemGitVersion(context.getRealPath("/"))); result.put("annotators", configurationController.getAnnotators(token)); result.put("plugins", configurationController.getPlugins(token, context.getRealPath("/"))); return result; 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 f9bec121f2b0f1d56a069d48da46e23722415a9f..33ee71a1b5f123c061ae5fb2251d1f0b2f09d6fc 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 @@ -1,7 +1,6 @@ package lcsb.mapviewer.api.users; import java.io.IOException; -import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -13,8 +12,12 @@ 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.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.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.CookieValue; @@ -34,7 +37,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 { @@ -50,34 +52,33 @@ public class UserController extends BaseController { @Autowired private UserRestImpl userRest; + @Autowired + private AuthenticationProvider authenticationProvider; + @RequestMapping(value = "/doLogin", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE }) public Map<String, Object> login(// @RequestParam(value = "login", defaultValue = Configuration.ANONYMOUS_LOGIN) String login, // - @RequestParam(value = "password", required = false) String password, // - HttpServletResponse response // + @RequestParam(value = "password", defaultValue = "") String password, // + HttpServletResponse response, // + HttpServletRequest request// ) throws SecurityException, IOException { - AuthenticationToken token = userService.login(login, password); - if (token == null) { - throw new SecurityException("Invalid credentials"); - } else { - Map<String, Object> result = new HashMap<>(); - final Boolean useSecureCookie = false; - final int expiryTime = (int) (token.getExpires().getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) - / 1000; - final String cookiePath = "/"; + try { + UsernamePasswordAuthenticationToken springToken = new UsernamePasswordAuthenticationToken(login, password); + springToken.setDetails(new WebAuthenticationDetails(request)); + Authentication authentication = this.authenticationProvider.authenticate(springToken); + SecurityContextHolder.getContext().setAuthentication(authentication); - Cookie cookie = new Cookie("MINERVA_AUTH_TOKEN", token.getId()); + userService.login(login, password, request.getSession().getId()); - cookie.setSecure(useSecureCookie); - cookie.setMaxAge(expiryTime); - cookie.setPath(cookiePath); + Map<String, Object> result = new HashMap<>(); - response.addCookie(cookie); - result.put("info", "Login successful. TOKEN returned as a cookie"); - return result; - } - } + result.put("info", "Login successful. TOKEN returned as a cookie"); + return result; + } catch (AuthenticationException e) { + throw new SecurityException("Invalid credentials"); + } + } @RequestMapping(value = "/users/{login:.+}", method = { RequestMethod.GET }, produces = { MediaType.APPLICATION_JSON_VALUE }) @@ -126,15 +127,13 @@ public class UserController extends BaseController { public Map<String, String> logout(@CookieValue(value = Configuration.AUTH_TOKEN) String token, HttpServletRequest request, HttpServletResponse response // ) throws SecurityException, IOException { - //spring logout + // spring logout Authentication auth = SecurityContextHolder.getContext().getAuthentication(); logger.debug("LOGOUT"); logger.debug(auth); - if (auth != null){ - new SecurityContextLogoutHandler().logout(request, response, auth); + if (auth != null) { + new SecurityContextLogoutHandler().logout(request, response, auth); } - //our session manager logout - userService.logout(token); Map<String, String> result = new HashMap<>(); result.put("status", "OK"); @@ -148,24 +147,26 @@ public class UserController extends BaseController { cookie.setMaxAge(0); cookie.setPath(cookiePath); - response.addCookie(cookie); - result.put("status", "OK"); - return result; - } + response.addCookie(cookie); + result.put("status", "OK"); + return result; + } - @RequestMapping(value = "/users/{login:.+}", method = { RequestMethod.PATCH }, produces = { MediaType.APPLICATION_JSON_VALUE }) + @RequestMapping(value = "/users/{login:.+}", method = { RequestMethod.PATCH }, produces = { + MediaType.APPLICATION_JSON_VALUE }) public Map<String, Object> updateUser(// - @RequestBody String body, // - @PathVariable(value = "login") String login, // - @CookieValue(value = Configuration.AUTH_TOKEN) String token // + @RequestBody String body, // + @PathVariable(value = "login") String login, // + @CookieValue(value = Configuration.AUTH_TOKEN) String token // ) throws SecurityException, QueryException, IOException { - Map<String, Object> node = parseBody(body); - Map<String, Object> data = getData(node, "user"); - return userRest.updateUser(token, login, data); + Map<String, Object> node = parseBody(body); + Map<String, Object> data = getData(node, "user"); + return userRest.updateUser(token, login, data); } - @RequestMapping(value = "/users/{login:.+}", method = { RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE }) - public Map<String, Object> addOverlay(// + @RequestMapping(value = "/users/{login:.+}", method = { RequestMethod.POST }, produces = { + MediaType.APPLICATION_JSON_VALUE }) + public Map<String, Object> addOverlay(// @RequestBody MultiValueMap<String, Object> formData, // @PathVariable(value = "login") String login, // @CookieValue(value = Configuration.AUTH_TOKEN) String token // @@ -174,7 +175,8 @@ public class UserController extends BaseController { } - @RequestMapping(value = "/users/{login:.+}", method = { RequestMethod.DELETE }, produces = { MediaType.APPLICATION_JSON_VALUE }) + @RequestMapping(value = "/users/{login:.+}", method = { RequestMethod.DELETE }, produces = { + MediaType.APPLICATION_JSON_VALUE }) public Map<String, Object> removeProject(// @PathVariable(value = "login") String login, // @CookieValue(value = Configuration.AUTH_TOKEN) String token // @@ -183,7 +185,6 @@ public class UserController extends BaseController { } - /** * @return the userService * @see #userService 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..7004816d7c30d293524808245d1e0eb3c3ab3446 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,32 @@ 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.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 +44,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 +64,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..cb1d33bfb3b833cdd8dfc1e18c33157f94c2d47c 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/CommentService.java @@ -13,8 +13,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.common.ObjectUtils; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.exception.InvalidClassException; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.Comment; @@ -25,21 +23,13 @@ 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; import lcsb.mapviewer.services.interfaces.IModelService; import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.search.ElementIdentifierDetails; -import lcsb.mapviewer.services.search.comment.CommentDetails; -import lcsb.mapviewer.services.search.comment.FullCommentView; -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; /** * This class is responsible for all services connected with comments @@ -54,7 +44,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; @@ -87,12 +77,6 @@ public class CommentService implements ICommentService { @Autowired private IConfigurationService configurationService; - /** - * Factory object used for creation fo {@link CommentView} objects. - */ - @Autowired - private CommentViewFactory commentViewFactory; - @Override public Comment addComment(String name, String email, String content, Model model, Point2D coordinates, Object object, boolean pinned, Model submodel) { @@ -188,23 +172,6 @@ public class CommentService implements ICommentService { } } - @Override - public List<CommentView> getCommentsByMap(Model model, AuthenticationToken token) throws UserAccessException { - boolean editComments = userService.userHasPrivilege(token, PrivilegeType.EDIT_COMMENTS_PROJECT, model.getProject()); - boolean viewProject = userService.userHasPrivilege(token, PrivilegeType.VIEW_PROJECT, model.getProject()); - if (!editComments && !viewProject) { - throw new UserAccessException("You have no privileges to see comments for given project"); - } - List<Comment> comments = commentDao.getCommentByModel(model, null, null); - List<CommentView> commentList = new ArrayList<>(); - for (Comment comment : comments) { - CommentView row = commentViewFactory.create(comment, model); - commentList.add(row); - } - return commentList; - - } - @Override public long getCommentCount() { return commentDao.getCount(); @@ -286,32 +253,6 @@ public class CommentService implements ICommentService { this.configurationService = configurationService; } - /** - * Creates list of {@link CustomCommentMarker} that represents agregated - * comments. - * - * @param comments - * agregated comments (every list contains comments for single element) - * @param topModel - * model which is commented - * @return list of {@link CustomCommentMarker} that represents agregated - * comments - */ - protected List<FullCommentView> agregatedCommentsIntoMarker(List<List<Comment>> comments, Model topModel) { - List<FullCommentView> result = new ArrayList<>(); - FullCommentViewFactory factory = new FullCommentViewFactory(); - for (List<Comment> list : comments) { - result.add(factory.create(list)); - } - return result; - } - - @Override - public List<FullCommentView> getCommentMarkers(Model model) { - List<List<Comment>> comments = getAgregatedComments(model, true); - return agregatedCommentsIntoMarker(comments, model); - } - @Override public void removeCommentsForModel(ModelData model) { List<Comment> comments = commentDao.getCommentByModel(model, null, null); @@ -320,67 +261,6 @@ public class CommentService implements ICommentService { } } - /** - * Returns {@link CommentDetails detailed information} about comments for a - * specified element. - * - * @param element - * element for which we are looking for detailed information - * @param model - * model where we are looking for the information - * @return {@link CommentDetails detailed information} about comments for a - * specified element - */ - public List<ElementIdentifierDetails> getElementInformationForResult(ElementIdentifier element, Model model) { - // TODO refactor!!!! - // it's slow... - List<FullCommentView> comments = getCommentMarkers(model); - - List<ElementIdentifierDetails> result = new ArrayList<>(); - - if (ElementIdentifierType.REACTION.getJsName().equalsIgnoreCase(element.getType())) { - for (FullCommentView comment : comments) { - if (Reaction.class.equals(comment.getType())) { - if (comment.getIdObject().equals(element.getObjectId()) - && comment.getModelId().equals(element.getModelId())) { - for (Pair<String, String> c : comment.getComments()) { - result.add(new CommentDetails(c.getLeft(), c.getRight())); - } - return result; - } - } - } - return result; - } else if (ElementIdentifierType.POINT.getJsName().equalsIgnoreCase(element.getType())) { - for (FullCommentView comment : comments) { - if (Point2D.class.equals(comment.getType())) { - if (equalPoints(comment.getUniqueId(), element.getObjectId())) { - for (Pair<String, String> c : comment.getComments()) { - result.add(new CommentDetails(c.getLeft(), c.getRight())); - } - return result; - } - } - } - return result; - } else if (ElementIdentifierType.ALIAS.getJsName().equalsIgnoreCase(element.getType())) { - for (FullCommentView comment : comments) { - if (Element.class.equals(comment.getType())) { - if (comment.getIdObject().equals(element.getObjectId()) - && comment.getModelId().equals(element.getModelId())) { - for (Pair<String, String> c : comment.getComments()) { - result.add(new CommentDetails(c.getLeft(), c.getRight())); - } - return result; - } - } - } - return result; - } else { - throw new InvalidArgumentException("Unknown clas stype: " + element.getType()); - } - } - /** * Checks if identifier of the points refer to the same point. * @@ -409,7 +289,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 +306,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/ExporterService.java b/service/src/main/java/lcsb/mapviewer/services/impl/ExporterService.java deleted file mode 100644 index a2a369d7114ec1686ddf67be0b749ebaced353d9..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ExporterService.java +++ /dev/null @@ -1,1088 +0,0 @@ -package lcsb.mapviewer.services.impl; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.converter.model.celldesigner.reaction.ReactionLineData; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.compartment.PathwayCompartment; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.Modifier; -import lcsb.mapviewer.model.map.reaction.Product; -import lcsb.mapviewer.model.map.reaction.Reactant; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; -import lcsb.mapviewer.model.map.species.field.AntisenseRnaRegion; -import lcsb.mapviewer.model.map.species.field.ModificationResidue; -import lcsb.mapviewer.model.map.species.field.RnaRegion; -import lcsb.mapviewer.services.interfaces.IExporterService; -import lcsb.mapviewer.services.utils.data.ExportColumn; -import lcsb.mapviewer.services.utils.data.ExportFileType; -import lcsb.mapviewer.services.view.PubmedAnnotatedElementsView; -import lcsb.mapviewer.services.view.PubmedAnnotatedElementsViewFactory; - -/** - * Implementation of {@link IExporterService} interface that allows to export - * {@link Model}. - * - * @author Piotr Gawron - * - */ -public class ExporterService implements IExporterService { - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(ExporterService.class); - - /** - * List of publications by {@link Model#getId() model id}. This is used for - * caching, as obtaining this list on runtime is quite expensive. - */ - private static Map<Integer, List<PubmedAnnotatedElementsView>> pubmedPublicationsForModel = new HashMap<>(); - - /** - * Factory used to create {@link PubmedAnnotatedElementsView publication - * summary} elements. - */ - @Autowired - private PubmedAnnotatedElementsViewFactory pubmedAnnotatedElementsViewFactory; - - @Override - public void exportSpecies(ExporterParameters parameters) throws IOException { - String content = getExportSpeciesString(parameters); - writeToFile(content, parameters.getFileName()); - } - - @Override - public String getExportSpeciesString(ExporterParameters parameters) { - Set<String> uniqeLines = new HashSet<String>(); - StringBuilder builder = new StringBuilder(); - for (ExportColumn column : parameters.getColumns()) { - builder.append(column.getTitle() + "\t"); - } - builder.append("\n"); - for (Model model : parameters.getModels()) { - for (Element alias : model.getElements()) { - if (alias instanceof Species) { - Species speciesAlias = (Species) alias; - boolean toBeProcessed = false; - // check type - for (Class<?> type : parameters.getTypes()) { - if (type.isAssignableFrom(speciesAlias.getClass())) { - toBeProcessed = true; - break; - } - } - if (!toBeProcessed && parameters.getTypes().size() > 0) { - continue; - } - - // check where it lays - toBeProcessed = (parameters.getIncludedAliases().size() == 0); - for (Compartment ca : parameters.getIncludedAliases()) { - if (ca.cross(alias)) { - toBeProcessed = true; - } - } - for (Compartment ca : parameters.getExcludedAliases()) { - if (ca.cross(alias)) { - toBeProcessed = false; - } - } - if (toBeProcessed) { - List<String> elements = getExportStringForOneSpecies(speciesAlias, parameters); - for (String string : elements) { - uniqeLines.add(string); - } - } - } - } - } - List<String> sortedElements = new ArrayList<String>(); - sortedElements.addAll(uniqeLines); - Collections.sort(sortedElements); - for (String string : sortedElements) { - builder.append(string); - builder.append("\n"); - } - return builder.toString(); - } - - /** - * Returns strings with species alias exported using given parameters. Many - * lines can be exported because one species alias can belong to many - * pathways. - * - * @param parameters - * {@link ExporterParameters export parameters} - * @param species - * export string are generated for this alias - * @return list of strings representing exported data - */ - protected List<String> getExportStringForOneSpecies(Species species, ExporterParameters parameters) { - if (parameters.getFileType() != ExportFileType.TAB_SEPARATED) { - throw new InvalidArgumentException("Unhandled file type: " + parameters.getFileType()); - } - - List<Compartment> aliases = getComponentList(species); - List<String> result = new ArrayList<String>(); - - Compartment smallestCompartment = getCompartment(species); - - List<ExportColumn> processedColumns = new ArrayList<ExportColumn>(); - for (ExportColumn column : parameters.getColumns()) { - if (column.getClazz().isAssignableFrom(Species.class)) { - processedColumns.add(column); - } - } - - for (Compartment compartment : aliases) { - String separator = ""; - StringBuilder line = new StringBuilder(); - for (ExportColumn column : processedColumns) { - line.append(separator); - separator = "\t"; - if (column == ExportColumn.COMPARTMENT_NAME) { - if (smallestCompartment == null) { - line.append("null"); - } else { - line.append(smallestCompartment.getName()); - } - } else if (column == ExportColumn.POSITION_TO_COMPARTMENT) { - line.append(species.getPositionToCompartment()); - } else if (column == ExportColumn.COMPONENT_NAME) { - line.append(compartment.getName()); - } else if (column == ExportColumn.NAME) { - if (species instanceof Complex) { - if (!parameters.isComplexElementsName()) { - line.append(species.getName()); - } else { - line.append(getComplexNameWithElements((Complex) species, parameters)); - } - } else { - line.append(species.getName()); - } - } else if (column == ExportColumn.ID) { - line.append(getId(species)); - } else if (column == ExportColumn.TYPE) { - line.append(species.getClass().getSimpleName()); - } else if (column == ExportColumn.SUBMODEL) { - line.append(species.getModelData().getName()); - } else if (column == ExportColumn.COMPLEX) { - String complex = null; - if (species.getComplex() != null) { - complex = species.getComplex().getName(); - - complex += " [id=" + getId(species.getComplex()) + "]"; - } - line.append(complex); - } else { - throw new InvalidArgumentException("Unhandled column type: " + column); - } - } - for (MiriamType mt : parameters.getMiriamTypes()) { - line.append(separator); - String types = ""; - for (MiriamData md : species.getMiriamData()) { - if (md.getDataType().equals(mt)) { - if (!types.isEmpty()) { - types += ","; - } - types += md.getResource(); - } - } - if (types.equals("")) { - line.append(mt.toString() + ": N/A"); - } else { - line.append(mt.toString() + ": " + types); - } - } - result.add(line.toString().replaceAll("[\n\r]+", " ")); - } - return result; - } - - /** - * Returns {@link Compartment} to which element belongs to. - * - * @param element - * alias of the element - * @return {@link Compartment} to which element belongs to - */ - private Compartment getCompartment(Species element) { - Compartment smallestAlias = null; - List<Compartment> compartmentAliases = new ArrayList<Compartment>(); - - for (Compartment alias : element.getModel().getCompartments()) { - if (alias.cross(element)) { - if (!(alias instanceof PathwayCompartment)) { - compartmentAliases.add(alias); - } - } - } - - if (compartmentAliases.size() > 0) { - smallestAlias = compartmentAliases.get(0); - } - for (Compartment compartmentAlias : compartmentAliases) { - if (compartmentAlias.getSize() < smallestAlias.getSize()) { - smallestAlias = compartmentAlias; - } - } - return smallestAlias; - } - - /** - * Returns a list of pathways to which element belongs to. - * - * @param element - * alias of the element - * @return list of {@link Compartment} representing pathways - */ - private List<Compartment> getComponentList(Species element) { - Model model = element.getModel(); - - List<Compartment> aliases = new ArrayList<Compartment>(); - for (Compartment alias : model.getCompartments()) { - if (alias instanceof PathwayCompartment) { - if (alias.cross(element)) { - aliases.add(alias); - } - } - } - - // in case the element is outside any component then we have to crate - // artifical null component - if (aliases.size() == 0) { - PathwayCompartment nullAlias = new PathwayCompartment("default"); - nullAlias.setName("null"); - aliases.add(nullAlias); - } - - return aliases; - } - - /** - * Returns name of a complex with the names of all species included in this - * complex. - * - * @param complex - * complex for which name is computed - * @param parameters - * parameter limits the species that will be included in generated - * name - * @return name of a complex with the names of all species included in this - * complex - */ - private String getComplexNameWithElements(Complex complex, ExporterParameters parameters) { - StringBuilder result = new StringBuilder(); - String separator = ""; - for (Element species2 : complex.getAllSimpleChildren()) { - boolean add = false; - if (parameters.getTypes().size() == 0) { - add = true; - } - for (Class<?> class1 : parameters.getTypes()) { - if (class1.isAssignableFrom(species2.getClass())) { - add = true; - } - } - if (add) { - result.append(separator); - result.append(species2.getName()); - separator = ":"; - } - - } - if (result.length() == 0) { - return complex.getName(); - } else { - return result.toString(); - } - } - - /** - * Writes content into a file. - * - * @param content - * content that should be written into the file. - * @param fileName - * file name - * @throws IOException - * thrown when there is a problem with accessing file - */ - protected void writeToFile(String content, String fileName) throws IOException { - logger.debug("Save file: " + fileName); - File file = new File(fileName); - - // if file doesnt exists, then create it - if (!file.exists()) { - // first create directory structure - file.getParentFile().mkdirs(); - file.createNewFile(); - } - - FileWriter fw = new FileWriter(file.getAbsoluteFile()); - BufferedWriter bw = new BufferedWriter(fw); - bw.write(content); - bw.close(); - } - - @Override - public String getExportInteractionString(ExporterParameters parameters) { - Set<String> uniqueLines = new HashSet<String>(); - if (parameters.getFileType() != ExportFileType.SIF && parameters.getFileType() != ExportFileType.TAB_SEPARATED) { - throw new InvalidArgumentException("Unsupported file format: " + parameters.getFileType()); - } - - for (Model model : parameters.getModels()) { - for (Reaction reaction : model.getReactions()) { - int counter = 0; - for (ReactionNode node : reaction.getReactionNodes()) { - Element element = node.getElement(); - for (Class<?> type : parameters.getTypes()) { - if (type.isAssignableFrom(element.getClass())) { - counter++; - break; - } - } - } - if (counter > 1) { - uniqueLines.addAll(getExportSingleInteractionString(reaction, parameters)); - } - } - } - if (parameters.isMoleculeEdges()) { - for (Model model : parameters.getModels()) { - for (Element element : model.getElements()) { - if (element instanceof Species) { - if (element instanceof SimpleMolecule) { - boolean ok = false; - for (Compartment alias : parameters.getIncludedAliases()) { - if (alias.cross(element)) { - ok = true; - } - } - for (Compartment alias : parameters.getExcludedAliases()) { - if (alias.cross(element)) { - ok = false; - } - } - if (ok) { - String string = getExportSingleInteractionStringFromSpecies((SimpleMolecule) element, parameters); - if (parameters.getFileType() == ExportFileType.SIF) { - if (!uniqueLines.contains(string.replace("molecule_type", "reaction_type"))) { - uniqueLines.add(string); - } - } else { - uniqueLines.add(string); - } - } - } - } - } - } - } - List<String> sortedLines = new ArrayList<String>(); - sortedLines.addAll(uniqueLines); - Collections.sort(sortedLines); - StringBuilder result = new StringBuilder(); - for (String string : sortedLines) { - if (!string.equals("")) { - result.append(string); - result.append("\n"); - } - } - - return result.toString(); - } - - /** - * Creates interaction from molecule (molecule is used as extension of - * reaction between different types of elements). - * - * @param species - * molecule which is treaded as a reaction element - * @param parameters - * {@link ExporterParameters export parameters} - * @return string representing exported reaction - */ - protected String getExportSingleInteractionStringFromSpecies(SimpleMolecule species, ExporterParameters parameters) { - if (parameters.getFileType() != ExportFileType.SIF) { - throw new InvalidArgumentException("Unsupported file format: " + parameters.getFileType()); - } - StringBuilder result = new StringBuilder(); - Set<String> elements = new HashSet<String>(); - for (Model model : parameters.getModels()) { - for (Reaction reaction : model.getReactions()) { - boolean goodReaction = false; - for (ReactionNode node : reaction.getReactionNodes()) { - if (node.getElement() instanceof SimpleMolecule) { - Element species2 = node.getElement(); - if (species.getName().equalsIgnoreCase(species2.getName())) { - goodReaction = true; - } - } - } - if (!goodReaction) { - continue; - } - for (ReactionNode node : reaction.getReactionNodes()) { - boolean ok = false; - if (parameters.getIncludedAliases().size() == 0) { - ok = true; - } - for (Compartment alias2 : parameters.getIncludedAliases()) { - if (alias2.cross(node.getElement())) { - ok = true; - break; - } - } - for (Compartment alias2 : parameters.getExcludedAliases()) { - if (alias2.cross(node.getElement())) { - ok = false; - break; - } - } - if (ok) { - Element element = node.getElement(); - for (Class<?> type : parameters.getTypes()) { - if (type.isAssignableFrom(element.getClass())) { - if (element instanceof Complex) { - if (!parameters.isComplexElementsName()) { - elements.add(((Species) element).getName()); - } else { - String name = getComplexNameWithElements((Complex) element, parameters); - elements.add(name); - } - } else { - elements.add(((Species) element).getName()); - } - break; - } - } - } - } - } - } - if (elements.size() <= 1) { - return ""; - } - List<String> list = new ArrayList<String>(); - list.addAll(elements); - result.append(list.get(0)); - result.append("\tmolecule_type"); - for (int i = 1; i < list.size(); i++) { - result.append("\t"); - result.append(list.get(i)); - } - return result.toString(); - - } - - /** - * Returns strings with reactions exported using given parameters. Many lines - * can be exported because one species alias can belong to many pathways. - * - * @param parameters - * {@link ExporterParameters export parameters} - * @param reaction - * export string are generated for this reaction - * @return list of strings representing exported data - */ - protected List<String> getExportSingleInteractionString(Reaction reaction, ExporterParameters parameters) { - List<String> result = new ArrayList<String>(); - if (parameters.getFileType() == ExportFileType.SIF) { - StringBuilder builder = new StringBuilder(); - Set<Element> elements = new HashSet<>(); - for (ReactionNode node : reaction.getReactionNodes()) { - boolean ok = false; - if (parameters.getIncludedAliases().size() == 0) { - ok = true; - } - for (Compartment alias2 : parameters.getIncludedAliases()) { - if (alias2.cross(node.getElement())) { - ok = true; - break; - } - } - for (Compartment alias2 : parameters.getExcludedAliases()) { - if (alias2.cross(node.getElement())) { - ok = false; - break; - } - } - if (ok) { - Element element = node.getElement(); - if (parameters.getTypes().size() == 0) { - elements.add(element); - } else { - for (Class<?> type : parameters.getTypes()) { - if (type.isAssignableFrom(element.getClass())) { - elements.add(element); - break; - } - } - } - } - } - Set<String> elementsNames = new HashSet<>(); - for (Element element : elements) { - if (element instanceof Complex) { - if (!parameters.isComplexElementsName()) { - elementsNames.add(((Species) element).getName()); - } else { - String name = getComplexNameWithElements((Complex) element, parameters); - elementsNames.add(name); - } - - } else { - elementsNames.add(((Species) element).getName()); - } - } - - if (elementsNames.size() <= 1) { - return result; - } - List<String> list = new ArrayList<String>(); - list.addAll(elementsNames); - builder.append(list.get(0)); - builder.append("\treaction_type"); - for (int i = 1; i < list.size(); i++) { - builder.append("\t"); - builder.append(list.get(i)); - } - result.add(builder.toString()); - } else if (parameters.getFileType() == ExportFileType.TAB_SEPARATED) { - if (parameters.getColumns() == null || parameters.getColumns().size() == 0) { - result.add(getOldFormatString(reaction, parameters)); - } else { - result.addAll(getNewFormatString(reaction, parameters)); - } - } else { - throw new InvalidArgumentException("Unsupported file format: " + parameters.getFileType()); - } - return result; - } - - /** - * Creates tab separated string for reaction in old format... - * - * @param reaction - * reaction to transform - * @param parameters - * {@link ExporterParameters export parameters} - * @return export string representation of the reaction - */ - private String getOldFormatString(Reaction reaction, ExporterParameters parameters) { - StringBuilder result = new StringBuilder(); - result.append(reaction.getIdReaction()); - result.append("\t"); - result.append(ReactionLineData.getByReactionType(reaction.getClass())); - result.append("\t"); - result.append("reversible=" + reaction.isReversible()); - result.append("\t"); - if (reaction.getMiriamData().size() > 0) { - result.append("REACTION_MIRIAM_DATA"); - result.append("\t"); - for (MiriamData md : reaction.getMiriamData()) { - result.append("data_type=" + md.getDataType().getUris().get(0)); - result.append("\t"); - result.append("relation_type=" + md.getRelationType().getStringRepresentation()); - result.append("\t"); - result.append("resource=" + md.getResource()); - result.append("\t"); - } - } - for (Reactant reactant : reaction.getReactants()) { - result.append("REACTANT"); - result.append("\t"); - result.append(getExportSingleSpecies((Species) reactant.getElement(), parameters)); - result.append("\t"); - } - for (Product product : reaction.getProducts()) { - result.append("PRODUCT"); - result.append("\t"); - result.append(getExportSingleSpecies((Species) product.getElement(), parameters)); - result.append("\t"); - } - for (Modifier modifier : reaction.getModifiers()) { - result.append("MODIFIER"); - result.append("\t"); - result.append("type=" + modifier.getClass().getSimpleName()); - result.append("\t"); - result.append(getExportSingleSpecies((Species) modifier.getElement(), parameters)); - result.append("\t"); - } - return result.toString(); - } - - /** - * Creates tab separated string for reaction in new format... - * - * @param reaction - * reaction to transform - * @param parameters - * {@link ExporterParameters export parameters} - * @return export string representation of the reaction - */ - private List<String> getNewFormatString(Reaction reaction, ExporterParameters parameters) { - List<String> result = new ArrayList<String>(); - StringBuilder builder = new StringBuilder(); - boolean splitReaction = false; - for (ExportColumn column : parameters.getColumns()) { - if (column.getClazz().isAssignableFrom(Reaction.class)) { - if (column.equals(ExportColumn.REACTION_ID)) { - builder.append(reaction.getIdReaction()); - } else if (column.equals(ExportColumn.REACTION_REVERSIBLE)) { - builder.append(reaction.isReversible()); - } else if (column.equals(ExportColumn.REACTION_TYPE)) { - builder.append(ReactionLineData.getByReactionType(reaction.getClass())); - } else if (column.equals(ExportColumn.REACTION_TWO_ELEMENT)) { - splitReaction = true; - continue; - } else { - throw new InvalidArgumentException("Unknown column type: " + column); - } - } - builder.append("\t"); - } - for (MiriamType mt : parameters.getMiriamTypes()) { - String types = ""; - for (MiriamData md : reaction.getMiriamData()) { - if (md.getDataType().equals(mt)) { - if (!types.isEmpty()) { - types += ","; - } - types += md.getResource(); - } - } - if (types.equals("")) { - builder.append(mt.toString() + ": N/A"); - } else { - builder.append(mt.toString() + ": " + types); - } - builder.append("\t"); - } - - int counter = 0; - - if (splitReaction) { - String base = builder.toString(); - Set<Element> inputs = new HashSet<Element>(); - Set<Element> outputs = new HashSet<Element>(); - for (Reactant reactant : reaction.getReactants()) { - if (!isAssignable(parameters, reactant.getElement())) { - continue; - } - if (reactant.getElement() instanceof Complex) { - inputs.addAll(((Complex) (reactant.getElement())).getAllChildren()); - } else { - inputs.add(reactant.getElement()); - } - } - for (Product product : reaction.getProducts()) { - if (!isAssignable(parameters, product.getElement())) { - continue; - } - if (product.getElement() instanceof Complex) { - outputs.addAll(((Complex) (product.getElement())).getAllChildren()); - } else { - outputs.add(product.getElement()); - } - } - for (Modifier modifier : reaction.getModifiers()) { - if (!isAssignable(parameters, modifier.getElement())) { - continue; - } - if (modifier.getElement() instanceof Complex) { - inputs.addAll(((Complex) (modifier.getElement())).getAllChildren()); - } else { - inputs.add(modifier.getElement()); - } - } - for (Element input : inputs) { - if (!isAssignable(parameters, input)) { - continue; - } - for (Element output : outputs) { - if (!isAssignable(parameters, output)) { - continue; - } - String line = base + "\t" + getId(input) + "\t" + getId(output); - result.add(line); - } - } - } else { - - for (Reactant reactant : reaction.getReactants()) { - if (!isAssignable(parameters, reactant.getElement())) { - continue; - } - counter++; - - builder.append("REACTANT"); - builder.append("\t"); - builder.append(getId(reactant.getElement())); - builder.append("\t"); - } - for (Product product : reaction.getProducts()) { - if (!isAssignable(parameters, product.getElement())) { - continue; - } - counter++; - - builder.append("PRODUCT"); - builder.append("\t"); - builder.append(getId(product.getElement())); - builder.append("\t"); - } - for (Modifier modifier : reaction.getModifiers()) { - if (!isAssignable(parameters, modifier.getElement())) { - continue; - } - counter++; - - builder.append("MODIFIER"); - builder.append("\t"); - builder.append(getId(modifier.getElement())); - builder.append("\t"); - } - if (counter > 1) { - result.add(builder.toString()); - } - } - return result; - } - - /** - * Checks if element is acceptable by {@link ExporterParameters export - * parameters}. - * - * @param parameters - * {@link ExporterParameters export parameters} - * @param element - * element to check - * @return true if element can exist in export string, <code>false</code> - * otherwise - */ - private boolean isAssignable(ExporterParameters parameters, Element element) { - boolean ok = false; - for (Class<?> clazz : parameters.getTypes()) { - if (clazz.isAssignableFrom(element.getClass())) { - ok = true; - } - } - return ok; - } - - /** - * Creates tab separated string for species for full mode. - * - * @param alias - * alias of the element to transform - * @param parameters - * {@link ExporterParameters export parameters} - * @return export string representation of the element - */ - private String getExportSingleSpecies(Species alias, ExporterParameters parameters) { - if (parameters.getFileType() != ExportFileType.TAB_SEPARATED) { - throw new InvalidArgumentException("Unsupported file format: " + parameters.getFileType()); - } - StringBuilder sb = new StringBuilder(); - sb.append(alias.getClass().getSimpleName() + "\t"); - sb.append("id=" + getId(alias) + "\t"); - sb.append("name=" + alias.getName() + "\t"); - sb.append("fullName=" + alias.getFullName() + "\t"); - sb.append("charge=" + alias.getCharge() + "\t"); - sb.append("initialAmount=" + alias.getInitialAmount() + "\t"); - sb.append("initialConcentration=" + alias.getInitialConcentration() + "\t"); - String compartment = null; - if (alias.getCompartment() != null) { - compartment = alias.getCompartment().getName(); - } - sb.append("compartment=" + compartment); - sb.append("\t"); - String complexId = null; - if (alias.getComplex() != null) { - complexId = getId(alias.getComplex()); - } - sb.append("complex=" + complexId); - sb.append("\t"); - sb.append("hasOnlySubstanceUnits=" + alias.hasOnlySubstanceUnits()); - sb.append("\t"); - sb.append("positionToCompartment=" + alias.getPositionToCompartment()); - sb.append("\t"); - - if (alias instanceof Protein) { - Protein protein = (Protein) alias; - sb.append("dimer=" + protein.getHomodimer()); - sb.append("\t"); - sb.append("structuralState=" + protein.getStructuralState()); - sb.append("\t"); - sb.append("hypothetical=" + protein.isHypothetical()); - sb.append("\t"); - for (ModificationResidue mr : protein.getModificationResidues()) { - sb.append("MODIFICATION RESIDUE"); - sb.append("\t"); - sb.append("angle=" + mr.getAngle()); - sb.append("\t"); - sb.append("name=" + mr.getName()); - if (mr.getState() != null) { - sb.append("\t"); - sb.append("shortName=" + mr.getState().getAbbreviation()); - } - sb.append("\t"); - sb.append("side=" + mr.getSide()); - sb.append("\t"); - sb.append("size=" + mr.getSize()); - sb.append("\t"); - if (mr.getState() != null) { - sb.append("state=" + mr.getState().getFullName() + "\t"); - } - } - } else if (alias instanceof Gene) { - Gene gene = (Gene) alias; - for (ModificationResidue mr : gene.getModificationResidues()) { - sb.append("MODIFICATION RESIDUE"); - sb.append("\t"); - sb.append("angle=" + mr.getAngle()); - sb.append("\t"); - sb.append("name=" + mr.getName()); - sb.append("\t"); - if (mr.getState() != null) { - sb.append("shortName=" + mr.getState().getAbbreviation() + "\t"); - } - sb.append("side=" + mr.getSide()); - sb.append("\t"); - sb.append("size=" + mr.getSize()); - sb.append("\t"); - if (mr.getState() != null) { - sb.append("state=" + mr.getState().getFullName() + "\t"); - } - } - } else if (alias instanceof Complex) { - Complex complex = (Complex) alias; - sb.append("dimer=" + complex.getHomodimer()); - sb.append("\t"); - sb.append("hypothetical=" + complex.isHypothetical()); - sb.append("\t"); - } else if (alias instanceof SimpleMolecule) { - SimpleMolecule molecule = (SimpleMolecule) alias; - sb.append("dimer=" + molecule.getHomodimer()); - sb.append("\t"); - } else if (alias instanceof Ion) { - sb.append(""); - } else if (alias instanceof Phenotype) { - sb.append(""); - } else if (alias instanceof Drug) { - sb.append(""); - - } else if (alias instanceof Rna) { - Rna rna = (Rna) alias; - for (RnaRegion region : rna.getRegions()) { - sb.append("RNA_REGION"); - sb.append("\t"); - sb.append("type=" + region.getType()); - sb.append("\t"); - if (region.getState() != null) { - sb.append("state=" + region.getState().getFullName() + "\t"); - } - sb.append("\t"); - sb.append("size=" + region.getSize()); - sb.append("\t"); - sb.append("pos=" + region.getPos()); - sb.append("\t"); - } - } else if (alias instanceof AntisenseRna) { - AntisenseRna antisenseRna = (AntisenseRna) alias; - for (AntisenseRnaRegion region : antisenseRna.getRegions()) { - sb.append("RNA_REGION" + "\t"); - if (region.getType() != null) { - sb.append("type=" + region.getType().getName() + "\t"); - } - sb.append("name=" + region.getName() + "\t"); - sb.append("size=" + region.getSize() + "\t"); - sb.append("pos=" + region.getPos() + "\t"); - } - } else if (alias instanceof Unknown) { - sb.append(""); - } else if (alias instanceof Degraded) { - sb.append(""); - } else { - throw new InvalidArgumentException("Invalid class type: " + alias.getClass()); - } - if (alias.getMiriamData().size() > 0) { - sb.append("MIRIAM_DATA"); - sb.append("\t"); - for (MiriamData md : alias.getMiriamData()) { - sb.append("data_type=" + md.getDataType().getUris().get(0)); - sb.append("\t"); - sb.append("relation_type=" + md.getRelationType().getStringRepresentation()); - sb.append("\t"); - sb.append("resource=" + md.getResource()); - sb.append("\t"); - } - } - return sb.toString(); - } - - @Override - public void exportReactions(ExporterParameters parameters) throws IOException { - String content = getExportInteractionString(parameters); - writeToFile(content, parameters.getFileName()); - } - - @Override - public void exportCompartments(ExporterParameters parameters) throws IOException { - String content = getExportCompartmentsString(parameters); - writeToFile(content, parameters.getFileName()); - } - - @Override - public String getExportCompartmentsString(ExporterParameters parameters) { - Set<String> uniqeLines = new HashSet<>(); - StringBuilder builder = new StringBuilder(); - for (Model model : parameters.getModels()) { - for (Compartment alias : model.getCompartments()) { - - // check where it lays - boolean toBeProcessed = (parameters.getIncludedAliases().size() == 0); - for (Compartment ca : parameters.getIncludedAliases()) { - if (ca.cross(alias)) { - toBeProcessed = true; - } - } - for (Compartment ca : parameters.getExcludedAliases()) { - if (ca.cross(alias)) { - toBeProcessed = false; - } - } - if (toBeProcessed) { - List<String> elements = getExportStringForOneCompartment(alias, parameters); - for (String string : elements) { - uniqeLines.add(string); - } - } - } - } - List<String> sortedElements = new ArrayList<>(); - sortedElements.addAll(uniqeLines); - Collections.sort(sortedElements); - for (String string : sortedElements) { - builder.append(string); - builder.append("\n"); - } - return builder.toString(); - } - - /** - * Exports compartments into set of text lines defining a compartment. - * - * @param compartment - * alias of the compartment to export - * @param parameters - * parameters used in export - * @return string srepresenting compartment in export format - */ - private List<String> getExportStringForOneCompartment(Compartment compartment, ExporterParameters parameters) { - List<String> result = new ArrayList<String>(); - if (parameters.getFileType() != ExportFileType.TAB_SEPARATED) { - throw new InvalidArgumentException("Unhandled file type: " + parameters.getFileType()); - } - StringBuilder sb = new StringBuilder(); - sb.append(getId(compartment) + "\t"); - sb.append("name=" + compartment.getName() + "\t"); - sb.append("fullname=" + compartment.getFullName() + "\t"); - if (compartment.getMiriamData().size() > 0) { - sb.append("MIRIAM_DATA"); - sb.append("\t"); - for (MiriamData md : compartment.getMiriamData()) { - sb.append("data_type=" + md.getDataType().getUris().get(0)); - sb.append("\t"); - sb.append("relation_type=" + md.getRelationType().getStringRepresentation()); - sb.append("\t"); - sb.append("resource=" + md.getResource()); - sb.append("\t"); - } - } - result.add(sb.toString()); - return result; - } - - /** - * Returns identifier that should be used for a given alias. - * - * @param alias - * alis for which identifier will be returned - * @return identifier that should be used for a given alias - */ - private String getId(Element alias) { - return alias.getElementId(); - } - - @Override - public List<PubmedAnnotatedElementsView> getPublicationModelSummary(Model model) { - List<PubmedAnnotatedElementsView> result = pubmedPublicationsForModel.get(model.getId()); - if (result != null) { - return result; - } else { - result = new ArrayList<>(); - pubmedPublicationsForModel.put(model.getId(), result); - } - List<Model> models = new ArrayList<>(); - models.add(model); - models.addAll(model.getSubmodels()); - Set<MiriamData> miriamDatas = new HashSet<>(); - for (Model m : models) { - for (Element element : m.getElements()) { - for (MiriamData md : element.getMiriamData()) { - if (MiriamType.PUBMED.equals(md.getDataType())) { - miriamDatas.add(md); - } - } - } - for (Reaction reaction : m.getReactions()) { - for (MiriamData md : reaction.getMiriamData()) { - if (MiriamType.PUBMED.equals(md.getDataType())) { - miriamDatas.add(md); - } - } - } - } - for (MiriamData miriamData : miriamDatas) { - result.add(pubmedAnnotatedElementsViewFactory.create(miriamData, model)); - } - return result; - } - -} 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..32036ab9eea3e89c36e4fba6f2c73da723671498 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/ModelService.java @@ -12,27 +12,21 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.annotation.data.Article; -import lcsb.mapviewer.annotation.services.MeSHParser; import lcsb.mapviewer.annotation.services.MiriamConnector; import lcsb.mapviewer.annotation.services.PubmedParser; import lcsb.mapviewer.annotation.services.PubmedSearchException; -import lcsb.mapviewer.annotation.services.TaxonomyBackend; -import lcsb.mapviewer.annotation.services.TaxonomySearchException; -import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.commands.CopyCommand; import lcsb.mapviewer.common.IProgressUpdater; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.map.MiriamData; import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.layout.Layout; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelData; import lcsb.mapviewer.model.map.model.ModelFullIndexed; import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.persist.dao.ProjectDao; import lcsb.mapviewer.persist.dao.map.ModelDao; import lcsb.mapviewer.services.interfaces.ILayoutService; @@ -41,11 +35,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; -import lcsb.mapviewer.services.view.ProjectView; /** * Implementation of the service that manages models. @@ -86,12 +75,6 @@ public class ModelService implements IModelService { @Autowired private ProjectDao projectDao; - /** - * Object allowing access to the mesh database. - */ - @Autowired - private MeSHParser meshParser; - /** * Local backend to the pubmed data. */ @@ -110,20 +93,9 @@ public class ModelService implements IModelService { @Autowired private MiriamConnector miriamConnector; - /** - * Factory object used for creation of {@link ModelView} elements. - */ - @Autowired - private ModelViewFactory modelViewFactory; - - /** - * Access point and parser for the online ctd database. - */ - @Autowired - 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; } @@ -236,82 +208,6 @@ public class ModelService implements IModelService { logger.debug("Caching finished"); } - @Override - public void updateModel(ModelData model, ProjectView selectedProject) { - - for (Model cachedModel : models.values()) { - if (cachedModel.getId().equals(selectedProject.getModelId())) { - setModel(cachedModel.getModelData(), selectedProject); - } - } - setModel(model, selectedProject); - modelDao.update(model); - } - - /** - * Sets the data from selectedProject into model. - * - * @param model - * destination of the data - * @param selectedProject - * source of the data - */ - private void setModel(ModelData model, ProjectView selectedProject) { - model.setNotes(selectedProject.getDescription()); - List<Layout> toRemove = new ArrayList<Layout>(); - for (Layout layout : model.getLayouts()) { - boolean exists = false; - for (LayoutView row : selectedProject.getLayouts()) { - if (layout.getId() == row.getIdObject()) { - exists = true; - // don't allow client side to edit layouts - // layout.setDirectory(row.getDirectory()); - layout.setTitle(row.getName()); - layout.setDescription(row.getDescription()); - } - } - if (!exists) { - toRemove.add(layout); - } - } - model.getLayouts().removeAll(toRemove); - - MiriamData disease = null; - if (selectedProject.getNewDiseaseName() != null) { - disease = new MiriamData(MiriamType.MESH_2012, selectedProject.getNewDiseaseName()); - } - - try { - if (meshParser.isValidMeshId(disease)) { - model.getProject().setDisease(disease); - } else { - model.getProject().setDisease(null); - selectedProject.setNewDiseaseName(null); - } - } catch (AnnotatorException e) { - logger.warn("Problem with accessing mesh db"); - } - - if (model.getProject() != null) { - MiriamData organism = null; - if (selectedProject.getNewOrganismName() != null && !selectedProject.getNewOrganismName().isEmpty()) { - organism = new MiriamData(MiriamType.TAXONOMY, selectedProject.getNewOrganismName()); - } - - try { - if (taxonomyBackend.getNameForTaxonomy(organism) != null) { - model.getProject().setOrganism(organism); - } else { - model.getProject().setOrganism(null); - } - } catch (TaxonomySearchException e) { - logger.error("Problem with accessing taxonomy db", e); - model.getProject().setOrganism(null); - } - } - - } - @Override public void removeModelFromCache(Model model) { models.remove(model.getProject().getProjectId()); @@ -376,19 +272,6 @@ public class ModelService implements IModelService { } - @Override - public ModelView getModelView(Model model, User user) { - ModelView result = modelViewFactory.create(model); - if (user != null) { - result.setCustomLayouts(layoutService.getCustomLayouts(model, user, true, user)); - for (ModelView view : result.getSubmodels()) { - view.setCustomLayouts( - layoutService.getCustomLayouts(model.getSubmodelById(view.getIdObject()), user, true, user)); - } - } - return result; - } - @Override public void removeModelFromCache(ModelData model) { models.remove(model.getProject().getProjectId()); @@ -561,7 +444,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..7480e12f91a3308d83bb71813ea2309284ecddbc 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/ProjectService.java @@ -33,7 +33,6 @@ import lcsb.mapviewer.annotation.services.MeSHParser; import lcsb.mapviewer.annotation.services.ModelAnnotator; import lcsb.mapviewer.annotation.services.ProblematicAnnotation; import lcsb.mapviewer.annotation.services.TaxonomyBackend; -import lcsb.mapviewer.annotation.services.TaxonomySearchException; import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; import lcsb.mapviewer.annotation.services.annotators.ElementAnnotator; import lcsb.mapviewer.commands.ClearColorModelCommand; @@ -106,9 +105,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; /** * Implementation of the project service. It allows to manage and access project @@ -241,12 +237,6 @@ public class ProjectService implements IProjectService { @Autowired private DbUtils dbUtils; - /** - * Factory object for {@link ProjectView} elements. - */ - @Autowired - private ProjectViewFactory projectViewFactory; - /** * Access point and parser for the online ctd database. */ @@ -265,7 +255,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 +277,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; @@ -301,70 +291,6 @@ public class ProjectService implements IProjectService { return result; } - @Override - public List<ProjectView> getAllProjectViews(AuthenticationToken token) { - List<ProjectView> result = new ArrayList<>(); - List<Project> projects = getAllProjects(token); - for (Project project : projects) { - result.add(projectViewFactory.create(project)); - } - return result; - } - - @Override - public void updateProject(ProjectView selectedProject) { - Project project = projectDao.getById(selectedProject.getIdObject()); - project.setProjectId(selectedProject.getProjectId()); - project.setName(selectedProject.getProjectName()); - project.setVersion(selectedProject.getVersion()); - project.setNotifyEmail(selectedProject.getNotifyEmail()); - MiriamData disease = null; - MiriamData organism = null; - if (selectedProject.getNewDiseaseName() != null && !selectedProject.getNewDiseaseName().isEmpty()) { - disease = new MiriamData(MiriamType.MESH_2012, selectedProject.getNewDiseaseName()); - } - if (selectedProject.getNewOrganismName() != null && !selectedProject.getNewOrganismName().isEmpty()) { - organism = new MiriamData(MiriamType.TAXONOMY, selectedProject.getNewOrganismName()); - } - try { - if (meshParser.isValidMeshId(disease)) { - project.setDisease(disease); - } else { - project.setDisease(null); - selectedProject.setNewDiseaseName(null); - } - } catch (AnnotatorException e) { - logger.error("Problem with accessing mesh", e); - project.setDisease(null); - selectedProject.setNewDiseaseName(null); - } - try { - if (taxonomyBackend.getNameForTaxonomy(organism) != null) { - project.setOrganism(organism); - } else { - project.setOrganism(null); - selectedProject.setNewOrganismName(null); - } - } catch (TaxonomySearchException e) { - logger.error("Problem with accessing taxonomy db", e); - project.setOrganism(null); - selectedProject.setNewOrganismName(null); - } - for (ModelData model : project.getModels()) { - if (model.getId().equals(selectedProject.getModelId())) { - modelService.updateModel(model, selectedProject); - } - } - projectDao.update(project); - } - - @Override - public void removeProject(ProjectView selectedProject, String homeDir, boolean async, AuthenticationToken token) - throws UserAccessException { - Project project = projectDao.getById(selectedProject.getIdObject()); - removeProject(project, homeDir, async, token); - } - /** * Removes all types of privileges from every user to the project given in the * parameter. @@ -381,14 +307,8 @@ public class ProjectService implements IProjectService { } @Override - public ProjectView getProjectViewByProjectId(String name, AuthenticationToken token) throws UserAccessException { - 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 +417,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 +442,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(); @@ -539,18 +459,6 @@ public class ProjectService implements IProjectService { } - @Override - public ProjectView getProjectViewById(Integer id, AuthenticationToken token) throws UserAccessException { - Project project = projectDao.getById(id); - if (userService.userHasPrivilege(token, PrivilegeType.VIEW_PROJECT, project)) { - return projectViewFactory.create(project); - } else if (userService.userHasPrivilege(token, PrivilegeType.ADD_MAP)) { - return projectViewFactory.create(project); - } else { - throw new UserAccessException("User cannot access project"); - } - } - /** * This methods add privileges for the users listed in params to the project. * @@ -1278,11 +1186,6 @@ public class ProjectService implements IProjectService { this.dataMiningService = dataMiningService; } - @Override - public ProjectView createEmpty() { - return projectViewFactory.create(null); - } - /** * Analyzes annotation of the model and put information about invalid * annotations into the {@link Model#creationWarnings} field. @@ -1529,11 +1432,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 @@ -1560,30 +1463,6 @@ public class ProjectService implements IProjectService { } - @Override - public byte[] getInputDataForProject(ProjectView projectView) { - return getInputDataForProject(projectView.getIdObject()); - } - - /** - * Returns byte array containing data from original input file that was used to - * create this project. - * - * @param projectId - * identifier of project 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 - */ - private byte[] getInputDataForProject(int projectId) { - Project project = projectDao.getById(projectId); - if (project == null || project.getInputData() == null) { - return null; - } else { - return project.getInputData().getFileContent(); - } - } - /** * Method that handles exception reporting during creation of a project. * 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 f2bbf63c14c9657f9d4e3fa1a65e22f1f47a9bc2..385a8626ee9bc9db38c0e38a4733aa32c077dbc1 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java @@ -1,15 +1,17 @@ package lcsb.mapviewer.services.impl; import java.awt.Color; +import java.math.BigInteger; +import java.security.SecureRandom; import java.util.ArrayList; -import java.util.Calendar; -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.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; import org.springframework.transaction.annotation.Transactional; @@ -29,18 +31,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; -import lcsb.mapviewer.services.view.UserViewFactory; /** * Implementation of the service that manages users. @@ -51,10 +46,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. */ @@ -78,11 +69,8 @@ public class UserService implements IUserService { @Autowired private PrivilegeDao privilegeDao; - /** - * Factory object for {@link UserView} elements. - */ @Autowired - private UserViewFactory userViewFactory; + private SessionRegistry sessionRegistry; /** * Service that provides password encoding. @@ -97,46 +85,16 @@ public class UserService implements IUserService { private ILogService logService; /** - * Service used for accessing confguration parameters. + * Service used for accessing configuration parameters. */ @Autowired private IConfigurationService configurationService; @Override - public AuthenticationToken login(String login, String password) { - User user = userDao.getUserByLoginAndPassword(login, password); - if (Configuration.ANONYMOUS_LOGIN.equals(login)) { - user = getUserByLogin(Configuration.ANONYMOUS_LOGIN); - } - if (user != null) { - int count = 0; - synchronized (authenticationTokens) { - count = authenticationTokens.size(); - } - - if (count > 1000) { - clearAuthenticationTokens(); - } - AuthenticationToken authenticationToken = new AuthenticationToken(); - synchronized (authenticationTokens) { - authenticationTokens.put(authenticationToken.getId(), authenticationToken); - authenticatedUsers.put(authenticationToken, user); - } - return authenticationToken; - } else { - return null; - } - } - - private void clearAuthenticationTokens() { - synchronized (authenticationTokens) { - List<String> toRemove = new ArrayList<>(); - for (AuthenticationToken token : authenticationTokens.values()) { - if (token.getExpires().before(Calendar.getInstance())) { - toRemove.add(token.getId()); - } - } - } + 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); } @Override @@ -206,79 +164,6 @@ public class UserService implements IUserService { return result; } - @Override - public List<UserView> getAllUserRows() { - List<Project> projects = projectDao.getAll(); - - List<UserView> result = new ArrayList<>(); - List<User> fullList = userDao.getAll(); - for (User user : fullList) { - result.add(userViewFactory.create(user, projects)); - } - - return result; - } - - @Override - public UserView getUserRow(User user) { - List<Project> projects = projectDao.getAll(); - return userViewFactory.create(user, projects); - } - - @Override - public void updateUser(UserView userRow) { - User user = null; - if (userRow.getIdObject() == null || userRow.getIdObject() == 0) { - user = new User(); - user.setLogin(userRow.getLogin()); - } else { - user = getUserById(userRow.getIdObject()); - } - if (userRow.getPassword() != null && !userRow.getPassword().trim().equals("")) { - user.setCryptedPassword(passwordEncoder.encode(userRow.getPassword())); - } - - user.setEmail(userRow.getEmail()); - user.setName(userRow.getName()); - user.setSurname(userRow.getSurname()); - if (user.getId() == null) { - addUser(user); - } else { - updateUser(user); - } - - userRow.setIdObject(user.getId()); - - for (PrivilegeView pRow : userRow.getBasicPrivileges()) { - if (pRow.getNumeric()) { - setUserPrivilege(user, new BasicPrivilege(pRow.getLevel(), pRow.getType(), user)); - } else if (pRow.getSelected()) { - setUserPrivilege(user, new BasicPrivilege(1, pRow.getType(), user)); - } else { - setUserPrivilege(user, new BasicPrivilege(0, pRow.getType(), user)); - } - } - for (UserProjectPrivilegeView upRow : userRow.getProjectPrivileges()) { - for (PrivilegeView pRow : upRow.getProjectPrivileges()) { - Project project = projectDao.getById(upRow.getIdObject()); - if (pRow.getNumeric()) { - setUserPrivilege(user, new ObjectPrivilege(project, pRow.getLevel(), pRow.getType(), user)); - } else if (pRow.getSelected()) { - setUserPrivilege(user, new ObjectPrivilege(project, 1, pRow.getType(), user)); - } else { - setUserPrivilege(user, new ObjectPrivilege(project, 0, pRow.getType(), user)); - } - } - } - } - - @Override - public void deleteUser(UserView selectedUser) { - if (selectedUser.getIdObject() != null && selectedUser.getIdObject() != 0) { - deleteUser(getUserById(selectedUser.getIdObject())); - } - } - @Override public void dropPrivilegesForObjectType(PrivilegeType type, int id) { IntegerComparator integerComparator = new IntegerComparator(); @@ -355,11 +240,6 @@ public class UserService implements IUserService { return -1; } - @Override - public void addUser(UserView userRow) { - updateUser(userRow); - } - @Override public void setUserPrivilege(User user, PrivilegeType type, Integer value) { BasicPrivilege privilege = new BasicPrivilege(value, type, user); @@ -448,18 +328,6 @@ public class UserService implements IUserService { this.passwordEncoder = passwordEncoder; } - @Override - public UserView createEmptyUserRow() { - return userViewFactory.create(null); - } - - @Override - public void updateUsers(Collection<UserView> users) { - for (UserView user : users) { - updateUser(user); - } - } - /** * @param password * input password @@ -520,63 +388,39 @@ public class UserService implements IUserService { } @Override - public User getUserByToken(AuthenticationToken token) { - User result = null; - if (Calendar.getInstance().before(token.getExpires())) { - 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 (result.getExpires().before(Calendar.getInstance())) { - logout(result); - throw new AuthenticationTokenExpireException("Token validity expired"); + public User getUserByToken(String token) throws SecurityException { + if (!isSessionExpired(token)) { + 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; } - @Override - public void logout(AuthenticationToken token) { - synchronized (authenticationTokens) { - authenticationTokens.remove(token.getId()); - authenticatedUsers.remove(token); + private boolean isSessionExpired(String token) { + SessionInformation sessionData = sessionRegistry.getSessionInformation(token); + if (sessionData == null) { + logger.debug("No session data for token id: " + token); + return true; } + return sessionData.isExpired(); } @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)) { @@ -589,7 +433,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 { @@ -598,8 +442,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"); } @@ -617,7 +460,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) { @@ -649,7 +492,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); @@ -664,4 +507,19 @@ public class UserService implements IUserService { return userHasPrivilege(getUserByToken(token), type); } + @Override + 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) { + 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..554da7657e36b5fbbfa7ed416855614d6a34364a 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/ICommentService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/ICommentService.java @@ -8,12 +8,8 @@ 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; /** * Service responsible for comments functionality. @@ -22,101 +18,72 @@ 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(); + List<Comment> getCommentsByProject(Project project, String token) throws UserAccessException, SecurityException; - /** - * Removes comments from the model. - * - * @param model - * from which model we want to remove comments - */ - void removeCommentsForModel(Model model); + /** + * Returns number of comments in the system. + * + * @return number of comments in the system + */ + long getCommentCount(); - /** - * 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); + /** + * Removes comments from the model. + * + * @param model + * from which model we want to remove comments + */ + void removeCommentsForModel(Model model); - /** - * 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(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); + Comment getCommentById(String commentId); } diff --git a/service/src/main/java/lcsb/mapviewer/services/interfaces/IExporterService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/IExporterService.java deleted file mode 100644 index 1895e4acd5a37704bd29d8fb4bedbda470430366..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IExporterService.java +++ /dev/null @@ -1,557 +0,0 @@ -package lcsb.mapviewer.services.interfaces; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.services.utils.data.ExportColumn; -import lcsb.mapviewer.services.utils.data.ExportFileType; -import lcsb.mapviewer.services.view.PubmedAnnotatedElementsView; - -/** - * Interface used for simple export of the {@link Model}. - * - * @author Piotr Gawron - * - */ -public interface IExporterService { - /** - * Class that contains parameters used for exporting data. - * - * @author Piotr Gawron - * - */ - class ExporterParameters { - /** - * File where the export data should be saved. - */ - private String fileName = null; - /** - * List of models from which data is exported. - */ - private List<Model> models = new ArrayList<Model>(); - /** - * List of compartment names that should be included in export (empty list - * means that everything should be included). - */ - private List<String> included = new ArrayList<String>(); - /** - * List of compartment names that should be excluded in export (empty list - * means that anything should be excluded). - */ - private List<String> excluded = new ArrayList<String>(); - /** - * Type of file to which export should be performed. - */ - private ExportFileType fileType = null; - /** - * Elements that should be exported. - */ - private List<Class<?>> types = new ArrayList<Class<?>>(); - /** - * Columns that should be included in the export data. - */ - private List<ExportColumn> columns = new ArrayList<ExportColumn>(); - /** - * Miriam annotations that should be included in the export data. - */ - private List<MiriamType> miriamTypes = new ArrayList<MiriamType>(); - /** - * List of compartment aliases that should be included in export (empty list - * means that everything should be included). - */ - private Set<Compartment> includedAliases = new HashSet<Compartment>(); - /** - * List of compartment aliases that should be excluded in export (empty list - * means that anything should be excluded). - */ - private Set<Compartment> excludedAliases = new HashSet<Compartment>(); - /** - * If false default complex name will be used for exporting complexes. If - * true then the name will be a concatenated string of all complex - * subspecies. - */ - private boolean complexElementsName = false; - - /** - * Should the molecules be considered as edges. Might be usefull for <a - * href= - * "http://en.wikipedia.org/wiki/Protein%E2%80%93protein_interaction">PPI - * </a>. - */ - private boolean moleculeEdges = false; - - /** - * - */ - public ExporterParameters() { - } - - /** - * Sets {@link #fileName}. - * - * @param fileName - * new {@link #fileName} - * @return object with all parameters set - */ - public ExporterParameters fileName(String fileName) { - this.fileName = fileName; - return this; - } - - /** - * Sets {@link #model}. - * - * @param model - * new {@link #model} - * @return object with all parameters set - */ - public ExporterParameters model(Model model) { - this.models = new ArrayList<Model>(); - models.add(model); - for (Model m : model.getSubmodels()) { - models.add(m); - } - - for (Model modelElement : models) { - includedAliases.clear(); - for (String string : included) { - for (Compartment alias : modelElement.getCompartments()) { - if (alias.getName().equalsIgnoreCase(string)) { - includedAliases.add(alias); - } - } - } - - excludedAliases.clear(); - for (String string : excluded) { - for (Compartment alias : modelElement.getCompartments()) { - if (alias.getName().equalsIgnoreCase(string)) { - excludedAliases.add(alias); - } - } - } - } - return this; - } - - /** - * Adds element to {@link #included}. - * - * @param included - * new element in {@link #included} - * @return object with all parameters set - */ - public ExporterParameters included(String included) { - this.included.add(included); - - if (models.size() > 0) { - for (Model model : models) { - for (Compartment alias : model.getCompartments()) { - if (alias.getName().equalsIgnoreCase(included)) { - includedAliases.add(alias); - } - } - } - } - return this; - } - - /** - * Adds elements to {@link #included}. - * - * @param included - * list of elements to add to {@link #included} - * @return object with all parameters set - */ - public ExporterParameters included(List<String> included) { - for (String string : included) { - included(string); - } - return this; - } - - /** - * Adds element to {@link #excluded}. - * - * @param excluded - * new element in {@link #excluded} - * @return object with all parameters set - */ - public ExporterParameters excluded(String excluded) { - this.excluded.add(excluded); - - if (models.size() > 0) { - for (Model model : models) { - for (Compartment alias : model.getCompartments()) { - if (alias.getName().equalsIgnoreCase(excluded)) { - excludedAliases.add(alias); - } - } - } - } - return this; - } - - /** - * Adds element to {@link #excluded}. - * - * @param excluded - * new element in {@link #excluded} - * @return object with all parameters set - */ - public ExporterParameters excluded(Compartment excluded) { - this.excluded.add(excluded.getName()); - - excludedAliases.add(excluded); - return this; - } - - /** - * Adds elements to {@link #excluded}. - * - * @param excluded - * list of elements to add to {@link #excluded} - * @return object with all parameters set - */ - public ExporterParameters excluded(List<String> excluded) { - for (String string : excluded) { - excluded(string); - } - return this; - } - - /** - * Adds elements to {@link #excluded}. - * - * @param excluded - * list of elements to add to {@link #excluded} - * @return object with all parameters set - */ - public ExporterParameters excluded(Collection<Compartment> excluded) { - for (Compartment string : excluded) { - excluded(string); - } - return this; - } - - /** - * Sets {@link #fileType}. - * - * @param fileType - * new {@link #fileType} - * @return object with all parameters set - */ - public ExporterParameters fileType(ExportFileType fileType) { - this.fileType = fileType; - return this; - } - - /** - * Adds type to {@link #types}. - * - * @param type - * new element in {@link #types} - * @return object with all parameters set - */ - public ExporterParameters type(Class<?> type) { - this.types.add(type); - return this; - } - - /** - * Adds types to {@link #types}. - * - * @param types - * new elements in {@link #types} - * @return object with all parameters set - */ - public ExporterParameters type(List<Class<?>> types) { - this.types.addAll(types); - return this; - } - - /** - * Adds column to {@link #columns}. - * - * @param column - * new element in {@link #columns} - * @return object with all parameters set - */ - public ExporterParameters column(ExportColumn column) { - this.columns.add(column); - return this; - } - - /** - * Adds columns to {@link #columns}. - * - * @param columns - * new elements in {@link #columns} - * @return object with all parameters set - */ - public ExporterParameters column(List<ExportColumn> columns) { - this.columns.addAll(columns); - return this; - } - - /** - * Adds {@link MiriamType} to {@link #miriamTypes}. - * - * @param mt - * new element in {@link #miriamTypes} - * @return object with all parameters set - */ - public ExporterParameters miriamType(MiriamType mt) { - this.miriamTypes.add(mt); - return this; - } - - /** - * Adds {@link MiriamType miriam types} to {@link #miriamTypes list}. - * - * @param mts - * new elements in {@link #miriamTypes} - * @return object with all parameters set - */ - public ExporterParameters miriamTypes(List<MiriamType> mts) { - this.miriamTypes.addAll(mts); - return this; - } - - /** - * Adds columns to {@link #columns}. - * - * @param columns2 - * new elements in {@link #columns} - * @return object with all parameters set - */ - public ExporterParameters column(ExportColumn[] columns2) { - for (ExportColumn exportColumn : columns2) { - column(exportColumn); - } - return this; - } - - /** - * Sets {@link #moleculeEdges}. - * - * @param moleculeEdges - * new {@link #moleculeEdges} - * @return object with all parameters set - */ - public ExporterParameters moleculeEdges(boolean moleculeEdges) { - this.moleculeEdges = moleculeEdges; - return this; - } - - /** - * Adds elements to {@link #included}. - * - * @param included - * list of elements to add to {@link #included} - * @return object with all parameters set - */ - public ExporterParameters included(String[] included) { - for (String string : included) { - included(string); - } - return this; - } - - /** - * Adds elements to {@link #excluded}. - * - * @param excluded - * list of elements to add to {@link #excluded} - * @return object with all parameters set - */ - public ExporterParameters excluded(String[] excluded) { - for (String string : excluded) { - excluded(string); - } - return this; - } - - /** - * Sets {@link #complexElementsName}. - * - * @param complexElementsName - * new {@link #complexElementsName} - * @return object with all parameters set - */ - public ExporterParameters complexElementsName(boolean complexElementsName) { - this.complexElementsName = complexElementsName; - return this; - } - - /** - * @return the fileName - * @see #fileName - */ - public String getFileName() { - return fileName; - } - - /** - * @return the model - * @see #model - */ - public List<Model> getModels() { - return models; - } - - /** - * @return the included - * @see #included - */ - public List<String> getIncluded() { - return included; - } - - /** - * @return the excluded - * @see #excluded - */ - public List<String> getExcluded() { - return excluded; - } - - /** - * @return the fileType - * @see #fileType - */ - public ExportFileType getFileType() { - return fileType; - } - - /** - * @return the types - * @see #types - */ - public List<Class<?>> getTypes() { - return types; - } - - /** - * @return the columns - * @see #columns - */ - public List<ExportColumn> getColumns() { - return columns; - } - - /** - * @return the includedAliases - * @see #includedAliases - */ - public Set<Compartment> getIncludedAliases() { - return includedAliases; - } - - /** - * @return the excludedAliases - * @see #excludedAliases - */ - public Set<Compartment> getExcludedAliases() { - return excludedAliases; - } - - /** - * @return the complexElementsName - * @see #complexElementsName - */ - public boolean isComplexElementsName() { - return complexElementsName; - } - - /** - * @return the moleculeEdges - * @see #moleculeEdges - */ - public boolean isMoleculeEdges() { - return moleculeEdges; - } - - /** - * @return the miriamTypes - * @see #miriamTypes - */ - public List<MiriamType> getMiriamTypes() { - return miriamTypes; - } - - } - - /** - * Export species using given parameters. - * - * @param parameters - * {@link ExporterParameters export parameters} - * @throws IOException - * thrown when there is a problem with accessing output file - */ - void exportSpecies(ExporterParameters parameters) throws IOException; - - /** - * Returns string with all species exported using given parameters. - * - * @param parameters - * {@link ExporterParameters export parameters} - * @return String representing exported data - */ - String getExportSpeciesString(ExporterParameters parameters); - - /** - * Returns string with all compartments exported using given parameters. - * - * @param parameters - * {@link ExporterParameters export parameters} - * @return String representing exported data - */ - String getExportCompartmentsString(ExporterParameters parameters); - - /** - * Export compartments using given parameters. - * - * @param parameters - * {@link ExporterParameters export parameters} - * @throws IOException - * thrown when there is a problem with accessing output file - */ - void exportCompartments(ExporterParameters parameters) throws IOException; - - /** - * Export reactions using given parameters. - * - * @param parameters - * {@link ExporterParameters export parameters} - * @throws IOException - * thrown when there is a problem with accessing output file - */ - void exportReactions(ExporterParameters parameters) throws IOException; - - /** - * Returns string with all reactions exported using given parameters. - * - * @param parameters - * {@link ExporterParameters export parameters} - * @return String representing exported data - */ - String getExportInteractionString(ExporterParameters parameters); - - /** - * Returns list of publciations for given model. - * - * @param model - * model for which list of publication will be returned - * @return list of publciations for given model - */ - List<PubmedAnnotatedElementsView> getPublicationModelSummary(Model model); -} 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..b150036d82ea1fcb11e2e0b3c19c3d419f811d73 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IModelService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IModelService.java @@ -6,12 +6,9 @@ import lcsb.mapviewer.common.IProgressUpdater; 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; /** * Service that manages models (maps). @@ -28,8 +25,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. @@ -41,16 +39,6 @@ public interface IModelService { */ void cacheAllPubmedIds(Model model, IProgressUpdater updater); - /** - * Updates information in the model with the one taken from selectedProject. - * - * @param model - * model to update - * @param selectedProject - * source of data that should be used in the update - */ - void updateModel(ModelData model, ProjectView selectedProject); - /** * Removes model from application cache. * @@ -69,17 +57,6 @@ public interface IModelService { */ void cacheAllMiriamLinks(Model model, IProgressUpdater updater); - /** - * Returns {@link ModelView} for the given model. - * - * @param model - * model for which view is returned. - * @param user - * user for which custom layouts should be added - * @return {@link ModelView} for the given {@link Model} - */ - ModelView getModelView(Model model, User user); - /** * Removes model from application cache. * @@ -126,5 +103,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..d3a236cfb7fe828b643bc1689cb1c2bb4328d6eb 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IProjectService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IProjectService.java @@ -11,8 +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; /** * Service that manages projects. @@ -29,8 +27,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,38 +45,9 @@ public interface IProjectService { * Returns list of all projects. * * @return list of all projects. + * @throws SecurityException */ - List<Project> getAllProjects(AuthenticationToken token); - - /** - * Returns a list of Project views for all projects. - * - * @return list of Project views for all projects - */ - List<ProjectView> getAllProjectViews(AuthenticationToken token); - - /** - * Updates project. - * - * @param projectView - * project view with the data to update - */ - void updateProject(ProjectView projectView); - - /** - * Removes project from the system. - * - * @param homeDir - * directory where the system is deployed - * - * @param projectView - * information about project to remove - * @param async - * should the operation be done asynchronously - * @throws UserAccessException - */ - void removeProject(ProjectView projectView, String homeDir, boolean async, AuthenticationToken token) - throws UserAccessException; + List<Project> getAllProjects(String token) throws SecurityException; /** * Removes project from the system. @@ -88,20 +58,9 @@ public interface IProjectService { * object to remove * @param async * should the operation be done asynchronously - * @throws UserAccessException - */ - void removeProject(Project project, String homeDir, boolean async, AuthenticationToken token) - throws UserAccessException; - - /** - * Gets view of the project by the {@link Project#projectId project identifier}. - * - * @param projectId - * {@link Project#projectId project identifier} - * @return view of the project - * @throws UserAccessException + * @throws SecurityException */ - ProjectView getProjectViewByProjectId(String projectId, AuthenticationToken token) throws UserAccessException; + void removeProject(Project project, String homeDir, boolean async, String token) throws SecurityException; /** * Adds project to the system. @@ -111,16 +70,6 @@ public interface IProjectService { */ void addProject(Project project); - /** - * Return the view of the project identified by database identifier. - * - * @param id - * database identifier of the project - * @return project view - * @throws UserAccessException - */ - ProjectView getProjectViewById(Integer id, AuthenticationToken token) throws UserAccessException; - /** * Creates project using give parameters. See {@link CreateProjectParams}. * @@ -130,13 +79,6 @@ public interface IProjectService { */ void createProject(CreateProjectParams params) throws SecurityException; - /** - * Creates empty {@link ProjectView}. - * - * @return empty {@link ProjectView} - */ - ProjectView createEmpty(); - /** * Creates {@link TreeNode} that contains information about all classes that can * be annotated and associate set of @@ -155,7 +97,7 @@ public interface IProjectService { * given user and default params used when creating project. * * @param user - * user for which we updte information + * user for which we update information * @param sbgnFormat * new * {@link lcsb.mapviewer.model.user.UserAnnotationSchema#sbgnFormat} @@ -179,18 +121,6 @@ public interface IProjectService { */ void updateProject(Project project); - /** - * Returns content of the file that was 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 - * @return content of the file that was used to create project given in the - * parameter - */ - byte[] getInputDataForProject(ProjectView projectView); - UserAnnotationSchema prepareUserAnnotationSchema(User user); /** 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/ISearchService.java b/service/src/main/java/lcsb/mapviewer/services/interfaces/ISearchService.java index 1229bba669f7c0ff77bcaeda5157200b0a63c60f..08d53f7a875f8bc6ab58f5127e11a778c07fc043 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/ISearchService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/ISearchService.java @@ -278,7 +278,7 @@ public interface ISearchService { * @param perfectMatch * should the match be perfect * @param ipAddress - * ip address of a client who is searchin (used for logging purpose) + * ip address of a client who is searching (used for logging purpose) * @return list of objects that matches the query sorted by the match quality */ SearchElementResult searchByQuery(Model model, String query, int limit, Boolean perfectMatch, String ipAddress); 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 72aa5851f1c45e53928b81191eeb21e62e9470a2..d11ffec752a33098732d22d9c279e1c51a085784 100644 --- a/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java +++ b/service/src/main/java/lcsb/mapviewer/services/interfaces/IUserService.java @@ -1,6 +1,5 @@ package lcsb.mapviewer.services.interfaces; -import java.util.Collection; import java.util.List; import lcsb.mapviewer.commands.ColorExtractor; @@ -8,263 +7,195 @@ 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; /** * Service that manages users. * * @author Piotr Gawron - * + * */ public interface IUserService { - /** - * Check if its possible to login using given login and password. - * - * @param login - * user login - * @param password - * plan password - * @return {@link AuthenticationToken} if credentials are valid, - * <code>null</code> otherwise - */ - AuthenticationToken login(String login, String password); - - /** - * Returns user by login. - * - * @param login - * user login - * @return user if the login is valid, <code>null</code> otherwise - */ - User getUserByLogin(String login); - - /** - * Checks if user has a given privilege. - * - * @param user - * user for which the check is performed - * @param type - * type of the privilege - * @return <code>true</code> if user has privilege, <code>false</code> - * otherwise - */ - boolean userHasPrivilege(User user, PrivilegeType type); - - boolean userHasPrivilege(String token, PrivilegeType type) throws SecurityException; - - /** - * Returns level of the user privilege. - * - * @param user - * user for which the check is performed - * @param type - * type of the privilege - * @return level of the privilege - */ - int getUserPrivilegeLevel(User user, PrivilegeType type); - - /** - * Checks if user has a given privilege on the object. - * - * @param user - * user for which the check is performed - * @param type - * type of the privilege - * @param object - * object of the privilege - * @return <code>true</code> if user has privilege, <code>false</code> - * otherwise - */ - boolean userHasPrivilege(User user, PrivilegeType type, Object object); - - /** - * Returns level of the user privilege. - * - * @param object - * object of the privilege - * @param user - * user for which the check is performed - * @param type - * type of the privilege - * @return level of the privilege - */ - int getUserPrivilegeLevel(User user, PrivilegeType type, Object object); - - /** - * Sets the user privilege. - * - * @param user - * user for whom the privilege should be granted/dropped - * @param privilege - * user privilege - */ - void setUserPrivilege(User user, BasicPrivilege privilege); - - /** - * Adds user to the system. - * - * @param user - * user to be added - */ - void addUser(User user); - - /** - * Updates user in the system. - * - * @param user - * user to be updated - */ - void updateUser(User user); - - /** - * Removes user from the system. - * - * @param user - * user to be removed - */ - void deleteUser(User user); - - /** - * Returns user by the database identifier. - * - * @param id - * database identifier - * @return user for the given identifier, null if user doesn't exist - * - */ - User getUserById(int id); - - /** - * Returns user views for all users. - * - * @return list of user {@link lcsb.mapviewer.services.view.AbstractView - * views} for all users - */ - List<UserView> getAllUserRows(); - - /** - * @param user - * user that will have view. - * @return view for one user. - */ - UserView getUserRow(User user); - - /** - * Updates user from user {@link lcsb.mapviewer.services.view.AbstractView - * view}. - * - * @param selectedUser - * user {@link lcsb.mapviewer.services.view.AbstractView view} to - * update - */ - void updateUser(UserView selectedUser); - - /** - * Removes user based on user {@link lcsb.mapviewer.services.view.AbstractView - * view}. - * - * @param selectedUser - * user {@link lcsb.mapviewer.services.view.AbstractView view} to be - * removed - */ - void deleteUser(UserView selectedUser); - - /** - * Creates empty view. - * - * @return empty user {@link lcsb.mapviewer.services.view.AbstractView view} . - */ - UserView createEmptyUserRow(); - - /** - * Drops privileges for every user on the given object and type. - * - * @param type - * type of privilege that should be dropped - * @param objectId - * identifier of the object to which privileges should be dropped - */ - void dropPrivilegesForObjectType(PrivilegeType type, int objectId); - - /** - * Adds user from user view. - * - * @param selectedUser - * user view representation that should be added - */ - void addUser(UserView selectedUser); - - /** - * Adds privilege to the user. - * - * @param user - * user to which privilege should be added - * @param type - * type of the privilege - */ - void setUserPrivilege(User user, PrivilegeType type, Integer value); - - /** - * Updates users from list of user - * {@link lcsb.mapviewer.services.view.AbstractView view}. - * - * @param users - * user {@link lcsb.mapviewer.services.view.AbstractView views} to - * update - */ - void updateUsers(Collection<UserView> users); - - /** - * @param password - * input password - * @return encoded password - */ - String encodePassword(String password); - - /** - * Returns {@link User} for given "name surname" string. - * - * @param nameSurnameString - * string identifying user with name and surname separated by single - * space - * @return {@link User} for given "name surname" string - */ - User getUserByNameSurname(String nameSurnameString); - - /** - * Returns {@link ColorExtractor} that transform overlay values into colors - * for given user. - * - * @param user - * {@link User} for which {@link ColorExtractor} will be obtained - * @return {@link ColorExtractor} that transform overlay values into colors - * for given user - */ - 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); - - void logout(String tokenString) throws SecurityException; - - void logout(AuthenticationToken token); - - boolean userHasPrivilege(AuthenticationToken token, PrivilegeType addMap); - - User getUserById(String creatorId, AuthenticationToken authenticationToken) throws SecurityException; - - List<User> getUsers(AuthenticationToken token) throws SecurityException; - - void setUserPrivilege(User modifiedUser, PrivilegeType type, Object privilegeToSet, AuthenticationToken authenticationToken) throws SecurityException; - - void setUserPrivilege(User modifiedUser, PrivilegeType type, Object privilegeToSet, Integer objectId, AuthenticationToken authenticationToken) throws SecurityException; - - void updateUser(User modifiedUser, AuthenticationToken authenticationToken) throws SecurityException; + /** + * Check if its possible to login using given login and password. + * + * @param login + * user login + * @param password + * plan password + * @return {@link String} containing session id if credentials are valid, + * <code>null</code> otherwise + */ + String login(String login, String password); + + /** + * Returns user by login. + * + * @param login + * user login + * @return user if the login is valid, <code>null</code> otherwise + */ + User getUserByLogin(String login); + + /** + * Checks if user has a given privilege. + * + * @param user + * user for which the check is performed + * @param type + * type of the privilege + * @return <code>true</code> if user has privilege, <code>false</code> otherwise + */ + boolean userHasPrivilege(User user, PrivilegeType type); + + /** + * Returns level of the user privilege. + * + * @param user + * user for which the check is performed + * @param type + * type of the privilege + * @return level of the privilege + */ + int getUserPrivilegeLevel(User user, PrivilegeType type); + + /** + * Checks if user has a given privilege on the object. + * + * @param user + * user for which the check is performed + * @param type + * type of the privilege + * @param object + * object of the privilege + * @return <code>true</code> if user has privilege, <code>false</code> otherwise + */ + boolean userHasPrivilege(User user, PrivilegeType type, Object object); + + /** + * Returns level of the user privilege. + * + * @param object + * object of the privilege + * @param user + * user for which the check is performed + * @param type + * type of the privilege + * @return level of the privilege + */ + int getUserPrivilegeLevel(User user, PrivilegeType type, Object object); + + /** + * Sets the user privilege. + * + * @param user + * user for whom the privilege should be granted/dropped + * @param privilege + * user privilege + */ + void setUserPrivilege(User user, BasicPrivilege privilege); + + /** + * Adds user to the system. + * + * @param user + * user to be added + */ + void addUser(User user); + + /** + * Updates user in the system. + * + * @param user + * user to be updated + */ + void updateUser(User user); + + /** + * Removes user from the system. + * + * @param user + * user to be removed + */ + void deleteUser(User user); + + /** + * Returns user by the database identifier. + * + * @param id + * database identifier + * @return user for the given identifier, null if user doesn't exist + * + */ + User getUserById(int id); + + /** + * Drops privileges for every user on the given object and type. + * + * @param type + * type of privilege that should be dropped + * @param objectId + * identifier of the object to which privileges should be dropped + */ + void dropPrivilegesForObjectType(PrivilegeType type, int objectId); + + /** + * Adds privilege to the user. + * + * @param user + * user to which privilege should be added + * @param type + * type of the privilege + */ + void setUserPrivilege(User user, PrivilegeType type, Integer value); + + /** + * @param password + * input password + * @return encoded password + */ + String encodePassword(String password); + + /** + * Returns {@link User} for given "name surname" string. + * + * @param nameSurnameString + * string identifying user with name and surname separated by single + * space + * @return {@link User} for given "name surname" string + */ + User getUserByNameSurname(String nameSurnameString); + + /** + * Returns {@link ColorExtractor} that transform overlay values into colors for + * given user. + * + * @param user + * {@link User} for which {@link ColorExtractor} will be obtained + * @return {@link ColorExtractor} that transform overlay values into colors for + * given user + */ + ColorExtractor getColorExtractorForUser(User user); + + User getUserByToken(String token) throws SecurityException; + + boolean userHasPrivilege(String token, PrivilegeType type, Object object) throws SecurityException; + + void logout(String tokenString) throws SecurityException; + + boolean userHasPrivilege(String token, PrivilegeType addMap) throws SecurityException; + + User getUserById(String creatorId, String token) throws SecurityException; + + List<User> getUsers(String token) throws SecurityException; + + void setUserPrivilege(User modifiedUser, PrivilegeType type, Object privilegeToSet, String authenticationToken) + throws SecurityException; + + void setUserPrivilege(User modifiedUser, PrivilegeType type, Object privilegeToSet, Integer objectId, + String authenticationToken) throws SecurityException; + + void updateUser(User modifiedUser, String authenticationToken) throws SecurityException; + + String login(String login, String password, String id); } diff --git a/service/src/main/java/lcsb/mapviewer/services/search/ElementIdentifierDetails.java b/service/src/main/java/lcsb/mapviewer/services/search/ElementIdentifierDetails.java deleted file mode 100644 index 3607fee90cf440838212776ba5dc740d91b41e5e..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/search/ElementIdentifierDetails.java +++ /dev/null @@ -1,18 +0,0 @@ -package lcsb.mapviewer.services.search; - -import java.io.Serializable; - -/** - * Class with detailed information about elements for specific search result. - * - * @author Piotr Gawron - * - */ -public abstract class ElementIdentifierDetails implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - -} diff --git a/service/src/main/java/lcsb/mapviewer/services/search/comment/CommentDetails.java b/service/src/main/java/lcsb/mapviewer/services/search/comment/CommentDetails.java deleted file mode 100644 index 87315d0d248f888326842739a830ac5f9612559c..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/search/comment/CommentDetails.java +++ /dev/null @@ -1,87 +0,0 @@ -package lcsb.mapviewer.services.search.comment; - -import lcsb.mapviewer.model.map.Comment; -import lcsb.mapviewer.services.search.ElementIdentifierDetails; - -/** - * Class with detailed information about element comments. - * - * @author Piotr Gawron - * - */ -public class CommentDetails extends ElementIdentifierDetails { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Identifier of the comment. - */ - private String commentId; - - /** - * Content of the comment. - */ - private String commentContent; - - /** - * Default constructor. - * - * @param id - * {@link #commentId} - * @param content - * {@link #commentContent} - */ - public CommentDetails(String id, String content) { - this.commentId = id; - this.commentContent = content; - } - - /** - * Default constructor. - * - * @param comment - * comment with detailed information - */ - public CommentDetails(Comment comment) { - commentId = comment.getId() + ""; - commentContent = comment.getContent(); - } - - /** - * @return the commentId - * @see #commentId - */ - public String getCommentId() { - return commentId; - } - - /** - * @param commentId - * the commentId to set - * @see #commentId - */ - public void setCommentId(String commentId) { - this.commentId = commentId; - } - - /** - * @return the commentContent - * @see #commentContent - */ - public String getCommentContent() { - return commentContent; - } - - /** - * @param commentContent - * the commentContent to set - * @see #commentContent - */ - public void setCommentContent(String commentContent) { - this.commentContent = commentContent; - } - -} diff --git a/service/src/main/java/lcsb/mapviewer/services/search/comment/FullCommentView.java b/service/src/main/java/lcsb/mapviewer/services/search/comment/FullCommentView.java deleted file mode 100644 index 871f7150b1283c56cc0f49f63839aee84398e0c7..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/search/comment/FullCommentView.java +++ /dev/null @@ -1,97 +0,0 @@ -package lcsb.mapviewer.services.search.comment; - -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.List; - -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.services.search.ISearchResultView; - -/** - * This class represent data that are sent into the client (by designe Google - * Map object, but not necessery). It is connected to the comment on the map. It - * contains information required for vizualization like localization - * information. However, there are no information about formating, css, etc. - * - * @author Piotr Gawron - * - */ -public class FullCommentView extends LightCommentView implements ISearchResultView { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * List of comments in the marker. {@link Pair#left} is id of a comment; - * {@link Pair#right} is a content. - */ - private List<Pair<String, String>> comments = new ArrayList<Pair<String, String>>(); - - /** - * Type of the object that is commented. - */ - private Class<?> type = null; - - /** - * Default constructor. - * - * @param point - * {@link Point2D} where the comment is placed - * @param idModel - * identifier of the model where comment is placed - * - */ - public FullCommentView(Point2D point, Integer idModel) { - super(point, idModel); - } - - /** - * Default constructor. - * - * @param objectId - * identifier of the element that is commented - * @param idModel - * identifier of the model where comment is placed - * - */ - public FullCommentView(Integer objectId, Integer idModel) { - super(objectId, idModel); - } - - /** - * @return the comments - * @see #comments - */ - public List<Pair<String, String>> getComments() { - return comments; - } - - /** - * @param comments - * the comments to set - * @see #comments - */ - public void setComments(List<Pair<String, String>> comments) { - this.comments = comments; - } - - /** - * @return the type - * @see #type - */ - public Class<?> getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(Class<?> type) { - this.type = type; - } - -} diff --git a/service/src/main/java/lcsb/mapviewer/services/search/comment/FullCommentViewFactory.java b/service/src/main/java/lcsb/mapviewer/services/search/comment/FullCommentViewFactory.java deleted file mode 100644 index 928f73601844211250078e22b1fcd960eb6c5f51..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/search/comment/FullCommentViewFactory.java +++ /dev/null @@ -1,84 +0,0 @@ -package lcsb.mapviewer.services.search.comment; - -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import com.google.gson.Gson; - -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.map.Comment; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.services.overlay.IconManager; -import lcsb.mapviewer.services.search.SearchResultFactory; -import lcsb.mapviewer.services.search.data.ElementIdentifier; -import lcsb.mapviewer.services.search.data.ElementIdentifier.ElementIdentifierType; - -/** - * Factory class for {@link FullCommentView} class. - * - * @author Piotr Gawron - * - */ -public class FullCommentViewFactory extends SearchResultFactory<List<Comment>, FullCommentView> { - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = Logger.getLogger(FullCommentViewFactory.class); - - @Override - public FullCommentView create(List<Comment> list) { - Point2D point = new Point2D.Double(0, 0); - Comment comment = list.get(0); - Class<?> type; - FullCommentView result; - if (comment.getTableName() != null) { - result = new FullCommentView(comment.getTableId(), comment.getSubmodelData().getId()); - if (comment.getTableName().getName().contains("Reaction")) { - type = Reaction.class; - } else { - type = Element.class; - } - } else { - point.setLocation(comment.getCoordinates().getX(), comment.getCoordinates().getY()); - result = new FullCommentView(point, comment.getSubmodelData().getId()); - type = Point2D.class; - } - result.setType(type); - - for (int i = 0; i < list.size(); i++) { - Pair<String, String> pair = new Pair<String, String>("" + list.get(i).getId(), list.get(i).getContent()); - result.getComments().add(pair); - } - return result; - } - - @Override - public String createGson(FullCommentView object) { - return new Gson().toJson(object); - } - - @Override - public List<ElementIdentifier> searchResultToElementIdentifier(FullCommentView comment, Model model) { - List<ElementIdentifier> result = new ArrayList<>(); - if (Reaction.class.equals(comment.getType())) { - result - .add(new ElementIdentifier(comment.getIdObject(), comment.getModelId(), ElementIdentifierType.REACTION, IconManager.getInstance().getCommentIcon())); - } else if (Element.class.equals(comment.getType())) { - result.add(new ElementIdentifier(comment.getIdObject(), comment.getModelId(), ElementIdentifierType.ALIAS, IconManager.getInstance().getCommentIcon())); - } else if (Point2D.class.equals(comment.getType())) { - result.add(new ElementIdentifier(comment.getIdObject(), comment.getModelId(), ElementIdentifierType.POINT, IconManager.getInstance().getCommentIcon())); - } else { - throw new InvalidArgumentException("Unknown comment type: " + comment.getType()); - } - return result; - } - -} diff --git a/service/src/main/java/lcsb/mapviewer/services/search/comment/LightCommentView.java b/service/src/main/java/lcsb/mapviewer/services/search/comment/LightCommentView.java deleted file mode 100644 index 9758b6f03a5c46a0e25c8e814b62594bb72c5420..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/search/comment/LightCommentView.java +++ /dev/null @@ -1,54 +0,0 @@ -package lcsb.mapviewer.services.search.comment; - -import java.awt.geom.Point2D; - -import lcsb.mapviewer.services.search.ElementView; - -/** - * Light {@link ElementView view} for comment representing data that should be - * send to client. - * - * @author Piotr Gawron - * - */ -public class LightCommentView extends ElementView { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - * - * @param point - * {@link Point2D} where the comment is placed - * @param idModel - * identifier of the model where comment is placed - * - */ - protected LightCommentView(Point2D point, Integer idModel) { - super(point.toString(), idModel); - } - - /** - * Default constructor. - * - * @param objectId - * identifier of the element that is commented - * @param idModel - * identifier of the model where comment is placed - * - */ - protected LightCommentView(Integer objectId, Integer idModel) { - super(objectId, idModel); - } - - /** - * Constructor that should be used only for (de)serialization. - */ - protected LightCommentView() { - super(); - } - -} diff --git a/service/src/main/java/lcsb/mapviewer/services/search/comment/package-info.java b/service/src/main/java/lcsb/mapviewer/services/search/comment/package-info.java deleted file mode 100644 index d8e30b66a4dd7ab6d6e0982d8089914143809346..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/search/comment/package-info.java +++ /dev/null @@ -1,8 +0,0 @@ -/** - * This package contains structures used for passing data about comments to - * client. - * <p/> - * Be carefull when refactoring classes in this package. Data are accessed not - * directly (not via managable code) by client side. - */ -package lcsb.mapviewer.services.search.comment; diff --git a/service/src/main/java/lcsb/mapviewer/services/utils/ColorSchemaReader.java b/service/src/main/java/lcsb/mapviewer/services/utils/ColorSchemaReader.java index 624927757ad13fdfeaf903dbf2ec635a08bc84b6..7a4fd265978fe7fba61bd6ac405d6404ea934784 100644 --- a/service/src/main/java/lcsb/mapviewer/services/utils/ColorSchemaReader.java +++ b/service/src/main/java/lcsb/mapviewer/services/utils/ColorSchemaReader.java @@ -457,7 +457,6 @@ public class ColorSchemaReader { */ protected Collection<ColorSchema> readGenericColorSchema(InputStream colorInputStream) throws IOException, InvalidColorSchemaException { - MiriamConnector mc = new MiriamConnector(); List<ColorSchema> result = new ArrayList<>(); BufferedReader br = new BufferedReader(new InputStreamReader(colorInputStream)); 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/AbstractTargetView.java b/service/src/main/java/lcsb/mapviewer/services/view/AbstractTargetView.java deleted file mode 100644 index 9e633bfd0b89b5e8e9d7ae0f92f5756ea1cd3406..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/AbstractTargetView.java +++ /dev/null @@ -1,136 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.io.Serializable; - -/** - * View representation. - * - * @author Ayan Rota - * - */ -public class AbstractTargetView implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Icon associated with the target. - */ - private String icon; - - /** - * Type of the target. Possible values are set in - */ - private String type; - - /** - * Is the target selectable by client. - */ - private Boolean selectable = false; - - /** - * Is the target selected by client. - */ - private Boolean selected = false; - - /** - * Is the target visiblke to the client. - */ - private Boolean visible = false; - - /** - * defualt constructor. - */ - public AbstractTargetView() { - super(); - } - - - /** - * @return the icon - * @see #icon - */ - public String getIcon() { - return icon; - } - - /** - * @param icon - * the icon to set - * @see #icon - */ - public void setIcon(String icon) { - this.icon = icon; - } - - /** - * @return the selectable - * @see #selectable - */ - public Boolean getSelectable() { - return selectable; - } - - /** - * @param selectable - * the selectable to set - * @see #selectable - */ - public void setSelectable(Boolean selectable) { - this.selectable = selectable; - } - - /** - * @return the selected - * @see #selected - */ - public Boolean getSelected() { - return selected; - } - - /** - * @param selected - * the selected to set - * @see #selected - */ - public void setSelected(Boolean selected) { - this.selected = selected; - } - - /** - * @return the visible - * @see #visible - */ - public Boolean getVisible() { - return visible; - } - - /** - * @param visible - * the visible to set - * @see #visible - */ - public void setVisible(Boolean visible) { - this.visible = visible; - } - - /** - * @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; - } - -} 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 91c065e193130b13e07382cdc785f9ac517f9fca..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/AuthenticationToken.java +++ /dev/null @@ -1,41 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.math.BigInteger; -import java.security.SecureRandom; -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Random; - -public class AuthenticationToken { - private String id; - private Calendar expires; - - public AuthenticationToken() { - Random random = new SecureRandom(); - id = new BigInteger(130, random).toString(32); - 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/main/java/lcsb/mapviewer/services/view/CommentView.java b/service/src/main/java/lcsb/mapviewer/services/view/CommentView.java deleted file mode 100644 index 0cffa23ff649c375f47ef58cec582288f11ac1cd..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/CommentView.java +++ /dev/null @@ -1,292 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.io.Serializable; - -import lcsb.mapviewer.model.map.Comment; - -/** - * View representation of the Comment. - * - * @author Piotr Gawron - * - */ - -public class CommentView extends AbstractView<Comment> implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Author of the comment. - */ - private String author; - - /** - * Email of the comment. - */ - private String email; - - /** - * Content of the comment. - */ - private String content; - - /** - * Title of the comment. - */ - private String title; - - /** - * Is the comment visible on the map. - */ - private String pinned; - - /** - * Is the comment removed. - */ - private String removed; - - /** - * X coordinate on the map. - */ - private String xCoord; - - /** - * Y coordinate on the map. - */ - private String yCoord; - - /** - * Zoom level at which comment should be investigated on the map (to see - * details). - */ - private String zoom; - - /** - * Submap on which comment was placed. - */ - private String submap; - - /** - * Constructor that initialize the view with the data from original comment. - * - * @param comment - * data required for initialization - */ - protected CommentView(final Comment comment) { - super(comment); - } - - /** - * Default constructor. Should be used only for deserialization. - */ - protected CommentView() { - } - - /** - * @return the author - * @see #author - */ - public String getAuthor() { - return author; - } - - /** - * @param author - * the author to set - * @see #author - */ - public void setAuthor(String author) { - this.author = author; - } - - /** - * @return the email - * @see #email - */ - public String getEmail() { - return email; - } - - /** - * @param email - * the email to set - * @see #email - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return the content - * @see #content - */ - public String getContent() { - return content; - } - - /** - * @param content - * the content to set - * @see #content - */ - public void setContent(String content) { - this.content = content; - } - - /** - * @return the title - * @see #title - */ - public String getTitle() { - return title; - } - - /** - * @param title - * the title to set - * @see #title - */ - public void setTitle(String title) { - this.title = title; - } - - /** - * @return the pinned - * @see #pinned - */ - public String getPinned() { - return pinned; - } - - /** - * @param pinned - * the pinned to set - * @see #pinned - */ - public void setPinned(String pinned) { - this.pinned = pinned; - } - - /** - * @return the removed - * @see #removed - */ - public String getRemoved() { - return removed; - } - - /** - * @param removed - * the removed to set - * @see #removed - */ - public void setRemoved(String removed) { - this.removed = removed; - } - - /** - * @return the xCoord - * @see #xCoord - */ - public String getxCoord() { - return xCoord; - } - - /** - * @param xCoord - * the xCoord to set - * @see #xCoord - */ - public void setxCoord(String xCoord) { - this.xCoord = xCoord; - } - - /** - * @return the yCoord - * @see #yCoord - */ - public String getyCoord() { - return yCoord; - } - - /** - * @param yCoord - * the yCoord to set - * @see #yCoord - */ - public void setyCoord(String yCoord) { - this.yCoord = yCoord; - } - - /** - * @return the zoom - * @see #zoom - */ - public String getZoom() { - return zoom; - } - - /** - * @param zoom - * the zoom to set - * @see #zoom - */ - public void setZoom(String zoom) { - this.zoom = zoom; - } - - /** - * @param pinned - * the pinned to set - * @see #pinned - */ - public void setPinned(final boolean pinned) { - if (pinned) { - setPinned("YES"); - } else { - setPinned("NO"); - } - } - - /** - * Sets x coordinate. - * - * @param x - * x coordinate to set - * @see #xCoord - */ - public void setxCoord(double x) { - this.xCoord = x + ""; - } - - /** - * Sets y coordinate. - * - * @param y - * y coordinate to set - * @see #yCoord - */ - public void setyCoord(double y) { - this.yCoord = y + ""; - } - - /** - * @return the submap - * @see #submap - */ - public String getSubmap() { - return submap; - } - - /** - * @param submap - * the submap to set - * @see #submap - */ - public void setSubmap(String submap) { - this.submap = submap; - } -}; diff --git a/service/src/main/java/lcsb/mapviewer/services/view/CommentViewFactory.java b/service/src/main/java/lcsb/mapviewer/services/view/CommentViewFactory.java deleted file mode 100644 index 09b831833228255f96aa223f8f49373fc0ad7562..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/CommentViewFactory.java +++ /dev/null @@ -1,116 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.awt.geom.Point2D; - -import org.apache.log4j.Logger; - -import com.google.gson.Gson; - -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.Comment; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; - -/** - * Factory class for {@link CommentView} class. - * - * @author Piotr Gawron - * - */ -public class CommentViewFactory extends AbstractViewFactory<Comment, CommentView> { - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(CommentViewFactory.class); - - @Override - public CommentView create(Comment comment) { - CommentView result = new CommentView(comment); - if (comment == null) { - return result; - } - Model model = comment.getModelData().getModel(); - return create(comment, model); - } - - /** - * Creates a {@link CommentView} object for given comment. - * - * @param comment - * comment for which view is created - * @param model - * model where comments is placed - * @return {@link CommentView} object for given comment - */ - public CommentView create(Comment comment, Model model) { - CommentView result = new CommentView(comment); - if (comment == null) { - return result; - } - - result.setAuthor(comment.getName()); - result.setContent(comment.getContent()); - result.setEmail(comment.getEmail()); - result.setPinned(comment.isPinned()); - if (comment.isDeleted()) { - result.setRemoved("YES (" + comment.getRemoveReason() + ")"); - } else { - result.setRemoved("NO"); - } - if (comment.getSubmodelData() != null) { - result.setSubmap(comment.getSubmodelData().getId() + ""); - model = model.getSubmodelById(comment.getSubmodelData().getId()); - if (model == null) { - throw new InvalidArgumentException("Cannot find submodel with id: " + comment.getSubmodelData().getId()); - } - } - - String title = ""; - Point2D coordinates = null; - if (comment.getCoordinates() != null) { - title = "Comment (coord: " + String.format("%.2f", comment.getCoordinates().getX()) + ", " + String.format("%.2f", comment.getCoordinates().getY()) - + ")"; - coordinates = comment.getCoordinates(); - } - if (comment.getTableName() != null) { - if (comment.getTableName().getName().contains("Reaction")) { - Reaction reaction = model.getReactionByDbId(comment.getTableId()); - if (reaction != null) { - title = "Reaction " + reaction.getIdReaction(); - coordinates = reaction.getCenterPoint(); - } else { - logger.warn("Invalid reaction dbID: " + comment.getTableId()); - } - - } else { - Element alias = model.getElementByDbId(comment.getTableId()); - if (alias != null) { - title = alias.getName(); - coordinates = alias.getCenter(); - } else { - logger.warn("Invalid alias dbID: " + comment.getTableId()); - } - } - } - result.setTitle(title); - if (coordinates != null) { - result.setxCoord(coordinates.getX()); - result.setyCoord(coordinates.getY()); - result.setZoom("" + (Configuration.MIN_ZOOM_LEVEL + model.getZoomLevels() - 1)); - } - return result; - } - - @Override - public String createGson(CommentView object) { - return new Gson().toJson(object); - } - - @Override - public Comment viewToObject(CommentView view) { - throw new NotImplementedException(); - } -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/ModelView.java b/service/src/main/java/lcsb/mapviewer/services/view/ModelView.java deleted file mode 100644 index 2780593bd456eb2f2f407d6a645ca4158bcafe00..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/ModelView.java +++ /dev/null @@ -1,418 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.io.Serializable; -import java.util.List; - -import lcsb.mapviewer.model.map.model.Model; - -import org.apache.log4j.Logger; -import org.primefaces.model.map.LatLng; - -/** - * View representatin of a model. It's a light structre that present - * {@link Model} data to the client side. - * - * @author Piotr Gawron - * - */ -public class ModelView extends AbstractView<Model> implements Serializable { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = Logger.getLogger(ModelView.class); - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Version of the model. - */ - private String version; - - /** - * Name of the model. - */ - private String name; - - /** - * {@link lcsb.mapviewer.model.Project#projectId Project identifier}. - */ - private String projectId; - - /** - * Description of the model. - */ - private String description; - /** - * Size in pixels of the single square tile (small image used for graphical - * representation). - */ - private Integer tileSize; - /** - * Size of the whole map. - */ - private Integer pictureSize; - /** - * Minimum zoom level that should be allowed by the Google Maps API. - */ - private Integer minZoom; - /** - * Maximum zoom level that should be allowed by the Google Maps API. - */ - private Integer maxZoom; - /** - * Public layouts available for the model. - */ - private List<LayoutView> layouts; - - /** - * Custom layouts available only for the current user. - */ - private List<LayoutView> customLayouts; - - /** - * List of submodels in the model. - */ - private List<ModelView> submodels; - - /** - * Where is the center of the map in latituted, longiude format. - */ - private LatLng centerLatLng; - - /** - * Top-Left corner of the map (0,0) as a latLng coordinates. - */ - private LatLng topLeftLatLng; - - /** - * Bottom-Right corner of the map (width,height) as a latLng coordinates. - */ - private LatLng bottomRightLatLng; - - /** - * Should the map be automatically fit in the browser window. Bean should - * change this value if the map was already viewed by user and there is - * information about zoom level and coordinates where user is browsing it. - */ - private Boolean fitMapBounds = true; - - /** - * List of overview images attached to this model. - */ - private List<OverviewImageView> overviewImageViews; - - /** - * Top level overview image. - */ - private OverviewImageView topOverviewImage; - - /** - * Default constructor which creates view representation from the orignial - * model. - * - * @param model - * source map model - */ - protected ModelView(Model model) { - super(model); - } - - /** - * Default constructor. Should be used only for deserialization. - */ - protected ModelView() { - } - - /** - * @return the version - * @see #version - */ - public String getVersion() { - return version; - } - - /** - * @param version - * the version to set - * @see #version - */ - public void setVersion(String version) { - this.version = version; - } - - /** - * @return the description - * @see #description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - * @see #description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the tileSize - * @see #tileSize - */ - public Integer getTileSize() { - return tileSize; - } - - /** - * @param tileSize - * the tileSize to set - * @see #tileSize - */ - public void setTileSize(Integer tileSize) { - this.tileSize = tileSize; - } - - /** - * @return the pictureSize - * @see #pictureSize - */ - public Integer getPictureSize() { - return pictureSize; - } - - /** - * @param pictureSize - * the pictureSize to set - * @see #pictureSize - */ - public void setPictureSize(Integer pictureSize) { - this.pictureSize = pictureSize; - } - - /** - * @return the minZoom - * @see #minZoom - */ - public Integer getMinZoom() { - return minZoom; - } - - /** - * @param minZoom - * the minZoom to set - * @see #minZoom - */ - public void setMinZoom(Integer minZoom) { - this.minZoom = minZoom; - } - - /** - * @return the maxZoom - * @see #maxZoom - */ - public Integer getMaxZoom() { - return maxZoom; - } - - /** - * @param maxZoom - * the maxZoom to set - * @see #maxZoom - */ - public void setMaxZoom(Integer maxZoom) { - this.maxZoom = maxZoom; - } - - /** - * @return the layouts - * @see #layouts - */ - public List<LayoutView> getLayouts() { - return layouts; - } - - /** - * @param layouts - * the layouts to set - * @see #layouts - */ - public void setLayouts(List<LayoutView> layouts) { - this.layouts = layouts; - } - - /** - * @return the centerLatLng - * @see #centerLatLng - */ - public LatLng getCenterLatLng() { - return centerLatLng; - } - - /** - * @param centerLatLng - * the centerLatLng to set - * @see #centerLatLng - */ - public void setCenterLatLng(LatLng centerLatLng) { - this.centerLatLng = centerLatLng; - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @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 submodels - * @see #submodels - */ - public List<ModelView> getSubmodels() { - return submodels; - } - - /** - * @param submodels - * the submodels to set - * @see #submodels - */ - public void setSubmodels(List<ModelView> submodels) { - this.submodels = submodels; - } - - /** - * @return the overviewImageViews - * @see #overviewImageViews - */ - public List<OverviewImageView> getOverviewImageViews() { - return overviewImageViews; - } - - /** - * @param overviewImageViews - * the overviewImageViews to set - * @see #overviewImageViews - */ - public void setOverviewImageViews(List<OverviewImageView> overviewImageViews) { - this.overviewImageViews = overviewImageViews; - } - - /** - * @return the topOverviewImage - * @see #topOverviewImage - */ - public OverviewImageView getTopOverviewImage() { - return topOverviewImage; - } - - /** - * @param topOverviewImage - * the topOverviewImage to set - * @see #topOverviewImage - */ - public void setTopOverviewImage(OverviewImageView topOverviewImage) { - this.topOverviewImage = topOverviewImage; - } - - /** - * @return the topLeftLatLng - * @see #topLeftLatLng - */ - public LatLng getTopLeftLatLng() { - return topLeftLatLng; - } - - /** - * @param topLeftLatLng - * the topLeftLatLng to set - * @see #topLeftLatLng - */ - public void setTopLeftLatLng(LatLng topLeftLatLng) { - this.topLeftLatLng = topLeftLatLng; - } - - /** - * @return the bottomRightLatLng - * @see #bottomRightLatLng - */ - public LatLng getBottomRightLatLng() { - return bottomRightLatLng; - } - - /** - * @param bottomRightLatLng - * the bottomRightLatLng to set - * @see #bottomRightLatLng - */ - public void setBottomRightLatLng(LatLng bottomRightLatLng) { - this.bottomRightLatLng = bottomRightLatLng; - } - - /** - * @return the fitMapBounds - * @see #fitMapBounds - */ - public Boolean getFitMapBounds() { - return fitMapBounds; - } - - /** - * @param fitMapBounds - * the fitMapBounds to set - * @see #fitMapBounds - */ - public void setFitMapBounds(Boolean fitMapBounds) { - this.fitMapBounds = fitMapBounds; - } - - /** - * @return the projectId - * @see #projectId - */ - public String getProjectId() { - return projectId; - } - - /** - * @param projectId - * the projectName to set - * @see #projectId - */ - public void setProjectId(String projectId) { - this.projectId = projectId; - } - -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/ModelViewFactory.java b/service/src/main/java/lcsb/mapviewer/services/view/ModelViewFactory.java deleted file mode 100644 index 673700f9f80f8d1d5c4286c8225740ab6829c875..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/ModelViewFactory.java +++ /dev/null @@ -1,99 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.awt.geom.Point2D; -import java.util.ArrayList; -import java.util.List; - -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.services.utils.gmap.CoordinationConverter; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.transaction.annotation.Transactional; - -import lcsb.mapviewer.common.exception.NotImplementedException; - -import com.google.gson.Gson; - -/** - * Factory class for {@link ModelView} class. - * - * @author Piotr Gawron - * - */ -@Transactional(value = "txManager") -public class ModelViewFactory extends AbstractViewFactory<Model, ModelView> { - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(ModelViewFactory.class); - - /** - * Factory object used for creation of {@link LayoutView} elements. - */ - @Autowired - private LayoutViewFactory layoutViewFactory; - - /** - * Factory object used for creation of {@link OverviewImageView} elements. - */ - @Autowired - private OverviewImageViewFactory overviewImageViewFactory; - - @Override - public ModelView create(Model model) { - ModelView result = new ModelView(model); - if (model == null) { - logger.warn("Empty model..."); - return result; - } - if (model.getProject() != null) { - result.setProjectId(model.getProject().getProjectId()); - result.setOverviewImageViews(overviewImageViewFactory.createList(model.getProject().getOverviewImages())); - if (result.getOverviewImageViews().size() > 0) { - result.setTopOverviewImage(overviewImageViewFactory.create(model.getProject().getTopOverviewImage())); - } - } - result.setLayouts(new ArrayList<LayoutView>()); - result.setCustomLayouts(new ArrayList<LayoutView>()); - result.setName(model.getName()); - - result.setMinZoom(Configuration.MIN_ZOOM_LEVEL); - result.setMaxZoom(result.getMinZoom() + model.getZoomLevels()); - result.setTileSize(model.getTileSize()); - result.setPictureSize((int) Math.max(model.getWidth(), model.getHeight())); - // we have to add copies (originals contain reference to model which - // shouldn't be passed to simple structure) - for (Layout layout : model.getLayouts()) { - if (layout.isPublicLayout()) { - result.getLayouts().add(layoutViewFactory.create(layout)); - } - } - CoordinationConverter cConverter = new CoordinationConverter(model); - result.setCenterLatLng(cConverter.toLatLng(new Point2D.Double(result.getPictureSize() / 2, result.getPictureSize() / 2))); - result.setBottomRightLatLng(cConverter.toLatLng(new Point2D.Double(model.getWidth(), model.getHeight()))); - result.setTopLeftLatLng(cConverter.toLatLng(new Point2D.Double(0, 0))); - - result.setDescription(model.getNotes()); - - List<ModelView> submodels = new ArrayList<ModelView>(); - for (ModelSubmodelConnection connection : model.getSubmodelConnections()) { - submodels.add(create(connection.getSubmodel().getModel())); - } - result.setSubmodels(submodels); - return result; - } - - @Override - public String createGson(ModelView object) { - return new Gson().toJson(object); - } - - @Override - public Model viewToObject(ModelView view) { - throw new NotImplementedException(); - } -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/PrivilegeView.java b/service/src/main/java/lcsb/mapviewer/services/view/PrivilegeView.java deleted file mode 100644 index c084036ba7982ce9a5bc898f3e0dfce56a7d4d4b..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/PrivilegeView.java +++ /dev/null @@ -1,206 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.io.Serializable; - -import lcsb.mapviewer.model.user.BasicPrivilege; -import lcsb.mapviewer.model.user.PrivilegeType; - -/** - * This class repesents single user privilege in the way understandable by the - * client side. - * - * @author Piotr Gawron - * - */ -public class PrivilegeView extends AbstractView<BasicPrivilege> implements Comparable<PrivilegeView>, Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * What is the name of the privilege. - */ - private String commonName; - - /** - * Does user has this privilege. - */ - private Boolean selected; - - /** - * Type associated with this privilege. - */ - private PrivilegeType type; - - /** - * If privilege is associated with some object (the privilege defines access - * level to this object) then {@link #objectId} points to database identifier - * of this object. - */ - private Integer objectId; - - /** - * Access level for this privilege. Usually it's boolean {0,1} value. However, - * some privileges (the ones that are characterized as {@link #numeric}) - * accept any integer values. - */ - private Integer level; - - /** - * This field describe if privilege is: - * <ul> - * <li>numeric - privileges that takes as an input number of something,</li> - * <li>boolean - only logic value is acceptable.</li> - * </ul> - */ - private Boolean numeric; - - /** - * Default constructor. Creates view representation from existing privilege. - * - * @param privilege - * original privilege - */ - protected PrivilegeView(BasicPrivilege privilege) { - super(privilege); - } - - /** - * Default constructor. Should be used only for deserialization. - */ - protected PrivilegeView() { - } - - /** - * Constructor that creates empty privilege representation for the type given - * in the parameter. - * - * @param type2 - * type of the privilege - */ - protected PrivilegeView(PrivilegeType type2) { - super(null); - this.commonName = type2.getCommonName(); - this.selected = false; - this.type = type2; - this.objectId = null; - this.numeric = type2.isNumeric(); - this.level = 0; - } - - @Override - public int compareTo(PrivilegeView o) { - if (commonName == null) { - return -1; - } - if (o == null) { - return -1; - } - return this.commonName.compareTo(o.getCommonName()); - } - - /** - * @return the commonName - * @see #commonName - */ - public String getCommonName() { - return commonName; - } - - /** - * @param commonName - * the commonName to set - * @see #commonName - */ - public void setCommonName(String commonName) { - this.commonName = commonName; - } - - /** - * @return the selected - * @see #selected - */ - public Boolean getSelected() { - return selected; - } - - /** - * @param selected - * the selected to set - * @see #selected - */ - public void setSelected(Boolean selected) { - this.selected = selected; - } - - /** - * @return the type - * @see #type - */ - public PrivilegeType getType() { - return type; - } - - /** - * @param type - * the type to set - * @see #type - */ - public void setType(PrivilegeType type) { - this.type = type; - } - - /** - * @return the objectId - * @see #objectId - */ - public Integer getObjectId() { - return objectId; - } - - /** - * @param objectId - * the objectId to set - * @see #objectId - */ - public void setObjectId(Integer objectId) { - this.objectId = objectId; - } - - /** - * @return the level - * @see #level - */ - public Integer getLevel() { - return level; - } - - /** - * @param level - * the level to set - * @see #level - */ - public void setLevel(Integer level) { - this.level = level; - } - - /** - * @return the numeric - * @see #numeric - */ - public Boolean getNumeric() { - return numeric; - } - - /** - * @param numeric - * the numeric to set - * @see #numeric - */ - public void setNumeric(Boolean numeric) { - this.numeric = numeric; - } - -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/PrivilegeViewFactory.java b/service/src/main/java/lcsb/mapviewer/services/view/PrivilegeViewFactory.java deleted file mode 100644 index 2d7cdae3a46c2c2f83345174a88c70e208143af1..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/PrivilegeViewFactory.java +++ /dev/null @@ -1,69 +0,0 @@ -package lcsb.mapviewer.services.view; - -import lcsb.mapviewer.model.user.BasicPrivilege; -import lcsb.mapviewer.model.user.ObjectPrivilege; -import lcsb.mapviewer.model.user.PrivilegeType; - -import org.apache.log4j.Logger; - -import lcsb.mapviewer.common.exception.NotImplementedException; - -import com.google.gson.Gson; - -/** - * Factory class for {@link PrivilegeView} class. - * - * @author Piotr Gawron - * - */ -public class PrivilegeViewFactory extends AbstractViewFactory<BasicPrivilege, PrivilegeView> { - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(PrivilegeViewFactory.class); - - @Override - public PrivilegeView create(BasicPrivilege privilege) { - PrivilegeView result = new PrivilegeView(privilege); - if (privilege == null) { - return result; - } - result.setSelected(privilege.getLevel() > 0); - result.setType(privilege.getType()); - if (privilege.getType() != null) { - result.setCommonName(privilege.getType().getCommonName()); - result.setNumeric(privilege.getType().isNumeric()); - } else { - logger.warn("Privilege without type..."); - } - if (privilege.getClass().equals(ObjectPrivilege.class)) { - result.setObjectId(((ObjectPrivilege) privilege).getId()); - } - result.setLevel(privilege.getLevel()); - return result; - } - - /** - * Creates empty {@link PrivilegeView} element for given {@link PrivilegeType} - * . - * - * - * @param type - * type of empty privilege to create - * @return empty {@link PrivilegeView} element for given {@link PrivilegeType} - * - */ - public PrivilegeView create(PrivilegeType type) { - return new PrivilegeView(type); - } - - @Override - public String createGson(PrivilegeView object) { - return new Gson().toJson(object); - } - - @Override - public BasicPrivilege viewToObject(PrivilegeView view) { - throw new NotImplementedException(); - } -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/ProjectView.java b/service/src/main/java/lcsb/mapviewer/services/view/ProjectView.java deleted file mode 100644 index 6e1ed975ea37398c6e56a39020d759674f3932f2..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/ProjectView.java +++ /dev/null @@ -1,527 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.model.Project; - -/** - * This class is a client view that represents {@link Project} class. Right now - * this class highly entangles {@link Project} and - * {@link lcsb.mapviewer.model.map.model.db.model.map.Model Model}. In the - * future it should separate it. - * - * @author Piotr Gawron - * - */ -public class ProjectView extends AbstractView<Project> implements Comparable<ProjectView>, Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Identifier of the model that is represented in this project view (this must - * be refactorized in the future). - */ - private Integer modelId; - - /** - * List of layouts in the model (identified by {@link #modelId}). - */ - private List<LayoutView> layouts = new ArrayList<LayoutView>(); - - /** - * {@link Project#projectId Identifier} of the project. - */ - private String projectId; - - /** - * {@link Project#name Name} of the project. - */ - private String projectName; - - /** - * {@link Project#name newDiseaseName} of the project. - */ - private String newDiseaseName; - - /** - * {@link Project#organism newOrganismName} of the project. - */ - private String newOrganismName; - - /** - * {@link Project#disease Disease} of the project. - */ - private AnnotationView projectDiseaseLink; - - /** - * {@link Project#disease Disease name} of the project. - */ - private String diseaseName = "N/A"; - - /** - * {@link Project#organism Organism} of the project. - */ - private AnnotationView organismLink; - - /** - * Email used for notification obut the events connected to this project. - */ - private String notifyEmail; - - /** - * Status of the project processing. - */ - private String status; - - /** - * Errors that appeard in the project. - */ - private String errors; - - /** - * Progress of the project processng (value between 0..100). - */ - private Integer progress; - - /** - * Short list of warnings that appeard during model creation. - */ - private String warningsPreview; - - /** - * List of warnings that appeard during model creation. - */ - private List<String> warnings; - - /** - * Description of the model. - */ - private String description; - /** - * Version of the model. - */ - private String version; - - /** - * "true" if input file from which project was created is available, "false" - * otherwise. - */ - private String inputDataAvailable; - - /** - * List of data mining sets used to gernerate suggested connections. - */ - private List<DataMiningSetView> dataMiningSets = new ArrayList<DataMiningSetView>(); - - /** - * Default constructor. - * - * @param project - * {@link Project} for which this view is created - */ - protected ProjectView(Project project) { - super(project); - } - - /** - * Default constructor. Should be used only for deserialization. - */ - protected ProjectView() { - } - - /** - * Constructor that creates copy of the {@link ProjectView}. - * - * @param row - * original object - */ - public ProjectView(ProjectView row) { - super(null); - setIdObject(row.getIdObject()); - modelId = row.getModelId(); - layouts.addAll(row.getLayouts()); - projectId = row.getProjectId(); - projectName = row.getProjectName(); - newDiseaseName = row.getNewDiseaseName(); - newOrganismName = row.getNewOrganismName(); - projectDiseaseLink = row.getProjectDiseaseLink(); - organismLink = row.getOrganismLink(); - notifyEmail = row.getNotifyEmail(); - status = row.getStatus(); - progress = row.getProgress(); - description = row.getDescription(); - version = row.getVersion(); - errors = row.getErrors(); - warningsPreview = row.getWarningsPreview(); - warnings = row.getWarnings(); - for (DataMiningSetView view : row.getDataMiningSets()) { - dataMiningSets.add(new DataMiningSetView(view)); - } - inputDataAvailable = row.getInputDataAvailable(); - } - - @Override - public int compareTo(ProjectView o) { - if (o == null) { - new IntegerComparator().compare(getIdObject(), null); - } - return new IntegerComparator().compare(getIdObject(), o.getIdObject()); - } - - /** - * @return the modelId - * @see #modelId - */ - public Integer getModelId() { - return modelId; - } - - /** - * @param modelId - * the modelId to set - * @see #modelId - */ - public void setModelId(Integer modelId) { - this.modelId = modelId; - } - - /** - * @return the layouts - * @see #layouts - */ - public List<LayoutView> getLayouts() { - return layouts; - } - - /** - * @param layouts - * the layouts to set - * @see #layouts - */ - public void setLayouts(List<LayoutView> layouts) { - this.layouts = layouts; - } - - /** - * @return the name - * @see #projectId - */ - public String getProjectId() { - return projectId; - } - - /** - * @param projectId - * project identifier - * @see #projectId - */ - public void setProjectId(String projectId) { - this.projectId = projectId; - } - - /** - * @return the notifyEmail - * @see #notifyEmail - */ - public String getNotifyEmail() { - return notifyEmail; - } - - /** - * @param notifyEmail - * the notifyEmail to set - * @see #notifyEmail - */ - public void setNotifyEmail(String notifyEmail) { - this.notifyEmail = notifyEmail; - } - - /** - * @return the status - * @see #status - */ - public String getStatus() { - return status; - } - - /** - * @param status - * the status to set - * @see #status - */ - public void setStatus(String status) { - this.status = status; - } - - /** - * @return the progress - * @see #progress - */ - public Integer getProgress() { - return progress; - } - - /** - * @param progress - * the progress to set - * @see #progress - */ - public void setProgress(Integer progress) { - this.progress = progress; - } - - /** - * @return the description - * @see #description - */ - public String getDescription() { - return description; - } - - /** - * @param description - * the description to set - * @see #description - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the version - * @see #version - */ - public String getVersion() { - return version; - } - - /** - * @param version - * the version to set - * @see #version - */ - public void setVersion(String version) { - this.version = version; - } - - /** - * Adds layout to the view. - * - * @param row - * layout to add - */ - public void addLayout(LayoutView row) { - layouts.add(row); - } - - /** - * @return the warnings - * @see #warnings - */ - public List<String> getWarnings() { - return warnings; - } - - /** - * @param warnings - * the warnings to set - * @see #warnings - */ - public void setWarnings(List<String> warnings) { - this.warnings = warnings; - } - - /** - * @return the errors - * @see #errors - */ - public String getErrors() { - return errors; - } - - /** - * @param errors - * the errors to set - * @see #errors - */ - public void setErrors(String errors) { - this.errors = errors; - } - - /** - * @return the dataMiningSets - * @see #dataMiningSets - */ - public List<DataMiningSetView> getDataMiningSets() { - return dataMiningSets; - } - - /** - * @param dataMiningSets - * the dataMiningSets to set - * @see #dataMiningSets - */ - public void setDataMiningSets(List<DataMiningSetView> dataMiningSets) { - this.dataMiningSets = dataMiningSets; - } - - /** - * Adds {@link DataMiningSetView} to {@link #dataMiningSets}. - * - * @param dataMiningSetView - * object to add - */ - public void addDataMiningSet(DataMiningSetView dataMiningSetView) { - dataMiningSets.add(dataMiningSetView); - } - - /** - * @return the projectName - * @see #projectName - */ - public String getProjectName() { - return projectName; - } - - /** - * @param projectName - * the projectName to set - * @see #projectName - */ - public void setProjectName(String projectName) { - this.projectName = projectName; - } - - /** - * @return project disease link - */ - public AnnotationView getProjectDiseaseLink() { - return projectDiseaseLink; - } - - /** - * @param projectDiseaseLink - * the link for the disease. - */ - public void setProjectDiseaseLink(AnnotationView projectDiseaseLink) { - this.projectDiseaseLink = projectDiseaseLink; - } - - /** - * @return this is used to update or add different disease association. - */ - public String getNewDiseaseName() { - return newDiseaseName; - } - - /** - * @param newDiseaseName - * this is used to update or add different disease association. - */ - public void setNewDiseaseName(String newDiseaseName) { - this.newDiseaseName = newDiseaseName; - } - - /** - * @return the diseaseName - * @see #diseaseName - */ - public String getDiseaseName() { - return diseaseName; - } - - /** - * @param diseaseName - * the diseaseName to set - * @see #diseaseName - */ - public void setDiseaseName(String diseaseName) { - this.diseaseName = diseaseName; - } - - /** - * @return the inputDataAvailable - * @see #inputDataAvailable - */ - public String getInputDataAvailable() { - return inputDataAvailable; - } - - /** - * @param inputDataAvailable - * the inputDataAvailable to set - * @see #inputDataAvailable - */ - public void setInputDataAvailable(String inputDataAvailable) { - this.inputDataAvailable = inputDataAvailable; - } - - /** - * @param value - * the inputDataAvailable to set - * @see #inputDataAvailable - */ - public void setInputDataAvailable(boolean value) { - if (value) { - this.inputDataAvailable = "true"; - } else { - this.inputDataAvailable = "false"; - } - - } - - /** - * @return the organismLink - * @see #organismLink - */ - public AnnotationView getOrganismLink() { - return organismLink; - } - - /** - * @param organismLink the organismLink to set - * @see #organismLink - */ - public void setOrganismLink(AnnotationView organismLink) { - this.organismLink = organismLink; - } - - /** - * @return the newOrganismName - * @see #newOrganismName - */ - public String getNewOrganismName() { - return newOrganismName; - } - - /** - * @param newOrganismName the newOrganismName to set - * @see #newOrganismName - */ - public void setNewOrganismName(String newOrganismName) { - this.newOrganismName = newOrganismName; - } - - /** - * @return the warningsPreview - * @see #warningsPreview - */ - public String getWarningsPreview() { - return warningsPreview; - } - - /** - * @param warningsPreview the warningsPreview to set - * @see #warningsPreview - */ - public void setWarningsPreview(String warningsPreview) { - this.warningsPreview = warningsPreview; - } - -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/ProjectViewFactory.java b/service/src/main/java/lcsb/mapviewer/services/view/ProjectViewFactory.java deleted file mode 100644 index 45af2c1ff6ed3987c486ab653b79e11a410c7ce6..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/ProjectViewFactory.java +++ /dev/null @@ -1,119 +0,0 @@ -package lcsb.mapviewer.services.view; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.gson.Gson; - -import lcsb.mapviewer.annotation.data.MeSH; -import lcsb.mapviewer.annotation.services.MeSHParser; -import lcsb.mapviewer.annotation.services.annotators.AnnotatorException; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.graph.DataMiningSet; -import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.model.ModelData; - -/** - * Factory class for {@link ProjectView} class. - * - * @author Piotr Gawron - * - */ -public class ProjectViewFactory extends AbstractViewFactory<Project, ProjectView> { - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(ProjectViewFactory.class); - - /** - * Factory object for {@link LayoutView} elements. - */ - @Autowired - private LayoutViewFactory layoutViewFactory; - - /** - * Factory object used for creation of {@link AnnotationView} elements. - */ - @Autowired - private AnnotationViewFactory annotationViewFactory; - - /** - * Access object for information about mesh terms. - */ - @Autowired - private MeSHParser meSHParser; - - @Override - public ProjectView create(Project project) { - ProjectView result = new ProjectView(project); - if (project == null) { - return result; - } - result.setIdObject(project.getId()); - result.setErrors(project.getErrors()); - result.setProjectId(project.getProjectId()); - result.setProjectName(project.getName()); - result.setNotifyEmail(project.getNotifyEmail()); - if (project.getDisease() != null) { - result.setProjectDiseaseLink(annotationViewFactory.create(project.getDisease())); - result.setNewDiseaseName(project.getDisease().getResource()); - MeSH mesh; - try { - mesh = meSHParser.getMeSH(project.getDisease()); - if (mesh != null) { - result.setDiseaseName(mesh.getName()); - } - } catch (AnnotatorException e) { - logger.error("Problem with getting info about mesh entry: ", e); - } - } - - if (project.getOrganism() != null) { - result.setOrganismLink(annotationViewFactory.create(project.getOrganism())); - result.setNewOrganismName(project.getOrganism().getResource()); - } - result.setStatus(project.getStatus().toString()); - result.setProgress(Integer.valueOf((int) project.getProgress())); - result.setInputDataAvailable(project.getInputData() != null); - - int warnCount = 0; - String warnPreview = ""; - for (String w : project.getWarnings()) { - if (!"".equals(w)) { - if (warnCount <= 2) { - warnPreview += w + "\n"; - } - warnCount++; - } - } - result.setWarningsPreview(warnPreview); - result.setWarnings(project.getWarnings()); - result.setVersion(project.getVersion()); - - for (ModelData model : project.getModels()) { - result.setModelId(model.getId()); - result.setDescription(model.getNotes()); - result.getLayouts().clear(); - for (Layout layout : model.getLayouts()) { - LayoutView layoutRow = layoutViewFactory.create(layout); - result.addLayout(layoutRow); - } - for (DataMiningSet dms : model.getDataMiningSets()) { - result.addDataMiningSet(new DataMiningSetView(dms)); - } - } - return result; - } - - @Override - public String createGson(ProjectView object) { - return new Gson().toJson(object); - } - - @Override - public Project viewToObject(ProjectView view) { - throw new NotImplementedException(); - } -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsView.java b/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsView.java deleted file mode 100644 index fa8eb02646c17c36ee7132dbf92ee9940d0ce041..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsView.java +++ /dev/null @@ -1,108 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.util.ArrayList; -import java.util.List; - -import lcsb.mapviewer.annotation.data.Article; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.InvalidStateException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.services.impl.SearchService; - -/** - * View object for pubmed article for a given model. It contains information - * about article and list of elements annotated by this - * {@link lcsb.mapviewer.model.map.MiriamType#PUBMED article}. - * - * @author Piotr Gawron - * - */ -public class PubmedAnnotatedElementsView extends AbstractView<MiriamData> { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Article for which this pubmed summary is created. - */ - private Article article; - - /** - * List of elements that are annotated the publication. {@link Pair#left} - * refers to human readable name and {@link Pair#right} is search string that - * can be used to access element on the model. - */ - private List<Pair<String, String>> elements = new ArrayList<>(); - - /** - * Default constructor. - * - * @param element - * {@link MiriamData} that represents publication for this object. - * - * @see #article - */ - public PubmedAnnotatedElementsView(MiriamData element) { - super(element); - } - - /** - * @return the article - * @see #article - */ - public Article getArticle() { - return article; - } - - /** - * @param article - * the article to set - * @see #article - */ - public void setArticle(Article article) { - this.article = article; - } - - /** - * @return the elements - * @see #elements - */ - public List<Pair<String, String>> getElements() { - return elements; - } - - /** - * @param elements - * the elements to set - * @see #elements - */ - public void setElements(List<Pair<String, String>> elements) { - this.elements = elements; - } - - /** - * Adds element annotratd by {@link #article}. - * - * @param annotatedObject - * object to add - */ - public void addElement(BioEntity annotatedObject) { - if (annotatedObject instanceof Element) { - Element alias = (Element) annotatedObject; - elements.add(new Pair<String, String>(alias.getName(), SearchService.SPECIES_SEARCH_PREFIX + ":" + alias.getElementId())); - } else if (annotatedObject instanceof Reaction) { - Reaction reaction = (Reaction) annotatedObject; - elements.add( - new Pair<>( - SearchService.REACTION_SEARCH_PREFIX + ":" + reaction.getIdReaction(), SearchService.REACTION_SEARCH_PREFIX + ":" + reaction.getIdReaction())); - } else { - throw new InvalidStateException("Unknown subtype of " + BioEntity.class.getName() + ": " + annotatedObject.getClass().getName()); - } - - } -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsViewFactory.java b/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsViewFactory.java deleted file mode 100644 index f743b95b3ac9b74d1284b818d9985452187c9da7..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/PubmedAnnotatedElementsViewFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.util.Set; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; - -import com.google.gson.Gson; - -import lcsb.mapviewer.annotation.data.Article; -import lcsb.mapviewer.annotation.services.PubmedParser; -import lcsb.mapviewer.annotation.services.PubmedSearchException; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.BioEntity; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.model.Model; - -/** - * Factory class for {@link LayoutView} class. - * - * @author Piotr Gawron - * - */ -public class PubmedAnnotatedElementsViewFactory extends AbstractViewFactory<MiriamData, PubmedAnnotatedElementsView> { - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(PubmedAnnotatedElementsViewFactory.class); - - /** - * Local backend to the pubmed data. - */ - @Autowired - private PubmedParser pubmedParser; - - @Override - public PubmedAnnotatedElementsView create(MiriamData element) { - PubmedAnnotatedElementsView result = new PubmedAnnotatedElementsView(element); - if (element == null) { - return result; - } else if (!MiriamType.PUBMED.equals(element.getDataType())) { - throw new InvalidArgumentException("Only " + MiriamType.PUBMED + " types are valid"); - } - try { - result.setArticle(pubmedParser.getPubmedArticleById(Integer.valueOf(element.getResource()))); - } catch (PubmedSearchException e) { - Article article = new Article(); - article.setTitle("N/A"); - result.setArticle(article); - logger.error(e, e); - } - return result; - } - - /** - * Creates publication summary for a given model. - * - * @param miriamData - * {@link MiriamData} representing article - * @param model - * model for which summary will be prepared - * @return publication summary for a given model and publication - */ - public PubmedAnnotatedElementsView create(MiriamData miriamData, Model model) { - PubmedAnnotatedElementsView result = create(miriamData); - Set<BioEntity> elements = model.getElementsByAnnotation(miriamData); - for (Model submodel : model.getSubmodels()) { - elements.addAll(submodel.getElementsByAnnotation(miriamData)); - } - for (BioEntity annotatedObject : elements) { - result.addElement(annotatedObject); - } - return result; - } - - @Override - public String createGson(PubmedAnnotatedElementsView object) { - return new Gson().toJson(object); - } - - @Override - public MiriamData viewToObject(PubmedAnnotatedElementsView view) { - throw new NotImplementedException(); - } -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/UserView.java b/service/src/main/java/lcsb/mapviewer/services/view/UserView.java deleted file mode 100644 index 7569de2fc50c3e4538f5e60c828862ddf378e6d2..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/UserView.java +++ /dev/null @@ -1,599 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.model.ListDataModel; - -import lcsb.mapviewer.common.comparator.IntegerComparator; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; - -import org.apache.log4j.Logger; -import org.primefaces.model.SelectableDataModel; - -/** - * This class represents view of the {@link User} that is available on the - * client side. - * - * @author Piotr Gawron - * - */ -public class UserView extends AbstractView<User> implements Comparable<UserView>, Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(UserView.class); - - /** - * This data model is extension of faces {@link ListDataModel} and implements - * {@link SelectableDataModel} from primefaces library. It allows client to - * create a table (in xhtml) that allows to select element on it and call select - * event associated with the row. The model operates on - * {@link UserProjectPrivilegeView} that describe set of privileges to single - * project. - * - * @author Piotr Gawron - * - */ - public class ProjectDataModel extends ListDataModel<UserProjectPrivilegeView> - implements SelectableDataModel<UserProjectPrivilegeView>, Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public ProjectDataModel() { - } - - /** - * Constructor that initialize the data. - * - * @param data - * data used in the model - */ - public ProjectDataModel(List<UserProjectPrivilegeView> data) { - super(data); - } - - @Override - public Object getRowKey(UserProjectPrivilegeView object) { - return object.toString(); - } - - @SuppressWarnings("unchecked") - @Override - public UserProjectPrivilegeView getRowData(String rowKey) { - List<UserProjectPrivilegeView> privileges = (List<UserProjectPrivilegeView>) getWrappedData(); - - for (UserProjectPrivilegeView privilege : privileges) { - if ((privilege.toString()).equals(rowKey)) { - return privilege; - } - } - return null; - } - - } - - /** - * Class representing prvileges to the specific project. - * - * @author Piotr Gawron - * - */ - public class UserProjectPrivilegeView extends AbstractView<Project> implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * {@link Project#projectId Project identifier}. - */ - private String projectId; - - /** - * List of privileges to the project. - */ - private List<PrivilegeView> projectPrivileges = new ArrayList<PrivilegeView>(); - - /** - * List of layouts with privileges. - */ - private List<UserLayoutPrivilege> layoutPrivileges = new ArrayList<UserLayoutPrivilege>(); - - /** - * Constructor that creates view for the project. - * - * @param project - * originasl project - */ - public UserProjectPrivilegeView(Project project) { - super(project); - this.projectId = project.getProjectId(); - } - - /** - * Default constructor. - */ - public UserProjectPrivilegeView() { - super(null); - } - - /** - * @return the projectId - * @see #projectId - */ - public String getProjectId() { - return projectId; - } - - /** - * @param projectId - * the projectId to set - * @see #projectId - */ - public void setProjectId(String projectId) { - this.projectId = projectId; - } - - /** - * @return the projectPrivileges - * @see #projectPrivileges - */ - public List<PrivilegeView> getProjectPrivileges() { - return projectPrivileges; - } - - /** - * @param projectPrivileges - * the projectPrivileges to set - * @see #projectPrivileges - */ - public void setProjectPrivileges(List<PrivilegeView> projectPrivileges) { - this.projectPrivileges = projectPrivileges; - } - - /** - * @return the layoutPrivileges - * @see #layoutPrivileges - */ - public List<UserLayoutPrivilege> getLayoutPrivileges() { - return layoutPrivileges; - } - - /** - * @param layoutPrivileges - * the layoutPrivileges to set - * @see #layoutPrivileges - */ - public void setLayoutPrivileges(List<UserLayoutPrivilege> layoutPrivileges) { - this.layoutPrivileges = layoutPrivileges; - } - - /** - * Returns view of the {@link Privilege} for a given {@link PrivilegeType}. - * - * @param pt - * ttype of privilege - * @return view of the {@link Privilege} for a given {@link PrivilegeType} - */ - public PrivilegeView getProjectPrivilegeByPrivilegeType(PrivilegeType pt) { - for (PrivilegeView pv : projectPrivileges) { - if (pv.getType() == pt) { - return pv; - } - } - logger.warn("Cannot find " + pt + " for projectID: " + this.getIdObject() + " (" + this.getProjectId() - + "). UserId: " + UserView.this.getIdObject() + " (" + UserView.this.getLogin() + ")"); - return null; - } - - } - - /** - * Class representing prvileges to the specific - * {@link lcsb.mapviewer.db.model.map.layout.Layout Layout}. - * - * @author Piotr Gawron - * - */ - public class UserLayoutPrivilege extends AbstractView<Layout> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Name of the layout. - */ - private String layoutName; - - /** - * List of privileges for the layout. - */ - private List<PrivilegeView> layoutPrivileges = new ArrayList<PrivilegeView>(); - - /** - * Default constructor. - * - * @param layout - * object for which the privilege set is created - */ - protected UserLayoutPrivilege(Layout layout) { - super(layout); - } - - /** - * Default constructor. Should be used only for deserialization. - */ - protected UserLayoutPrivilege() { - } - - /** - * @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 layoutPrivileges - * @see #layoutPrivileges - */ - public List<PrivilegeView> getLayoutPrivileges() { - return layoutPrivileges; - } - - /** - * @param layoutPrivileges - * the layoutPrivileges to set - * @see #layoutPrivileges - */ - public void setLayoutPrivileges(List<PrivilegeView> layoutPrivileges) { - this.layoutPrivileges = layoutPrivileges; - } - - } - - /** - * Use login. - */ - private String login; - - /** - * User password (can be set only by the client side, when view is created - * password should be set to empty, simple precaution not to reveal passwords). - */ - private String password; - - /** - * User password 2. - */ - private String password2; - - /** - * Old password. - */ - private String oldPassword; - - /** - * Old Encrypted password. - */ - private String cryptedPassword; - - /** - * Name of the user. - */ - private String name; - - /** - * Family name of the user. - */ - private String surname; - - /** - * User email address. - */ - private String email; - - /** - * List of general privielges. - */ - private List<PrivilegeView> basicPrivileges = new ArrayList<PrivilegeView>(); - /** - * List of privileges divided by the projects. - */ - - private List<UserProjectPrivilegeView> projectPrivileges = new ArrayList<UserProjectPrivilegeView>(); - /** - * Data model used for managing project privileges. - */ - private ProjectDataModel pdm = null; - - /** - * Constructor that create user view from the user data. - * - * @param user - * orignal user - */ - protected UserView(User user) { - super(user); - this.login = user.getLogin(); - this.password = ""; - this.password2 = ""; - this.oldPassword = ""; - this.cryptedPassword = user.getCryptedPassword(); - this.name = user.getName(); - this.surname = user.getSurname(); - this.email = user.getEmail(); - } - - /** - * Default constructor. - */ - protected UserView() { - super(null); - } - - /** - * Returns object with privileges for the given project. - * - * @param projectId - * identifier of the project - * @return object with privileges for the given project - */ - public UserProjectPrivilegeView getProjectPrivilegeByProjectId(Integer projectId) { - IntegerComparator comparator = new IntegerComparator(); - for (UserProjectPrivilegeView projectPrivilege : getProjectPrivileges()) { - if (comparator.compare(projectPrivilege.getIdObject(), projectId) == 0) { - return projectPrivilege; - } - } - if (projectId == null) { - logger.warn("Cannot find default project privileges. User: " + getIdObject() + " (" + getLogin() + ")."); - - } else if (projectId != 0) { - logger.warn("Cannot find project privileges for projectID: " + projectId + ". User: " + getIdObject() + " (" - + getLogin() + ")."); - } - return null; - } - - /** - * - * @return {@link #pdm} - */ - public ProjectDataModel getPdm() { - if (pdm == null) { - pdm = new ProjectDataModel(projectPrivileges); - } - return pdm; - } - - /** - * - * @param pdm - * new {@link #pdm} object - */ - public void setPdm(ProjectDataModel pdm) { - this.pdm = pdm; - } - - /** - * Return object with privileges for layout given in the parameter. - * - * @param layoutId - * identifier of the layout - * @return object with privileges for layout - */ - public UserLayoutPrivilege getLayoutPrivilegeByLayoutId(int layoutId) { - for (UserProjectPrivilegeView projectPrivilege : getProjectPrivileges()) { - for (UserLayoutPrivilege layoutPrivilege : projectPrivilege.getLayoutPrivileges()) { - if (layoutPrivilege.getIdObject() == layoutId) { - return layoutPrivilege; - } - } - } - logger.warn("Cannot find project privileges for layoutID: " + layoutId); - return null; - } - - @Override - public int compareTo(UserView o) { - IntegerComparator comparator = new IntegerComparator(); - if (o == null) { - comparator.compare(getIdObject(), null); - } - return comparator.compare(getIdObject(), o.getIdObject()); - - } - - /** - * @return the login - * @see #login - */ - public String getLogin() { - return login; - } - - /** - * @param login - * the login to set - * @see #login - */ - public void setLogin(String login) { - this.login = login; - } - - /** - * @return the password - * @see #password - */ - public String getPassword() { - return password; - } - - /** - * @param password - * the password to set - * @see #password - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the surname - * @see #surname - */ - public String getSurname() { - return surname; - } - - /** - * @param surname - * the surname to set - * @see #surname - */ - public void setSurname(String surname) { - this.surname = surname; - } - - /** - * @return the email - * @see #email - */ - public String getEmail() { - return email; - } - - /** - * @param email - * the email to set - * @see #email - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return the basicPrivileges - * @see #basicPrivileges - */ - public List<PrivilegeView> getBasicPrivileges() { - return basicPrivileges; - } - - /** - * @param basicPrivileges - * the basicPrivileges to set - * @see #basicPrivileges - */ - public void setBasicPrivileges(List<PrivilegeView> basicPrivileges) { - this.basicPrivileges = basicPrivileges; - } - - /** - * @return the projectPrivileges - * @see #projectPrivileges - */ - public List<UserProjectPrivilegeView> getProjectPrivileges() { - return projectPrivileges; - } - - /** - * @param projectPrivileges - * the projectPrivileges to set - * @see #projectPrivileges - */ - public void setProjectPrivileges(List<UserProjectPrivilegeView> projectPrivileges) { - this.projectPrivileges = projectPrivileges; - } - - /** - * @return old password as typed by the user. - */ - public String getOldPassword() { - return oldPassword; - } - - /** - * @param oldPassword - * the field for the user to put in the old password, - */ - public void setOldPassword(String oldPassword) { - this.oldPassword = oldPassword; - } - - /** - * @return password crypted and stored in DB. - */ - public String getCryptedPassword() { - return cryptedPassword; - } - - /** - * @param cryptedPassword - * crypted password stored in DB - */ - public void setCryptedPassword(String cryptedPassword) { - this.cryptedPassword = cryptedPassword; - } - - /** - * @return password2. - */ - public String getPassword2() { - return password2; - } - - /** - * @param password2 - * to verify that the password match. - */ - public void setPassword2(String password2) { - this.password2 = password2; - } -} diff --git a/service/src/main/java/lcsb/mapviewer/services/view/UserViewFactory.java b/service/src/main/java/lcsb/mapviewer/services/view/UserViewFactory.java deleted file mode 100644 index c5c9561a93d986f28dc5dd167b01df6f9c67b18a..0000000000000000000000000000000000000000 --- a/service/src/main/java/lcsb/mapviewer/services/view/UserViewFactory.java +++ /dev/null @@ -1,239 +0,0 @@ -package lcsb.mapviewer.services.view; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.user.BasicPrivilege; -import lcsb.mapviewer.model.user.ObjectPrivilege; -import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.persist.dao.ProjectDao; -import lcsb.mapviewer.services.utils.InvalidPrivilegeException; -import lcsb.mapviewer.services.view.UserView.UserLayoutPrivilege; -import lcsb.mapviewer.services.view.UserView.UserProjectPrivilegeView; - -import org.apache.log4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.common.exception.NotImplementedException; - -import com.google.gson.Gson; - -/** - * Factory class for {@link UserView} class. - * - * @author Piotr Gawron - * - */ -public class UserViewFactory extends AbstractViewFactory<User, UserView> { - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = Logger.getLogger(UserViewFactory.class); - - /** - * Data access object for projects. - */ - @Autowired - private ProjectDao projectDao; - - /** - * Factory object for {@link PrivilegeView} elements. - */ - @Autowired - private PrivilegeViewFactory privilegeViewFactory; - - @Override - public UserView create(User user) { - return create(user, projectDao.getAll()); - } - - /** - * Creates {@link UserView} obejct for given user and given list of projects. - * - * @param user - * object for which {@link UserView} element will be created - * @param projects - * list of project for which privileges will be created as - * {@link PrivilegeView} elements in the result - * @return {@link UserView} obejct for given user - */ - public UserView create(User user, List<Project> projects) { - UserView result = null; - if (user == null) { - result = new UserView(); - for (Project project : projects) { - result.getProjectPrivileges().add(result.new UserProjectPrivilegeView(project)); - } - for (PrivilegeType type : getBasicTypes()) { - result.getBasicPrivileges().add(privilegeViewFactory.create(type)); - } - for (UserProjectPrivilegeView projectPrivilege : result.getProjectPrivileges()) { - for (PrivilegeType type : getObjectTypes()) { - if (type.getPrivilegeObjectType().equals(Project.class)) { - projectPrivilege.getProjectPrivileges().add(privilegeViewFactory.create(type)); - } - } - } - } else { - result = new UserView(user); - - for (Project project : projects) { - result.getProjectPrivileges().add(result.new UserProjectPrivilegeView(project)); - } - - setPrivilegeStatusFromDb(user, result); - - createUnknownPrivileges(result); - } - - Collections.sort(result.getBasicPrivileges()); - for (UserProjectPrivilegeView row1 : result.getProjectPrivileges()) { - Collections.sort(row1.getProjectPrivileges()); - } - - return result; - } - - /** - * Creates privileges for user that doesn't exists in database. - * - * @param row - * user for which we want to add missing privileges - */ - private void createUnknownPrivileges(UserView row) { - Set<PrivilegeType> knownPrivileges = new HashSet<PrivilegeType>(); - for (PrivilegeView privilege : row.getBasicPrivileges()) { - knownPrivileges.add(privilege.getType()); - } - - for (PrivilegeType type : getBasicTypes()) { - if (!knownPrivileges.contains(type)) { - row.getBasicPrivileges().add(privilegeViewFactory.create(type)); - } - } - for (UserProjectPrivilegeView projectPrivilege : row.getProjectPrivileges()) { - knownPrivileges.clear(); - for (PrivilegeView privilege : projectPrivilege.getProjectPrivileges()) { - knownPrivileges.add(privilege.getType()); - } - for (PrivilegeType type : getObjectTypes()) { - if (type.getPrivilegeObjectType().equals(Project.class)) { - if (!knownPrivileges.contains(type)) { - projectPrivilege.getProjectPrivileges().add(privilegeViewFactory.create(type)); - } - } - } - } - } - - /** - * Method that assigns privileges from original user object into view - * representation userView. - * - * @param user - * original object retrieved from database - * @param userView - * representation of the user passed later on to higher layer - */ - private void setPrivilegeStatusFromDb(User user, UserView userView) { - for (BasicPrivilege privilege : user.getPrivileges()) { - if (privilege.getClass().equals(BasicPrivilege.class)) { - userView.getBasicPrivileges().add(privilegeViewFactory.create(privilege)); - } else if (privilege.getClass().equals(ObjectPrivilege.class)) { - if (privilege.getType().getPrivilegeObjectType().equals(Project.class)) { - Integer projectId = ((ObjectPrivilege) privilege).getIdObject(); - UserProjectPrivilegeView projectPrivilege = userView.getProjectPrivilegeByProjectId(projectId); - if (projectPrivilege != null) { - projectPrivilege.getProjectPrivileges().add(privilegeViewFactory.create(privilege)); - } - } else if (privilege.getType().getPrivilegeObjectType().equals(Layout.class)) { - int layoutId = ((ObjectPrivilege) privilege).getIdObject(); - UserLayoutPrivilege layoutPrivilege = userView.getLayoutPrivilegeByLayoutId(layoutId); - if (layoutPrivilege != null) { - layoutPrivilege.getLayoutPrivileges().add(privilegeViewFactory.create(privilege)); - } - } else { - throw new InvalidPrivilegeException( - "Unknown class for object privilege: " + privilege.getType().getPrivilegeObjectType()); - } - } else { - throw new InvalidPrivilegeException("Unknown privilege type: " + privilege.getType()); - } - } - } - - /** - * Returns list of basic privilege types (privileges that doesn't refer to - * another object). - * - * @return list of basic privilege types - */ - public List<PrivilegeType> getBasicTypes() { - if (basicTypes == null) { - fillTypeList(); - } - return basicTypes; - } - - /** - * List of type privileges that refers to {@link BasicPrivilege} class. - */ - private List<PrivilegeType> basicTypes = null; - /** - * List of type privileges that refers to {@link ObjectPrivilege} class. - */ - private List<PrivilegeType> objectTypes = null; - - /** - * Returns list of object privilege types (privileges that refer to another - * object). - * - * @return list of object privilege types - */ - public List<PrivilegeType> getObjectTypes() { - if (objectTypes == null) { - fillTypeList(); - } - return objectTypes; - } - - /** - * This method initializes {@link #basicTypes} and {@link #objectTypes} lists. - */ - private void fillTypeList() { - basicTypes = new ArrayList<PrivilegeType>(); - objectTypes = new ArrayList<PrivilegeType>(); - - PrivilegeType[] types = PrivilegeType.values(); - - for (PrivilegeType privilegeType : types) { - if (privilegeType.getPrivilegeClassType().equals(BasicPrivilege.class)) { - basicTypes.add(privilegeType); - } else if (privilegeType.getPrivilegeClassType().equals(ObjectPrivilege.class)) { - objectTypes.add(privilegeType); - } else { - throw new InvalidPrivilegeException("Unknown privilege type: " + privilegeType.getPrivilegeClassType()); - } - } - - } - - @Override - public String createGson(UserView object) { - return new Gson().toJson(object); - } - - @Override - public User viewToObject(UserView view) { - throw new NotImplementedException(); - } - -} diff --git a/service/src/main/resources/applicationContext-service.xml b/service/src/main/resources/applicationContext-service.xml index 7d133276baca0b90b4f182c4120f431a268bb381..8e9ec634b7a398999e09d3744325117e8e930e99 100644 --- a/service/src/main/resources/applicationContext-service.xml +++ b/service/src/main/resources/applicationContext-service.xml @@ -19,8 +19,6 @@ <bean id="DrugService" class="lcsb.mapviewer.services.search.db.drug.DrugService"/> - <bean id="ExporterService" class="lcsb.mapviewer.services.impl.ExporterService"/> - <bean id="ExternalServicesService" class="lcsb.mapviewer.services.impl.ExternalServicesService"/> <bean id="LayoutService" class="lcsb.mapviewer.services.impl.LayoutService"/> @@ -50,19 +48,13 @@ <!-- View factories --> <bean id="AnnotationViewFactory" class="lcsb.mapviewer.services.view.AnnotationViewFactory"/> - <bean id="CommentViewFactory" class="lcsb.mapviewer.services.view.CommentViewFactory"/> <bean id="ConfigurationViewFactory" class="lcsb.mapviewer.services.view.ConfigurationViewFactory"/> <bean id="DataMiningViewFactory" class="lcsb.mapviewer.services.view.DataMiningViewFactory"/> <bean id="LayoutViewFactory" class="lcsb.mapviewer.services.view.LayoutViewFactory"/> - <bean id="ModelViewFactory" class="lcsb.mapviewer.services.view.ModelViewFactory"/> <bean id="OverviewImageViewFactory" class="lcsb.mapviewer.services.view.OverviewImageViewFactory"/> <bean id="OverviewLinkViewFactory" class="lcsb.mapviewer.services.view.OverviewLinkViewFactory"/> - <bean id="PrivilegeViewFactory" class="lcsb.mapviewer.services.view.PrivilegeViewFactory"/> - <bean id="ProjectViewFactory" class="lcsb.mapviewer.services.view.ProjectViewFactory"/> - <bean id="PubmedAnnotatedElementsViewFactory" class="lcsb.mapviewer.services.view.PubmedAnnotatedElementsViewFactory"/> <bean id="ReferenceGenomeViewFactory" class="lcsb.mapviewer.services.view.ReferenceGenomeViewFactory"/> <bean id="ReferenceGenomeGeneMappingViewFactory" class="lcsb.mapviewer.services.view.ReferenceGenomeGeneMappingViewFactory"/> - <bean id="UserViewFactory" class="lcsb.mapviewer.services.view.UserViewFactory"/> <bean id="FullAliasViewFactory" class="lcsb.mapviewer.services.search.data.FullAliasViewFactory"/> <bean id="FullReactionViewFactory" class="lcsb.mapviewer.services.search.data.FullReactionViewFactory"/> 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/AllImplServiceTests.java b/service/src/test/java/lcsb/mapviewer/services/impl/AllImplServiceTests.java index c190d180cf2a44b141055a62e0e74d30f093ea28..a5f016714de7a25ea45263a08df7156d9e3993eb 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/AllImplServiceTests.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/AllImplServiceTests.java @@ -9,7 +9,6 @@ import org.junit.runners.Suite.SuiteClasses; ConfigurationServiceTest.class, // DataMiningServiceTest.class, // DataMiningServiceTest2.class, // - ExporterServiceTest.class, // ExternalServicesServiceTest.class, // LayoutServiceTest.class, // Md5PasswordEncoderTest.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..673ade770fa33642d7af67a9a08c93210593f129 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/CommentServiceTest.java @@ -2,7 +2,6 @@ package lcsb.mapviewer.services.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.awt.geom.Point2D; @@ -19,230 +18,173 @@ import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.map.Comment; import lcsb.mapviewer.model.map.model.Model; import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.reaction.Reaction; import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.user.ObjectPrivilege; -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 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 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/ExporterServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/ExporterServiceTest.java deleted file mode 100644 index e65556f1044b7cf57849214923809461a2670647..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/impl/ExporterServiceTest.java +++ /dev/null @@ -1,540 +0,0 @@ -package lcsb.mapviewer.services.impl; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.commands.CreateHierarchyCommand; -import lcsb.mapviewer.converter.model.celldesigner.reaction.ReactionLineData; -import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.reaction.ReactionNode; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.services.ServiceTestFunctions; -import lcsb.mapviewer.services.interfaces.IExporterService; -import lcsb.mapviewer.services.interfaces.IExporterService.ExporterParameters; -import lcsb.mapviewer.services.utils.data.ExportColumn; -import lcsb.mapviewer.services.utils.data.ExportFileType; -import lcsb.mapviewer.services.view.PubmedAnnotatedElementsView; - -public class ExporterServiceTest extends ServiceTestFunctions { - Logger logger = Logger.getLogger(ExporterServiceTest.class); - @Autowired - IExporterService exporter2; - - ExporterService exporter; - - @Before - public void setUp() throws Exception { - exporter = (ExporterService) exporter2; - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetExportSpeciesStringForTabSeparatedFile() throws Exception { - try { - Model model = getModelForFile("testFiles/export_with_artifitial_comp.xml", false); - ExportColumn columns[] = { ExportColumn.NAME, ExportColumn.ID, ExportColumn.COMPONENT_NAME, - ExportColumn.COMPARTMENT_NAME, ExportColumn.TYPE }; - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).column(columns) - .fileType(ExportFileType.TAB_SEPARATED); - - // full export (all elements) - String string = exporter.getExportSpeciesString(params); - String lines[] = string.split("\n"); - assertTrue("Not enough elements in the result file", lines.length > 1); - - String response = lines[0]; - String textColumns[] = response.split("\t"); - assertEquals(5, textColumns.length); - - // only proteins for self-made modules - new CreateHierarchyCommand(model, 8, 80).execute(); - string = exporter.getExportSpeciesString(params.type(GenericProtein.class)); - lines = string.split("\n"); - assertTrue(lines.length > 1); - - boolean differenceBetweenComponentCompartmnet = false; - int lineCount = 0; - for (String string2 : lines) { - if (lineCount == 0) { - textColumns = string2.split("\t"); - assertEquals(ExportColumn.TYPE.getTitle(), textColumns[4]); - } else { - textColumns = string2.split("\t"); - assertEquals(GenericProtein.class.getSimpleName(), textColumns[4]); - if (!textColumns[2].equalsIgnoreCase(textColumns[3])) { - differenceBetweenComponentCompartmnet = true; - } - } - lineCount++; - } - assertTrue(differenceBetweenComponentCompartmnet); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testDuplicatesInGetExportSpeciesString() throws Exception { - try { - Model model = getModelForFile("testFiles/export_duplicate_elements.xml", false); - ExportColumn columns[] = { ExportColumn.NAME, ExportColumn.COMPONENT_NAME, ExportColumn.TYPE }; - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).column(columns) - .fileType(ExportFileType.TAB_SEPARATED); - - // full export (all elements) - String string = exporter.getExportSpeciesString(params); - - String lines[] = string.split("\n"); - Set<String> uniqueNames = new HashSet<String>(); - for (String string2 : lines) { - uniqueNames.add(string2); - } - assertEquals(uniqueNames.size(), lines.length); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetExportStringForOneSpecies_Complex() { - try { - Model model = getModelForFile("testFiles/export/hsp70.xml", true); - - Species alias = (Species) model.getElementByElementId("csa1"); - ExportColumn columns[] = { ExportColumn.NAME }; - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).// - column(columns).// - complexElementsName(false).// - fileType(ExportFileType.TAB_SEPARATED); - - List<String> elements = exporter.getExportStringForOneSpecies(alias, params); - assertTrue(elements.contains("HSP70:chaperon")); - - // now the results are concatenated children - params.complexElementsName(true); - - elements = exporter.getExportStringForOneSpecies(alias, params); - assertTrue(elements.size() > 0); - String string = elements.get(0); - assertFalse(string.equals("HSP70:chaperon")); - assertTrue(string.contains("HSP70")); - assertTrue(string.contains("STUB1")); - assertTrue(string.contains("DNAJB2")); - assertTrue(string.contains("BAG1")); - - // and now check complexes with mix of proteins and molecules - alias = (Species) model.getElementByElementId("csa3"); - - elements = exporter.getExportStringForOneSpecies(alias, params); - assertTrue(elements.size() > 0); - string = elements.get(0); - assertTrue(string.contains("UBA1")); - assertTrue(string.contains("UBA6")); - assertTrue(string.contains("AMP")); - - elements = exporter.getExportStringForOneSpecies(alias, params.type(Protein.class)); - assertTrue(elements.size() > 0); - string = elements.get(0); - assertTrue(string.contains("UBA1")); - assertTrue(string.contains("UBA6")); - assertFalse(string.contains("AMP")); - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured"); - } - } - - @Test - public void testGetExportStringForOneReaction() throws Exception { - try { - Model model = getModelForFile("testFiles/export/reaction.xml", false); - Set<Compartment> aliases = new HashSet<>(); - for (Compartment alias : model.getCompartments()) { - if (alias.getName().equalsIgnoreCase("Dopamine loaded synaptic vesicle")) - aliases.add(alias); - } - - Reaction reaction = model.getReactionByReactionId("re2"); - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).// - fileType(ExportFileType.SIF).// - type(Protein.class).// - type(Complex.class).// - fileType(ExportFileType.SIF).// - complexElementsName(false).// - excluded(aliases); - - String string = exporter.getExportSingleInteractionString(reaction, params).get(0); - assertNotNull(string); - assertTrue(string.contains("Calcium channel:RIMBP:RIM:MUNC13:RAB")); - assertTrue(string.contains("CSP:Hsc70:SGT")); - assertTrue(string.contains("SNCA")); - assertTrue(string.contains("trans-SNARE complex")); - assertFalse(string.contains("VAMP2")); - - params = new IExporterService.ExporterParameters().model(model).fileType(ExportFileType.SIF).type(Complex.class) - .type(Protein.class); - string = exporter.getExportSingleInteractionString(reaction, params).get(0); - assertTrue(string.contains("VAMP2")); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void testGetExportStringForOneReactionInGeneral() { - try { - Model model = getModelForFile("testFiles/export/reaction.xml", true); - Reaction reaction = model.getReactionByReactionId("re2"); - ExporterParameters params = new IExporterService.ExporterParameters().model(model).// - fileType(ExportFileType.SIF).// - complexElementsName(false).// - type(Complex.class).type(Protein.class); - String string = exporter.getExportSingleInteractionString(reaction, params).get(0); - assertNotNull(string); - assertTrue(string.contains("Calcium channel:RIMBP:RIM:MUNC13:RAB")); - assertTrue(string.contains("CSP:Hsc70:SGT")); - assertTrue(string.contains("SNCA")); - assertTrue(string.contains("trans-SNARE complex")); - assertTrue(string.contains("SNAP25")); - assertFalse(string.contains("RAB3A")); - - params.complexElementsName(true); - string = exporter.getExportSingleInteractionString(reaction, params).get(0); - assertFalse(string.contains("trans-SNARE complex")); - assertTrue(string.contains("RAB3A")); - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured"); - } - - } - - @Test - public void testGetExportStringForOneReactionInGeneralWithOnlyOneElement() throws Exception { - try { - Model model = getModelForFile("testFiles/export/reaction.xml", false); - Reaction reaction = model.getReactionByReactionId("re11"); - model.removeReactions(model.getReactions()); - model.addReaction(reaction); - Set<Compartment> aliases = new HashSet<>(); - aliases.add((Compartment) model.getElementByElementId("ca1")); - ExporterParameters params = new IExporterService.ExporterParameters().model(model).fileType(ExportFileType.SIF) - .included("dopamine loaded synaptic vesicle"); - assertEquals(0, exporter.getExportSingleInteractionString(reaction, params).size()); - - params = new IExporterService.ExporterParameters().model(model).fileType(ExportFileType.SIF); - assertEquals(1, exporter.getExportSingleInteractionString(reaction, params).size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetExportSingleInteractionString_text() { - try { - Model model = getModelForFile("testFiles/export_with_artifitial_comp.xml", false); - for (Reaction reaction : model.getReactions()) { - String str = exporter - .getExportSingleInteractionString(reaction, - new IExporterService.ExporterParameters().fileType(ExportFileType.TAB_SEPARATED).type(Species.class)) - .get(0); - - List<String> strings = new ArrayList<String>(); - strings.add(ReactionLineData.getByReactionType(reaction.getClass()).getCellDesignerString()); - strings.add(reaction.getIdReaction()); - for (ReactionNode node : reaction.getReactionNodes()) { - strings.add(node.getElement().getName()); - - } - for (String string : strings) { - assertTrue( - "Description \"" + str + "\" doesn't contain " + string + ". reactionId=" + reaction.getIdReaction(), - str.contains(string)); - } - } - - } catch (Exception e) { - e.printStackTrace(); - fail("Exception occured"); - } - } - - @Test - public void testGetExportComponentAndCompartments() throws Exception { - try { - Model model = getModelForFile("testFiles/export/export_model.xml", false); - new CreateHierarchyCommand(model, 7, 80).execute(); - ExporterParameters params = new IExporterService.ExporterParameters().model(model) - .fileType(ExportFileType.TAB_SEPARATED).column(ExportColumn.NAME).column(ExportColumn.COMPONENT_NAME) - .column(ExportColumn.COMPARTMENT_NAME); - - List<String> list = exporter.getExportStringForOneSpecies((Species) model.getElementByElementId("sa1"), params); - String desc = list.get(0); - String compartment = desc.split("\t")[2]; - assertEquals("c1", compartment); - String component = desc.split("\t")[1]; - assertEquals("Test3", component); - - list = exporter.getExportStringForOneSpecies((Species) model.getElementByElementId("sa2"), params); - desc = null; - for (String string : list) { - if (string.contains("Test 1")) { - desc = string; - } - } - compartment = desc.split("\t")[2]; - assertEquals("c2", compartment); - component = desc.split("\t")[1]; - assertEquals("Test 1", component); - - for (String string : list) { - if (string.contains("Test2")) { - desc = string; - } - } - compartment = desc.split("\t")[2]; - assertEquals("c2", compartment); - component = desc.split("\t")[1]; - assertEquals("Test2", component); - - for (String string : list) { - if (string.contains("Test3")) { - desc = string; - } - } - compartment = desc.split("\t")[2]; - assertEquals("c2", compartment); - component = desc.split("\t")[1]; - assertEquals("Test3", component); - - list = exporter.getExportStringForOneSpecies((Species) model.getElementByElementId("sa3"), params); - boolean ok = false; - for (String string : list) { - if (string.split("\t")[2].equals("null") && string.split("\t")[1].equals("Test2")) { - ok = true; - } - } - assertTrue(ok); - - list = exporter.getExportStringForOneSpecies((Species) model.getElementByElementId("sa4"), params); - desc = list.get(0); - compartment = desc.split("\t")[2]; - assertEquals("null", compartment); - component = desc.split("\t")[1]; - assertEquals("Test3", component); - - list = exporter.getExportStringForOneSpecies((Species) model.getElementByElementId("sa5"), params); - desc = list.get(0); - compartment = desc.split("\t")[2]; - assertEquals("c3", compartment); - component = desc.split("\t")[1]; - assertEquals("null", component); - - list = exporter.getExportStringForOneSpecies((Species) model.getElementByElementId("sa6"), params); - desc = list.get(0); - compartment = desc.split("\t")[2]; - assertEquals("null", compartment); - component = desc.split("\t")[1]; - assertEquals("null", component); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetExportSpeciesStringForTabSeparatedFile2() throws Exception { - try { - Model model = getModelForFile("testFiles/export_with_artifitial_comp.xml", false); - ExportColumn columns[] = { ExportColumn.NAME, ExportColumn.ID, ExportColumn.COMPONENT_NAME, - ExportColumn.COMPARTMENT_NAME, ExportColumn.TYPE }; - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).column(columns) - .fileType(ExportFileType.TAB_SEPARATED).type(Object.class); - - // full export (all elements) - String string = exporter.getExportSpeciesString(params); - String lines[] = string.split("\n"); - assertTrue("Not enough elements in the result file", lines.length > 1); - - String response = lines[0]; - String textColumns[] = response.split("\t"); - assertEquals(columns.length, textColumns.length); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetExportCompartmentsString() throws Exception { - try { - Model model = getModelForFile("testFiles/export/export_compartments.xml", false); - - ExporterParameters params = new IExporterService.ExporterParameters().model(model) - .fileType(ExportFileType.TAB_SEPARATED).type(Object.class); - - // full export (all compartments) - String string = exporter.getExportCompartmentsString(params); - String lines[] = string.split("\n"); - assertTrue("Not enough elements in the result file", lines.length >= 2); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAllExportColumnsSpecies() throws Exception { - try { - Model model = getModelForFile("testFiles/export_with_artifitial_comp.xml", false); - List<ExportColumn> columns = new ArrayList<ExportColumn>(); - for (ExportColumn column : ExportColumn.values()) { - if (column.getClazz().isAssignableFrom(Species.class)) { - columns.add(column); - } - } - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).column(columns) - .fileType(ExportFileType.TAB_SEPARATED); - - // full export (all elements) - String string = exporter.getExportSpeciesString(params); - assertNotNull(string); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testAllExportColumnsReaction() throws Exception { - try { - Model model = getModelForFile("testFiles/export_with_artifitial_comp.xml", false); - List<ExportColumn> columns = new ArrayList<ExportColumn>(); - for (ExportColumn column : ExportColumn.values()) { - if (column.getClazz().isAssignableFrom(Reaction.class)) { - columns.add(column); - } - } - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).column(columns) - .fileType(ExportFileType.TAB_SEPARATED); - - // full export (all elements) - String string = exporter.getExportInteractionString(params); - assertNotNull(string); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetTabSeparatedReaction() throws Exception { - try { - Model model = getModelForFile("testFiles/export/reaction.xml", false); - Set<Compartment> aliases = new HashSet<>(); - for (Compartment alias : model.getCompartments()) { - if (alias.getName().equalsIgnoreCase("Dopamine loaded synaptic vesicle")) - aliases.add(alias); - } - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).// - fileType(ExportFileType.TAB_SEPARATED).// - column(ExportColumn.REACTION_ID).// - column(ExportColumn.REACTION_TYPE).// - type(Species.class); - - String string = exporter.getExportInteractionString(params); - assertTrue(string.indexOf("STATE_TRANSITION REACTANT") >= 0); - assertTrue(string.indexOf("sa7") >= 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - - } - - @Test - public void test() throws Exception { - try { - Model model = getModelForFile("testFiles/export/new_line_file.xml", false); - List<ExportColumn> columns = new ArrayList<ExportColumn>(); - for (ExportColumn column : ExportColumn.values()) { - if (column.getClazz().isAssignableFrom(Species.class)) { - columns.add(column); - } - } - - ExporterParameters params = new IExporterService.ExporterParameters().model(model).column(columns) - .fileType(ExportFileType.TAB_SEPARATED); - - // full export (all elements) - String string = exporter.getExportSpeciesString(params); - String tmp[] = string.split("\n"); - for (String string2 : tmp) { - assertTrue(string2, columns.size() <= string2.split("\t", -1).length); - } - assertNotNull(string); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testPubmedSummary() throws Exception { - try { - Model model = getModelForFile("testFiles/export/reaction.xml", false); - List<PubmedAnnotatedElementsView> result = exporter.getPublicationModelSummary(model); - assertNotNull(result); - for (PubmedAnnotatedElementsView pubmedAnnotatedElementsView : result) { - assertNotNull(pubmedAnnotatedElementsView.getArticle()); - assertNotNull(pubmedAnnotatedElementsView.getArticle().getTitle()); - assertTrue(pubmedAnnotatedElementsView.getElements().size() > 0); - } - } 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/LayoutServiceTest2.java b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest2.java index ef9c4ddf5b15398aa01a758f4edef551940791f9..850c8695897c93835102dc082931c2edada4ae34 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest2.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest2.java @@ -17,7 +17,6 @@ import org.junit.Test; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.commands.ColorModelCommand; -import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.TextFileUtils; import lcsb.mapviewer.converter.ConverterParams; import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; 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..48edf8414c4f3f97df236f1d36ae76c115d4ca5d 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/ModelServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/ModelServiceTest.java @@ -1,10 +1,8 @@ package lcsb.mapviewer.services.impl; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; -import java.io.File; import java.util.ArrayList; import java.util.List; @@ -18,149 +16,86 @@ import org.springframework.test.annotation.Rollback; import lcsb.mapviewer.annotation.services.PubmedParser; import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.converter.graphics.MapGenerator; -import lcsb.mapviewer.converter.graphics.MapGenerator.MapGeneratorParams; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.layout.Layout; import lcsb.mapviewer.model.map.model.Model; 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 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; + } + + } } 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..a2df3103ff7b7ddb87c133e239c1777945e42e6f 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/ProjectServiceTest.java @@ -43,9 +43,7 @@ import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; import lcsb.mapviewer.model.map.model.SubmodelType; import lcsb.mapviewer.model.map.species.Element; import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.user.ObjectPrivilege; import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.model.user.UserAnnotationSchema; import lcsb.mapviewer.model.user.UserClassAnnotators; import lcsb.mapviewer.model.user.UserClassValidAnnotations; @@ -55,9 +53,7 @@ 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; @Rollback(true) public class ProjectServiceTest extends ServiceTestFunctions { @@ -72,7 +68,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 +80,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 +93,7 @@ public class ProjectServiceTest extends ServiceTestFunctions { } @Test - public void test() { + public void test() throws Exception { try { List<Project> projects = projectService.getAllProjects(adminToken); @@ -129,100 +125,6 @@ public class ProjectServiceTest extends ServiceTestFunctions { } } - @Test - public void testRemove() throws Exception { - - try { - String project_id = "Some_id"; - Project project = new Project(); - project.setProjectId(project_id); - projectDao.add(project); - - List<ProjectView> projects2 = projectService.getAllProjectViews(adminToken); - ProjectView row = null; - for (ProjectView projectRow : projects2) { - if (projectRow.getIdObject() == project.getId()) { - row = projectRow; - } - } - assertNotNull(row); - - User user = new User(); - user.setLogin("x"); - userDao.add(user); - userDao.evict(user); - - int userId = user.getId(); - - user = userService.getUserById(userId); - - userDao.evict(user); - - userService.setUserPrivilege(user, new ObjectPrivilege(project, 1, PrivilegeType.VIEW_PROJECT, user)); - - user = userService.getUserById(userId); - int newAmount = user.getPrivileges().size(); - - userDao.evict(user); - - projectService.removeProject(row, tmpResultDir, false, adminToken); - - user = userService.getUserById(userId); - - assertEquals("After removing project number of privileges didn't drop down", newAmount - 1, - user.getPrivileges().size()); - - userDao.delete(user); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemoveUserAfterRemoveProject() throws Exception { - - try { - String projectId = "Some_id"; - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - - List<ProjectView> projects2 = projectService.getAllProjectViews(adminToken); - ProjectView row = null; - for (ProjectView projectRow : projects2) { - if (projectRow.getIdObject() == project.getId()) { - row = projectRow; - } - } - assertNotNull(row); - - User user = new User(); - user.setLogin("x"); - userDao.add(user); - userDao.evict(user); - - int userId = user.getId(); - - userService.setUserPrivilege(user, new ObjectPrivilege(project, 1, PrivilegeType.VIEW_PROJECT, user)); - - user = userService.getUserById(userId); - - long counter = logDao.getCount(); - projectService.removeProject(row, tmpResultDir, false, adminToken); - long counter2 = logDao.getCount(); - assertTrue("Logs didn't appear after removing project", counter < counter2); - - user = userService.getUserById(userId); - userDao.delete(user); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - @Test public void testUpdater() throws Exception { try { @@ -251,9 +153,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 +174,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 +590,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 +622,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/java/lcsb/mapviewer/services/impl/UserServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java index 128344b26f3d320ce7167c538c7c880ed7635edf..57ae4d75f0bd5a9f408471a92fcbf6d7449051f8 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java @@ -7,35 +7,23 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.util.ArrayList; -import java.util.List; +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.test.annotation.Rollback; -import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.user.BasicPrivilege; import lcsb.mapviewer.model.user.ObjectPrivilege; import lcsb.mapviewer.model.user.PrivilegeType; import lcsb.mapviewer.model.user.User; import lcsb.mapviewer.services.ServiceTestFunctions; -import lcsb.mapviewer.services.view.PrivilegeView; -import lcsb.mapviewer.services.view.UserView; -import lcsb.mapviewer.services.view.UserView.UserProjectPrivilegeView; -import lcsb.mapviewer.services.view.UserViewFactory; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.Rollback; @Rollback(true) public class UserServiceTest extends ServiceTestFunctions { static Logger logger = Logger.getLogger(UserServiceTest.class); - @Autowired - UserViewFactory userViewFactory; - @Before public void setUp() throws Exception { createUser(); @@ -175,274 +163,4 @@ public class UserServiceTest extends ServiceTestFunctions { throw e; } } - - @Test - public void testGetAllUserList() throws Exception { - try { - User user2 = new User(); - user2.setLogin("login"); - userService.addUser(user2); - - Project project = new Project(); - projectDao.add(project); - - ObjectPrivilege privilege = new ObjectPrivilege(); - privilege.setLevel(1); - privilege.setType(PrivilegeType.VIEW_PROJECT); - privilege.setIdObject(project.getId()); - userService.setUserPrivilege(user2, privilege); - - List<UserView> list = userService.getAllUserRows(); - UserView currentUser = null; - for (UserView userRow : list) { - if (userRow.getIdObject() == user2.getId()) { - currentUser = userRow; - } - } - assertNotNull(currentUser); - assertEquals(user2.getLogin(), currentUser.getLogin()); - - PrivilegeType types[] = PrivilegeType.values(); - - List<BasicPrivilege> basicTypes = new ArrayList<BasicPrivilege>(); - List<ObjectPrivilege> projectObjectTypes = new ArrayList<ObjectPrivilege>(); - for (PrivilegeType privilegeType : types) { - if (privilegeType.getPrivilegeClassType().equals(BasicPrivilege.class)) { - basicTypes.add(privilegeType.getPrivilegeClassType().newInstance()); - } else if (privilegeType.getPrivilegeClassType().equals(ObjectPrivilege.class)) { - if (privilegeType.getPrivilegeObjectType().equals(Project.class)) { - projectObjectTypes.add((ObjectPrivilege) privilegeType.getPrivilegeClassType().newInstance()); - } - } - } - - assertEquals(basicTypes.size(), currentUser.getBasicPrivileges().size()); - - long projectCount = projectDao.getCount(); - - assertEquals(projectCount, currentUser.getProjectPrivileges().size()); - - UserProjectPrivilegeView currentProject = null; - for (UserProjectPrivilegeView projectPrivilege : currentUser.getProjectPrivileges()) { - assertEquals(projectObjectTypes.size(), projectPrivilege.getProjectPrivileges().size()); - if (projectPrivilege.getIdObject() == project.getId()) { - currentProject = projectPrivilege; - } - } - assertNotNull(currentProject); - PrivilegeView currentPrivilege = null; - for (PrivilegeView row : currentProject.getProjectPrivileges()) { - if (row.getType() == PrivilegeType.VIEW_PROJECT) { - currentPrivilege = row; - } - } - assertNotNull(currentPrivilege); - assertTrue(currentPrivilege.getSelected()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - /** - * Test update of a user that doesn't exist in db - */ - @Test - public void testUpdateUserRow() { - try { - Project project = new Project(); - projectDao.add(project); - - UserView userRow = userService.createEmptyUserRow(); - - for (PrivilegeView pRow : userRow.getBasicPrivileges()) { - if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { - pRow.setSelected(true); - } - } - - for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { - if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { - pRow.setSelected(true); - } - } - - userService.updateUser(userRow); - - assertNotNull(userRow.getIdObject()); - assertTrue(userRow.getIdObject() != 0); - - User user2 = userDao.getById(userRow.getIdObject()); - - assertTrue(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.PROJECT_MANAGEMENT)); - assertTrue(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - - for (PrivilegeView pRow : userRow.getBasicPrivileges()) { - if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { - pRow.setSelected(false); - } - } - - for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { - if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { - pRow.setSelected(false); - } - } - - userService.updateUser(userRow); - - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - /** - * Test update of a user that exist in the db - * - * @throws Exception - */ - @Test - public void testUpdateUserRow2() throws Exception { - String cryptedPassword = "passwd"; - - try { - Project project = new Project(); - projectDao.add(project); - - User user2 = new User(); - user2.setLogin("login"); - user2.setCryptedPassword(cryptedPassword); - userService.addUser(user2); - - List<UserView> rows = userService.getAllUserRows(); - UserView userRow = null; - for (UserView userRow2 : rows) { - if (userRow2.getIdObject() == user2.getId()) - userRow = userRow2; - } - - assertNotNull(userRow); - - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - - for (PrivilegeView pRow : userRow.getBasicPrivileges()) { - if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { - pRow.setSelected(true); - } - } - - for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { - if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { - pRow.setSelected(true); - } - } - - userRow.setPassword(""); - - userService.updateUser(userRow); - - User user3 = userDao.getById(user2.getId()); - - // check if password didn't change - assertEquals(cryptedPassword, user3.getCryptedPassword()); - - assertTrue(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertTrue(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - - for (PrivilegeView pRow : userRow.getBasicPrivileges()) { - if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { - pRow.setSelected(false); - } - } - - for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { - if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { - pRow.setSelected(false); - } - } - - userRow.setPassword("new passwd"); - userService.updateUser(userRow); - - user3 = userDao.getById(user2.getId()); - - // check if password changed - assertFalse(cryptedPassword.equals(user3.getCryptedPassword())); - - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemoveUserRow() throws Exception { - try { - UserView userRow = userService.createEmptyUserRow(); - userService.deleteUser(userRow); - - User user2 = new User(); - user2.setLogin("login"); - userService.addUser(user2); - - List<UserView> rows = userService.getAllUserRows(); - userRow = null; - for (UserView userRow2 : rows) { - if (userRow2.getIdObject() == user2.getId()) - userRow = userRow2; - } - - assertNotNull(userRow); - - userService.deleteUser(userRow); - - rows = userService.getAllUserRows(); - - userRow = null; - for (UserView userRow2 : rows) { - if (userRow2.getIdObject() == user2.getId()) - userRow = userRow2; - } - - assertNull(userRow); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateEmptyUserRow() { - try { - Project project = new Project(); - projectDao.add(project); - - UserView row = userService.createEmptyUserRow(); - - assertNotNull(row); - - long projectCount = projectDao.getCount(); - - assertEquals(projectCount, row.getProjectPrivileges().size()); - assertNotNull(row.getProjectPrivilegeByProjectId(project.getId())); - - for (UserProjectPrivilegeView upRow : row.getProjectPrivileges()) { - assertTrue(userViewFactory.getObjectTypes().size() >= upRow.getProjectPrivileges().size()); - } - assertEquals(userViewFactory.getBasicTypes().size(), row.getBasicPrivileges().size()); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } - } diff --git a/service/src/test/java/lcsb/mapviewer/services/search/AllSearchTests.java b/service/src/test/java/lcsb/mapviewer/services/search/AllSearchTests.java index 512a3b462cb76482a560273f03114acb946038b1..a3092af48cd13004aa392f8a5cf2f34cc9add511 100644 --- a/service/src/test/java/lcsb/mapviewer/services/search/AllSearchTests.java +++ b/service/src/test/java/lcsb/mapviewer/services/search/AllSearchTests.java @@ -4,17 +4,15 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; -import lcsb.mapviewer.services.search.comment.AllCommentTests; import lcsb.mapviewer.services.search.data.AllSearchDataTests; import lcsb.mapviewer.services.search.db.AllSearchDbTests; import lcsb.mapviewer.services.search.layout.AllSearchLayoutTests; @RunWith(Suite.class) -@SuiteClasses({ AllCommentTests.class, // - AllSearchDbTests.class, // - AllSearchDataTests.class, // - AllSearchLayoutTests.class, // - ElementMatcherTest.class, // +@SuiteClasses({ AllSearchDbTests.class, // + AllSearchDataTests.class, // + AllSearchLayoutTests.class, // + ElementMatcherTest.class, // }) public class AllSearchTests { diff --git a/service/src/test/java/lcsb/mapviewer/services/search/comment/AllCommentTests.java b/service/src/test/java/lcsb/mapviewer/services/search/comment/AllCommentTests.java deleted file mode 100644 index 1ea92dabc6a081556c202035f4eab2a163185cca..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/search/comment/AllCommentTests.java +++ /dev/null @@ -1,11 +0,0 @@ -package lcsb.mapviewer.services.search.comment; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ CommentDetailsTest.class }) -public class AllCommentTests { - -} diff --git a/service/src/test/java/lcsb/mapviewer/services/search/comment/CommentDetailsTest.java b/service/src/test/java/lcsb/mapviewer/services/search/comment/CommentDetailsTest.java deleted file mode 100644 index 538653fe471e57736e459c65f3ec0e7695d191ff..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/search/comment/CommentDetailsTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package lcsb.mapviewer.services.search.comment; - -import java.awt.geom.Point2D; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import lcsb.mapviewer.model.map.Comment; -import lcsb.mapviewer.model.map.model.ModelData; - -public class CommentDetailsTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - Comment comment = new Comment(); - comment.setCoordinates(new Point2D.Double()); - comment.setSubmodelData(new ModelData()); - - SerializationUtils.serialize(new CommentDetails(comment)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java b/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java index 671877a0c7cd18f503fa40b0c2a658686c104857..dd0b10fab092034fd723111df035ca3198469df7 100644 --- a/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/utils/ColorSchemaReaderTest.java @@ -24,10 +24,8 @@ import org.junit.Test; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.commands.ColorModelCommand; -import lcsb.mapviewer.common.Pair; import lcsb.mapviewer.common.TextFileUtils; import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; import lcsb.mapviewer.model.map.layout.ColorSchema; import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; import lcsb.mapviewer.model.map.model.Model; @@ -323,7 +321,7 @@ public class ColorSchemaReaderTest extends ServiceTestFunctions { Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/schemaWithIdentifiers.txt"); for (ColorSchema colorSchema : schemas) { - for (MiriamData md: colorSchema.getMiriamData()) { + for (MiriamData md : colorSchema.getMiriamData()) { assertNotNull(md.getResource()); assertFalse(md.getResource().isEmpty()); } @@ -342,7 +340,7 @@ public class ColorSchemaReaderTest extends ServiceTestFunctions { Collection<ColorSchema> schemas = reader.readColorSchema("testFiles/coloring/schemaIdWithoutName.txt"); for (ColorSchema colorSchema : schemas) { - for (MiriamData md: colorSchema.getMiriamData()) { + for (MiriamData md : colorSchema.getMiriamData()) { assertFalse(md.getResource().isEmpty()); assertNull(colorSchema.getName()); } diff --git a/service/src/test/java/lcsb/mapviewer/services/view/AllViewTests.java b/service/src/test/java/lcsb/mapviewer/services/view/AllViewTests.java index d8f1cf1cf592bd15e89a317fa8de67520eef61ab..07a5323d15622ea8f90bbbd88b5803a596645b4c 100644 --- a/service/src/test/java/lcsb/mapviewer/services/view/AllViewTests.java +++ b/service/src/test/java/lcsb/mapviewer/services/view/AllViewTests.java @@ -6,31 +6,21 @@ import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ AnnotationViewFactoryTest.class, // - AnnotationViewTest.class, // - CommentViewFactoryTest.class, // - CommentViewTest.class, // - ConfigurationViewFactoryTest.class, // - ConfigurationViewTest.class, // - DataMiningSetViewTest.class, // - DataMiningViewFactoryTest.class, // - DataMiningViewTest.class, // - FrameworkVersionViewTest.class, // - LayoutViewFactoryTest.class, // - LayoutViewTest.class, // - ModelViewFactoryTest.class, // - ModelViewTest.class, // - OverviewImageViewFactoryTest.class, // - OverviewImageViewTest.class, // - OverviewLinkViewFactoryTest.class, // - OverviewLinkViewTest.class, // - PrivilegeViewFactoryTest.class, // - PrivilegeViewTest.class, // - ProjectViewFactoryTest.class, // - ProjectViewTest.class, // - ReferenceGenomeViewFactoryTest.class, // - ReferenceGenomeGeneMappingViewFactoryTest.class, // - UserViewFactoryTest.class, // - UserViewTest.class, // + AnnotationViewTest.class, // + ConfigurationViewFactoryTest.class, // + ConfigurationViewTest.class, // + DataMiningSetViewTest.class, // + DataMiningViewFactoryTest.class, // + DataMiningViewTest.class, // + FrameworkVersionViewTest.class, // + LayoutViewFactoryTest.class, // + LayoutViewTest.class, // + OverviewImageViewFactoryTest.class, // + OverviewImageViewTest.class, // + OverviewLinkViewFactoryTest.class, // + OverviewLinkViewTest.class, // + ReferenceGenomeViewFactoryTest.class, // + ReferenceGenomeGeneMappingViewFactoryTest.class, // }) public class AllViewTests { diff --git a/service/src/test/java/lcsb/mapviewer/services/view/CommentViewFactoryTest.java b/service/src/test/java/lcsb/mapviewer/services/view/CommentViewFactoryTest.java deleted file mode 100644 index 13aeba6fe5b5d9beb2c177d9398dc57587ddb169..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/CommentViewFactoryTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package lcsb.mapviewer.services.view; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.model.map.Comment; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelFullIndexed; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.model.SubmodelType; -import lcsb.mapviewer.model.map.species.GenericProtein; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.services.ServiceTestFunctions; - -public class CommentViewFactoryTest extends ServiceTestFunctions { - - Logger logger = Logger.getLogger(CommentViewFactoryTest.class); - - @Autowired - CommentViewFactory commentViewFactory; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCreateEmpty() throws Exception { - try { - Object object = commentViewFactory.create(null); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateGson() throws Exception { - try { - CommentView object = commentViewFactory.create(null); - assertNotNull(commentViewFactory.createGson(object)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateOnSubmap() throws Exception { - try { - Model model = new ModelFullIndexed(null); - Model submodel = new ModelFullIndexed(null); - submodel.setId(1); - Species species = new GenericProtein("id"); - species.setId(23); - species.setName("ProteinName"); - submodel.addElement(species); - - model.addSubmodelConnection(new ModelSubmodelConnection(submodel, SubmodelType.UNKNOWN)); - - Comment comment = new Comment(); - comment.setModel(model); - comment.setSubmodel(submodel); - comment.setTableName(species.getClass()); - comment.setTableId(species.getId()); - CommentView object = commentViewFactory.create(comment,model); - assertTrue(object.getTitle().contains(species.getName())); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/service/src/test/java/lcsb/mapviewer/services/view/CommentViewTest.java b/service/src/test/java/lcsb/mapviewer/services/view/CommentViewTest.java deleted file mode 100644 index 170e999db182311a86f62b909ce669fe134ecc7f..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/CommentViewTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package lcsb.mapviewer.services.view; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class CommentViewTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new CommentView()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } -} diff --git a/service/src/test/java/lcsb/mapviewer/services/view/ModelViewFactoryTest.java b/service/src/test/java/lcsb/mapviewer/services/view/ModelViewFactoryTest.java deleted file mode 100644 index 32a78c241c5fd296359e71eea7c5afe6211cb508..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/ModelViewFactoryTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package lcsb.mapviewer.services.view; - -import static org.junit.Assert.assertNotNull; - -import java.util.ArrayList; -import java.util.List; - -import lcsb.mapviewer.services.ServiceTestFunctions; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.primefaces.model.map.LatLng; -import org.springframework.beans.factory.annotation.Autowired; - -public class ModelViewFactoryTest extends ServiceTestFunctions{ - @SuppressWarnings("unused") - private static Logger logger = Logger.getLogger(ModelViewFactoryTest .class); - - @Autowired - ModelViewFactory modelViewFactory; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCreateEmpty() throws Exception { - try { - Object object = modelViewFactory.create(null); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateJson() throws Exception { - try { - ModelView object = modelViewFactory.create(null); - String json = modelViewFactory.createGson(object); - assertNotNull(json); - - object.setCenterLatLng(new LatLng(1, 2)); - List<String> list = new ArrayList<>(); - list.add("ASS"); - object.setDescription("ASDAS"); - object.setIdObject(2); - List<LayoutView> views = new ArrayList<LayoutView>(); - LayoutView view = new LayoutView(); - view.setCreator("AA"); - view.setDirectory("C:\\test\\directory/"); - views.add(view); - object.setLayouts(views); - object.setMaxZoom(4); - object.setMinZoom(3); - object.setPictureSize(123); - object.setTileSize(234); - object.setVersion("#$#$#"); - json = modelViewFactory.createGson(object); - assertNotNull(json); - - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/service/src/test/java/lcsb/mapviewer/services/view/ModelViewTest.java b/service/src/test/java/lcsb/mapviewer/services/view/ModelViewTest.java deleted file mode 100644 index 36825505843e59d932aef5908f454e1939755901..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/ModelViewTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package lcsb.mapviewer.services.view; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ModelViewTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ModelView()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } -} diff --git a/service/src/test/java/lcsb/mapviewer/services/view/PrivilegeViewFactoryTest.java b/service/src/test/java/lcsb/mapviewer/services/view/PrivilegeViewFactoryTest.java deleted file mode 100644 index 9dc91d43c02ae25fffd6335d3b9a46aae0474084..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/PrivilegeViewFactoryTest.java +++ /dev/null @@ -1,47 +0,0 @@ -package lcsb.mapviewer.services.view; - -import static org.junit.Assert.*; -import lcsb.mapviewer.model.user.BasicPrivilege; -import lcsb.mapviewer.services.ServiceTestFunctions; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -public class PrivilegeViewFactoryTest extends ServiceTestFunctions{ - - @Autowired - PrivilegeViewFactory privilegeViewFactory; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCreateEmpty() throws Exception { - try { - Object object = privilegeViewFactory.create(new BasicPrivilege()); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateGson() throws Exception { - try { - PrivilegeView object = privilegeViewFactory.create(new BasicPrivilege()); - assertNotNull(privilegeViewFactory.createGson(object)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/service/src/test/java/lcsb/mapviewer/services/view/PrivilegeViewTest.java b/service/src/test/java/lcsb/mapviewer/services/view/PrivilegeViewTest.java deleted file mode 100644 index 09521bd38c4b8de7e196e29cfdeb7361626e3d93..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/PrivilegeViewTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package lcsb.mapviewer.services.view; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class PrivilegeViewTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new PrivilegeView()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } -} diff --git a/service/src/test/java/lcsb/mapviewer/services/view/ProjectViewFactoryTest.java b/service/src/test/java/lcsb/mapviewer/services/view/ProjectViewFactoryTest.java deleted file mode 100644 index 6a7665d94aabd0e1eb97703d2f9835a90705c36d..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/ProjectViewFactoryTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package lcsb.mapviewer.services.view; - -import static org.junit.Assert.*; -import lcsb.mapviewer.services.ServiceTestFunctions; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -public class ProjectViewFactoryTest extends ServiceTestFunctions{ - - @Autowired - ProjectViewFactory projectViewFactory; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCreateEmpty() throws Exception { - try { - Object object = projectViewFactory.create(null); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateGson() throws Exception { - try { - ProjectView object = projectViewFactory.create(null); - assertNotNull(projectViewFactory.createGson(object)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/service/src/test/java/lcsb/mapviewer/services/view/ProjectViewTest.java b/service/src/test/java/lcsb/mapviewer/services/view/ProjectViewTest.java deleted file mode 100644 index 6af4866b3afc03fc07e0ca53d8ab2d61d7c8eaf9..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/ProjectViewTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package lcsb.mapviewer.services.view; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class ProjectViewTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new ProjectView()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } -} diff --git a/service/src/test/java/lcsb/mapviewer/services/view/UserViewFactoryTest.java b/service/src/test/java/lcsb/mapviewer/services/view/UserViewFactoryTest.java deleted file mode 100644 index 993476aa48a9adf0bfc3d20c8035daeb5e04b79d..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/UserViewFactoryTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package lcsb.mapviewer.services.view; - -import static org.junit.Assert.*; -import lcsb.mapviewer.services.ServiceTestFunctions; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -public class UserViewFactoryTest extends ServiceTestFunctions{ - - @Autowired - UserViewFactory userViewFactory; - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testCreateEmpty() throws Exception { - try { - Object object = userViewFactory.create(null); - assertNotNull(object); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testCreateGson() throws Exception { - try { - UserView object = userViewFactory.create(null); - assertNotNull(userViewFactory.createGson(object)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/service/src/test/java/lcsb/mapviewer/services/view/UserViewTest.java b/service/src/test/java/lcsb/mapviewer/services/view/UserViewTest.java deleted file mode 100644 index 1ccae9a0721c8d91e78b9a9a69f2a684a0fb9a08..0000000000000000000000000000000000000000 --- a/service/src/test/java/lcsb/mapviewer/services/view/UserViewTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package lcsb.mapviewer.services.view; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class UserViewTest { - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSerialization() { - try { - SerializationUtils.serialize(new UserView()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } -} 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/AbstractManagedBean.java b/web/src/main/java/lcsb/mapviewer/bean/AbstractManagedBean.java deleted file mode 100644 index 8caa363dc146f987a72b0b54178b16376a29fc62..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/AbstractManagedBean.java +++ /dev/null @@ -1,547 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.VetoableChangeSupport; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.PostConstruct; -import javax.faces.component.UIComponent; -import javax.faces.context.ExternalContext; -import javax.faces.context.FacesContext; - -import org.apache.commons.io.IOUtils; -import org.apache.log4j.Logger; - -import com.google.gson.Gson; - -import lcsb.mapviewer.bean.utils.IPrimefacesUtils; -import lcsb.mapviewer.bean.utils.PrimefacesUtils; -import lcsb.mapviewer.common.MimeType; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.events.Event; -import lcsb.mapviewer.events.Listener; -import lcsb.mapviewer.model.map.model.Model; - -/** - * Abstarct bean class containing basic functionality common for all beans - * (property change listeners and vetoable property change listeners). - * - * @author Piotr Gawron - * - */ -public abstract class AbstractManagedBean implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Util class used to access information about current reqruest and general - * information about P framework. - */ - private transient IPrimefacesUtils primefacesUtils = new PrimefacesUtils(); - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(AbstractManagedBean.class); - - /** - * Set of verification listeners called when some property is changed. It's - * marked transient because we don't want to store this in session. TODO it's - * should be modified. - */ - private final VetoableChangeSupport vchs = new VetoableChangeSupport(this); - - /** - * Set of listeners called when some property is changed. It's marked - * transient because we don't want to store this in session. TODO it's should - * be modified. - */ - private final PropertyChangeSupport pchs = new PropertyChangeSupport(this); - - /** - * This map contains information about {@link Listener listeners} that should - * be handled when {@link #callListeners(Event)} method is called. It's marked - * transient because we don't want to store this in session. TODO it's should - * be modified. - */ - private transient Map<Class<? extends Event>, List<Listener<?>>> listeners = new HashMap<Class<? extends Event>, List<Listener<?>>>(); - - - /** - * Default constructor. Adds generic log listener to property change - * listeners. - */ - public AbstractManagedBean() { - // logger property listener - PropertyChangeListener propertyChangeLogger = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - logger.debug("Property changed: " + arg0.getPropertyName() + ". Old: " + arg0.getOldValue() + " New: " + arg0.getNewValue()); - } - - }; - addPropertyChangeListener(propertyChangeLogger); - - } - - /** - * Method run after creating all the beans. It's used for data initalization. - */ - public abstract void init(); - - /** - * Initialize common data and call custom initializer of the bean. - */ - @PostConstruct - public void internalInit() { - createSession(); - logger.debug("Initializing bean: " + this); - - // call init method for specific bean - init(); - logger.debug("Bean: " + this + " initialized."); - } - - /** - * Creates http session if session hasn't been created yet. - */ - public void createSession() { - getPrimefacesUtils().createSession(); - } - - /** - * Add property change listener that can VETO (cancel) the property change. - * - * @param listener - * property listener - */ - public final void addVetoablePropertyChangeListener(final VetoableChangeListener listener) { - vchs.addVetoableChangeListener(listener); - } - - /** - * Removes property change l;istener that can VETO from the available - * listeners. - * - * @param listener - * listeren to be removed - */ - public final void removeVetoablePropertyChangeListener(final VetoableChangeListener listener) { - vchs.removeVetoableChangeListener(listener); - } - - /** - * Adds property change listener that is fired after property of a bean is - * changed. - * - * @param listener - * listener to be added - */ - public final void addPropertyChangeListener(final PropertyChangeListener listener) { - pchs.addPropertyChangeListener(listener); - } - - /** - * Removes property change listener from the list of all available listeners. - * - * @param listener - * listener to be removed - */ - public final void removePropertyChangeListener(final PropertyChangeListener listener) { - pchs.removePropertyChangeListener(listener); - } - - /** - * Method that fires all vetoable property change listener for a given - * property. - * - * @param propertyName - * property that has changed - * @param oldValue - * old value of the property - * @param newValue - * new value of the property - * @throws PropertyVetoException - * if the change shouldn't be made this exception is thrown - */ - protected final void fireVetoableChange(final String propertyName, final Object oldValue, final Object newValue) throws PropertyVetoException { - vchs.fireVetoableChange(propertyName, oldValue, newValue); - } - - /** - * Method fires property change listener for a given property. - * - * @param propertyName - * name of the property that has changed - * @param oldValue - * old value of the property - * @param newValue - * new value of the property - */ - protected final void firePropertyChange(final String propertyName, final Object oldValue, final Object newValue) { - if (oldValue != null || newValue != null) { - pchs.firePropertyChange(propertyName, oldValue, newValue); - } - } - - /** - * Returns list of all property change listeners for the bean (includes only - * standard property change listeners, vetoable property change listeners are - * excluded). - * - * @return list of property change listeners - */ - protected final PropertyChangeListener[] getPropertyChangeListeners() { - return pchs.getPropertyChangeListeners(); - } - - // TODO refactor these two methods to reduce copy-paste - - /** - * Method sends to a client response with an attached file. The content of the - * file is taken from the content param. Type defines MimeType of the content - * (text file, xml, etc.) - this helps browser to properly handle response. - * - * @param content - * - string with the file content - * @param fileName - * - name of the file that should popup in the client browser - * @param type - * - MIME type of the file - * @throws IOException - * exception thrown when there are some problems with sending file - */ - protected final void sendFileAsResponse(String content, String fileName, MimeType type) throws IOException { - // send the response to client - FacesContext fc = FacesContext.getCurrentInstance(); - ExternalContext ec = fc.getExternalContext(); - - ec.responseReset(); - ec.setResponseContentType(type.getTextRepresentation()); - ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); - ec.addResponseHeader("Content-Type", type.getTextRepresentation()); - - OutputStream output = ec.getResponseOutputStream(); - PrintStream printStream = new PrintStream(output); - printStream.print(content); - - fc.responseComplete(); - } - - /** - * Method sends to a client response with an attached file. Type defines - * MimeType of the file content (text file, xml, etc.) - this helps browser to - * properly handle response. - * - * @param file - * - file which will be sent - * @param fileName - * - name of the file that should popup in the client browser - * @param type - * - MIME type of the file - * @throws IOException - * exception thrown when there are some problems with sending file - */ - protected void sendFileAsResponse(File file, String fileName, MimeType type) throws IOException { - - // start sending - FacesContext fc = FacesContext.getCurrentInstance(); - ExternalContext ec = fc.getExternalContext(); - - ec.responseReset(); - ec.setResponseContentType(type.getTextRepresentation()); - ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); - - // attach file - OutputStream output = ec.getResponseOutputStream(); - FileInputStream is = new FileInputStream(file); - IOUtils.copy(is, output); - fc.responseComplete(); - - } - - /** - * Clears whole data shared by this bean. - */ - public abstract void clear(); - - /** - * Register new {@link Listener} in this bean. - * - * @param listener - * listener that should be added - */ - public void registerListener(Listener<?> listener) { - List<Listener<?>> listenerList = getListeners().get(listener.getEventClass()); - if (listenerList == null) { - listenerList = new ArrayList<Listener<?>>(); - listeners.put(listener.getEventClass(), listenerList); - } - listenerList.add(listener); - } - - /** - * This method will call all listeners associated with the specified - * {@link Event}. - * - * @param event - * {@link Event} for which listeners will be called - */ - protected void callListeners(Event event) { - List<Listener<?>> listenerList = getListeners().get(event.getClass()); - if (listenerList == null) { - logger.warn("No listeners found for event: " + event); - } else { - for (Listener<?> listener : listenerList) { - listener.handleEvent(event); - } - } - - } - - /** - * Unregister {@link Listener} from this bean. - * - * @param listener - * listener that should be removed - */ - public void unregisterListener(Listener<?> listener) { - List<Listener<?>> listenerList = listeners.get(listener.getEventClass()); - if (listenerList == null) { - listenerList = new ArrayList<Listener<?>>(); - listeners.put(listener.getEventClass(), listenerList); - } - if (listenerList.contains(listener)) { - listenerList.remove(listener); - } else { - throw new InvalidArgumentException("Listener " + listener + " wasn't registered."); - } - - } - - /** - * @param primefacesUtils - * the primefacesUtils to set - * @see #primefacesUtils - */ - protected void setPrimefacesUtils(IPrimefacesUtils primefacesUtils) { - this.primefacesUtils = primefacesUtils; - } - - /** - * Returns value of the parameter from http request call. - * - * @param name - * name of the parameter - * @return value of the request parameter - */ - protected String getRequestParameter(String name) { - return getPrimefacesUtils().getRequestParameter(name); - } - - /** - * Adds a parameter that will be stored in user session. - * - * @param key - * name of the parameter - * @param value - * value of the parameter - */ - protected void addSessionParam(String key, Object value) { - getPrimefacesUtils().addSessionParam(key, value); - } - - /** - * Gets a value of the parameter stored in user session. - * - * @param key - * name of the parameter - * @return value of the user session parameter - */ - protected Object getSessionParam(String key) { - return getPrimefacesUtils().getSessionParam(key); - } - - /** - * @return the version of primefaces library - */ - public String getPrimefacesVersion() { - return getPrimefacesUtils().getVersion(); - } - - /** - * Returns path on hard drive where the project is deplyed. - * - * @return path where the projest is running - */ - public String getProjectDeployPath() { - return getPrimefacesUtils().getPath(); - } - - /** - * Sends an error message to the client. - * - * @param message - * error message to be sent - */ - protected void sendError(String message) { - getPrimefacesUtils().error(message); - } - - /** - * Sends an error message to the client. - * - * @param message - * error message to be sent - * @param exception - * exception which caused the error - */ - protected void sendError(String message, Exception exception) { - logger.error(message, exception); - getPrimefacesUtils().error(message); - } - - /** - * Sends info message to the client. - * - * @param message - * info message to be sent - */ - protected void sendInfo(String message) { - getPrimefacesUtils().info(message); - } - - /** - * Returns ip address of current client. - * - * @return IP addresss of the client - */ - protected String getClientIpAddress() { - return getPrimefacesUtils().getClientIpAddress(); - } - - /** - * Returns a {@link UIComponent} corresponding to the client side component - * with the identifier given in the parameter. - * - * @param id - * identifier of a component - * @return {@link UIComponent} corresponding to the client side component with - * the identifier given in the parameter - */ - protected UIComponent findComponent(String id) { - return getPrimefacesUtils().findComponent(id); - } - - /** - * Returns bean identified by {@link Class}. - * - * @param clazz - * class of the bean - * @param <T> - * class of the bean - * @return bean identified by {@link Class} - */ - public <T> T findBean(Class<T> clazz) { - return getPrimefacesUtils().findBean(clazz); - } - - /** - * @return primefacesUtils. - */ - public IPrimefacesUtils getPrimefacesUtils() { - if (primefacesUtils == null) { - primefacesUtils = new PrimefacesUtils(); - } - return primefacesUtils; - } - - /** - * @return listeners. - */ - public Map<Class<? extends Event>, List<Listener<?>>> getListeners() { - if (listeners == null) { - listeners = new HashMap<Class<? extends Event>, List<Listener<?>>>(); - } - return listeners; - } - - /** - * @param listeners - * general listeners. - */ - public void setListeners(Map<Class<? extends Event>, List<Listener<?>>> listeners) { - this.listeners = listeners; - } - - /** - * Executes javascript code on the client browser. - * - * @param javascript - * javascript code - */ - public void executeJavascript(String javascript) { - getPrimefacesUtils().executeJavascript(javascript); - } - - /** - * Transform json string representing list of pairs with model and object id - * (it can be list of alias ids or reaction ids) into a {@link List} of - * {@link Pair pairs}. - * - * @param string - * list containing pairs of identifiers - * @return list of pairs with model and alias id: {@link Pair#left} contains - * {@link Model#getId()} and {@link Pair#right} conatins - * {@link lcsb.mapviewer.model.map.species.Element#id}. - * - */ - protected List<Pair<Integer, Integer>> deserializeJsonIds(String string) { - List<Pair<Integer, Integer>> result = new ArrayList<>(); - @SuppressWarnings("unchecked") - List<List<?>> list = new Gson().fromJson(string, List.class); - for (List<?> list2 : list) { - Integer left = null; - Object leftObj = list2.get(0); - if (leftObj instanceof Double) { - left = ((Double) leftObj).intValue(); - } else if (leftObj instanceof String) { - left = Integer.valueOf((String) leftObj); - } else { - throw new InvalidArgumentException("Don't know how to handle class: " + leftObj.getClass()); - } - - Integer right = null; - Object rightObj = list2.get(1); - if (rightObj instanceof Double) { - right = ((Double) rightObj).intValue(); - } else if (rightObj instanceof String) { - right = Integer.valueOf((String) rightObj); - } else { - throw new InvalidArgumentException("Don't know how to handle class: " + rightObj.getClass()); - } - - result.add(new Pair<Integer, Integer>(left, right)); - } - return result; - } - - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/AbstractMarkerManagerBean.java b/web/src/main/java/lcsb/mapviewer/bean/AbstractMarkerManagerBean.java deleted file mode 100644 index 2ec5a5d19c3b97f84650149c6cbc4b0756376154..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/AbstractMarkerManagerBean.java +++ /dev/null @@ -1,333 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import javax.faces.event.ActionEvent; -import javax.faces.event.AjaxBehaviorEvent; - -import org.apache.log4j.Logger; - -import com.google.gson.Gson; - -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.services.search.ElementIdentifierDetails; -import lcsb.mapviewer.services.search.ISearchResultView; -import lcsb.mapviewer.services.search.data.ElementIdentifier; -import lcsb.mapviewer.services.search.data.ElementIdentifier.ElementIdentifierType; - -/** - * Abstract bean class containing interface to connect with google maps API on - * the client side. - * - * @param <T> - * type of search result returned by single query - * - * @author Piotr Gawron - * - */ -public abstract class AbstractMarkerManagerBean<T extends ISearchResultView> extends AbstractManagedBean { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(AbstractMarkerManagerBean.class); - - /** - * Object with all results to be send to the client. - */ - private List<T> results = new ArrayList<>(); - - /** - * List of elements that should be visualized on the map. Any element in - * {@link #results} can be visualized at many places (or none at all) o the - * map. - */ - private List<ElementIdentifier> elementsOnMap = new ArrayList<>(); - - /** - * This field should be initialized by client side and contain name of the - * javascript object that will accept callback with information about markers - * on the map. - */ - private String overlayCollection = ""; - - /** - * This method send the data to javascipt using javascipt class with the name - * stored in drugOverlayCollection. - */ - public final void refreshDataInJavascript() { - refreshDataInJavascript(false); - } - - /** - * This method send the data to javascipt using javascipt class with the name - * stored in drugOverlayCollection. - * - * @param autoZoom - * determines if the map should auto zoom into the region containing - * all elements. - */ - public final void refreshDataInJavascript(final boolean autoZoom) { - try { - if ("".equals(overlayCollection)) { - logger.warn(this.getClass().getSimpleName() + ": Cannot refresh data in JavaScript, because overlayCollection is not set"); - } else { - String javascriptCode = ""; - List<String> ids = new ArrayList<>(); - for (ISearchResultView element : results) { - ids.add(element.getUniqueId()); - } - javascriptCode += "ServerConnector.setOverlayResultIds('" + overlayCollection + "'," + new Gson().toJson(ids) + ");"; - javascriptCode += "ServerConnector.updateOverlayCollection('" + overlayCollection + "'," + getGmapElementsInGson() + ", " + autoZoom + ");"; - executeJavascript(javascriptCode); - } - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Sends detailed information to the broswer about specific element visualized - * on the map in context of a search result (from {@link #results}) identified - * by searchResultIdentifier ({@link ISearchResultView#getUniqueId()}). - * - * @param ei - * element for which we send detailed data - * @param searchResultIdentifier - * identifier of {@link ISearchResultView} for which the details are - * valid - * @param dataToSend - * data to be sent - */ - private void sendDetailData(ElementIdentifier ei, String searchResultIdentifier, ElementIdentifierDetails dataToSend) { - if ("".equals(overlayCollection)) { - logger.warn(this.getClass().getSimpleName() + ": Cannot refresh data in JavaScript, because overlayCollection is not set"); - } else { - Gson gsonParser = new Gson(); - String dataEncoded = "null"; - if (dataToSend != null) { - dataEncoded = gsonParser.toJson(dataToSend); - } - String nameEncoded = gsonParser.toJson(overlayCollection); - String resultResultIdEncoded = gsonParser.toJson(searchResultIdentifier); - String elementIdEncoded = gsonParser.toJson(ei); - String javascriptCode = "ServerConnector.updateOverviewElementDetailData(" + nameEncoded + "," + resultResultIdEncoded + "," + elementIdEncoded + ", " - + dataEncoded + ");\n"; - executeJavascript(javascriptCode.toString()); - } - } - - /** - * This method register javascript class name for the callback. - * - * @param actionEvent - * event from thefrom the client - */ - public final void registerOverlayCollection(final ActionEvent actionEvent) { - // get the request param with the overlay name - overlayCollection = getRequestParameter("overlayName"); - } - - /** - * Method called by client broswer to request detail information about - * element. - * - * @param actionEvent - * default {@link ActionEvent} object for jsf calls - * - * @see #sendDetailData(ElementIdentifier, String, ElementIdentifierDetails) - */ - public final void requestDetailData(final ActionEvent actionEvent) { - try { - // get the request param with the overlay name - String searchResultIdentifier = getRequestParameter("searchResultIdentifier"); - String objectIdentifier = getRequestParameter("objectIdentifier"); - String modelIdentifier = getRequestParameter("modelIdentifier"); - String type = getRequestParameter("type"); - ElementIdentifier ei = new ElementIdentifier(objectIdentifier, modelIdentifier, ElementIdentifierType.getTypeByJsName(type), null); - - T searchResult = null; - for (T element : results) { - if (element.getUniqueId().equals(searchResultIdentifier)) { - searchResult = element; - } - } - if (searchResult == null) { - List<Pair<String, ElementIdentifierDetails>> results = getElementInformationForResult(ei); - for (Pair<String, ElementIdentifierDetails> pair : results) { - sendDetailData(ei, pair.getLeft(), pair.getRight()); - } - sendDetailData(ei, "__FULL__", null); - - } else { - sendDetailData(ei, searchResultIdentifier, getElementInformationForResult(ei, searchResult)); - } - } catch (Exception e) { - sendError("Internal server error", e); - } - - } - - /** - * @param actionEvent - * event from thefrom the client - * @see #refreshDataInJavascript() - */ - public final void refreshOverlayCollection(final AjaxBehaviorEvent actionEvent) { - refreshOverlayCollection(new ActionEvent(actionEvent.getComponent())); - } - - /** - * @param actionEvent - * event from thefrom the client - * @see #refreshDataInJavascript() - */ - public final void refreshOverlayCollection(final ActionEvent actionEvent) { - refreshOverlayCollection(); - } - - /** - * Refresh list of visible elements on the map (only map, the left panel is - * untouched). - */ - private void refreshOverlayCollection() { - this.elementsOnMap.clear(); - for (T result : results) { - this.elementsOnMap.addAll(getLightElementsForSearchResult(result)); - } - refreshDataInJavascript(); - } - - /** - * Returns {@link #elementsOnMap} in json format. - * - * @return {@link #elementsOnMap} in json format - */ - private String getGmapElementsInGson() { - return new Gson().toJson(elementsOnMap); - } - - /** - * Clears result in {@link #results} and {@link #elementsOnMap}. - */ - protected void clearResults() { - results.clear(); - elementsOnMap.clear(); - } - - /** - * Adds result to the list of result that should be visualized on client side. - * - * @param result - * result to add - */ - protected void addResult(T result) { - this.results.add(result); - this.elementsOnMap.addAll(getLightElementsForSearchResult(result)); - - } - - /** - * Adds set of results to the list of result that should be visualized on - * client side. - * - * @param results - * collection of elements to add - */ - protected void addResults(Collection<T> results) { - for (T t : results) { - addResult(t); - } - } - - /** - * @return the results - * @see #results - */ - public List<T> getResults() { - return results; - } - - /** - * This method split query string into list of queies that should be processed - * by the bean. - * - * @param query - * input query string - * @param useFullName - * treat query as a name (without splitting) - * @return list of separate queries that could be obtained from input string - */ - protected List<String> splitQuery(String query, boolean useFullName) { - String tmpQuery = query.trim().toLowerCase(); - - List<String> result = new ArrayList<>(); - String[] elements; - if (query.contains(";")) { - elements = tmpQuery.split(";"); - } else { - elements = tmpQuery.split(","); - } - - for (String string : elements) { - result.add(string.trim()); - } - if (!result.contains(tmpQuery) && useFullName) { - result.add(tmpQuery); - } - return result; - } - - /** - * Returns list of {@link ElementIdentifier elements} that should be - * visualized for single search result. - * - * @param result - * object which we investigate - * @return list of {@link ElementIdentifier elements} that should be - * visualized for single search result - */ - protected abstract List<ElementIdentifier> getLightElementsForSearchResult(T result); - - /** - * Returns {@link ElementIdentifierDetails detailed information} about - * {@link ElementIdentifier element} in context of search result. - * - * @param element - * element for which we gather detailed information - * @param result - * {@link ISearchResultView} for which we want to have detailed - * information - * @return {@link ElementIdentifierDetails detailed information} about - * {@link ElementIdentifier element} in context of search result, - * <code>null</code> if such data doesn't exist - */ - protected abstract ElementIdentifierDetails getElementInformationForResult(ElementIdentifier element, T result); - - /** - * Returns {@link ElementIdentifierDetails detailed information} about - * {@link ElementIdentifier element}. - * - * @param element - * element for which we gather detailed information - * @return list of {@link ElementIdentifierDetails detailed informations} - * about {@link ElementIdentifier element}, or empty list if such data - * doesn't exist, the information is a pair: identifier, data - */ - protected abstract List<Pair<String, ElementIdentifierDetails>> getElementInformationForResult(ElementIdentifier element); - - /** - * @return the elementsOnMap - * @see #elementsOnMap - */ - public List<ElementIdentifier> getElementsOnMap() { - return elementsOnMap; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/ConfigurationBean.java b/web/src/main/java/lcsb/mapviewer/bean/ConfigurationBean.java deleted file mode 100644 index b93fdd83be4beaa8cbf60a0da5a956f6af3e40ac..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/ConfigurationBean.java +++ /dev/null @@ -1,509 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.io.File; -import java.io.Serializable; -import java.text.NumberFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.event.ActionEvent; - -import org.apache.commons.validator.routines.UrlValidator; -import org.apache.log4j.Logger; - -import lcsb.mapviewer.common.Configuration; -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; -import lcsb.mapviewer.services.view.ConfigurationView; -import lcsb.mapviewer.services.view.ProjectView; - -/** - * Bean used for managing configuration (configurable parameters of the system). - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "configurationMB") -@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); - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/ExportBean.java b/web/src/main/java/lcsb/mapviewer/bean/ExportBean.java deleted file mode 100644 index 5cae8b626361a5b2b54c37eadd42394c59164a38..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/ExportBean.java +++ /dev/null @@ -1,1391 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.awt.geom.Path2D; -import java.awt.geom.PathIterator; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; - -import org.apache.commons.io.IOUtils; -import org.apache.log4j.Logger; -import org.primefaces.model.DualListModel; -import org.primefaces.model.menu.DefaultMenuItem; -import org.primefaces.model.menu.DefaultMenuModel; -import org.primefaces.model.menu.DefaultSubMenu; -import org.primefaces.model.menu.MenuModel; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; - -import lcsb.mapviewer.bean.MapBean.ClientMapData; -import lcsb.mapviewer.commands.ClearColorModelCommand; -import lcsb.mapviewer.commands.ColorExtractor; -import lcsb.mapviewer.commands.ColorModelCommand; -import lcsb.mapviewer.commands.CopyCommand; -import lcsb.mapviewer.commands.SubModelCommand; -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.MimeType; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.converter.ConverterException; -import lcsb.mapviewer.converter.IConverter; -import lcsb.mapviewer.converter.graphics.AbstractImageGenerator; -import lcsb.mapviewer.converter.graphics.AbstractImageGenerator.Params; -import lcsb.mapviewer.converter.graphics.ImageGenerators; -import lcsb.mapviewer.converter.graphics.SvgImageGenerator; -import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; -import lcsb.mapviewer.converter.model.sbgnml.SbgnmlXmlConverter; -import lcsb.mapviewer.model.map.InconsistentModelException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.compartment.Compartment; -import lcsb.mapviewer.model.map.layout.ColorSchema; -import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.map.model.ModelSubmodelConnection; -import lcsb.mapviewer.model.map.reaction.Reaction; -import lcsb.mapviewer.model.map.species.AntisenseRna; -import lcsb.mapviewer.model.map.species.Complex; -import lcsb.mapviewer.model.map.species.Degraded; -import lcsb.mapviewer.model.map.species.Drug; -import lcsb.mapviewer.model.map.species.Element; -import lcsb.mapviewer.model.map.species.Gene; -import lcsb.mapviewer.model.map.species.Ion; -import lcsb.mapviewer.model.map.species.Phenotype; -import lcsb.mapviewer.model.map.species.Protein; -import lcsb.mapviewer.model.map.species.Rna; -import lcsb.mapviewer.model.map.species.SimpleMolecule; -import lcsb.mapviewer.model.map.species.Species; -import lcsb.mapviewer.model.map.species.Unknown; -import lcsb.mapviewer.services.interfaces.IExporterService; -import lcsb.mapviewer.services.interfaces.IExporterService.ExporterParameters; -import lcsb.mapviewer.services.interfaces.ILayoutService; -import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.utils.ColorSchemaReader; -import lcsb.mapviewer.services.utils.data.BuildInLayout; -import lcsb.mapviewer.services.utils.data.ExportColumn; -import lcsb.mapviewer.services.utils.data.ExportFileType; -import lcsb.mapviewer.services.utils.gmap.CoordinationConverter; -import lcsb.mapviewer.services.view.PubmedAnnotatedElementsView; - -/** - * Bean used to export data. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "exportMB") -@ViewScoped -public class ExportBean extends AbstractManagedBean { - - /** - * Constant defining size of the array returned by - * {@link PathIterator#currentSegment(double[])} method. More nformation can - * be found <a href= - * "http://docs.oracle.com/javase/7/docs/api/java/awt/geom/PathIterator.html#currentSegment(double[])" - * >here</a> - */ - private static final int PATH_ITERATOR_SEGMENT_SIZE = 6; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(ExportBean.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * List of selected species (node) types to be exported. - */ - private List<String> selectedSpeciesType = new ArrayList<>(); - - /** - * List of selected species (node) fields to be exported. - */ - private List<String> selectedSpeciesColumn = new ArrayList<>(); - - /** - * List of selected species (node) types to be exported in export network - * mode. - */ - private List<String> selectedNetworkType = new ArrayList<>(); - - /** - * Network export file type. - */ - private String selectedNetworkFileType = ""; - - /** - * List of species (nodes) types. - */ - private List<String> speciesTypeList; - - /** - * List of species (nodes) columns. - */ - private List<String> speciesColumnList = new ArrayList<>(); - - /** - * List of file types for network export. - */ - private List<String> networkFileTypeList = new ArrayList<>(); - - /** - * Part of the map (in polygon format) to be exported. - */ - private String selectedPolygon = ""; - - /** - * On which model the export should be perfomerd. - */ - private String selectedModelId = ""; - - /** - * Which layouts are visible in javascript. - */ - private String visibleLayouts = "[]"; - - /** - * List of model names. - */ - private List<String> models = new ArrayList<>(); - - /** - * List with information about available {@link AbstractImageGenerator} - * classes. Left value defines name of the format, right the class that is - * responsible to generate specific format. - */ - private List<Pair<String, Class<? extends AbstractImageGenerator>>> imageGenerators = new ArrayList<>(); - - /** - * Name of submodel to export. - */ - private String selectedModelString; - - /** - * List of {@link MiriamType} annotations to include in network export. - */ - private DualListModel<Pair<MiriamType, String>> networkAvailableMiriam = new DualListModel<>(); - - /** - * List of components (compartments) to include in network export. - */ - private DualListModel<String> networkIncludedComponent = new DualListModel<>(); - - /** - * List of components (compartments) to exclude in network export. - */ - private DualListModel<String> networkExcludedComponent = new DualListModel<>(); - - /** - * List of {@link MiriamType} annotations to include in element export. - */ - private DualListModel<Pair<MiriamType, String>> elementAvailableMiriam = new DualListModel<>(); - - /** - * List of components (compartments) to include in element export. - */ - private DualListModel<String> elementIncludedComponent = new DualListModel<>(); - - /** - * List of components (compartments) to exclude in element export. - */ - private DualListModel<String> elementExcludedComponent = new DualListModel<>(); - - /** - * Map between name of the node type and class. - */ - private Map<String, Class<?>> speciesTypeMap = null; - - /** - * Map between name of the column and column object. - */ - private Map<String, ExportColumn> speciesColumnMap = new LinkedHashMap<>(); - - /** - * Map between name of the file type and file type. - */ - private Map<String, ExportFileType> networkFileTypeMap = new LinkedHashMap<>(); - - /** - * List of publications for current model. If <code>null</code> then data is - * not initialized (this list is lazy initialized, because it can be big). - */ - private List<PubmedAnnotatedElementsView> pubmedModelSummary = null; - - /** - * Class used to export images. - */ - private transient ImageGenerators imageGenerator = null; - - /** - * Right menu allowing user to export data from map. It's dynamically created - * to handle all currently available formats. Menu is active when clicking on - * some selected region on the map. - */ - private transient MenuModel imageExportMenu; - - /** - * Right menu allowing user to export data from map. It's dynamically created - * to handle all currently available formats. Menu is active when clicking on - * any place (except of selected region) on the map. - */ - private transient MenuModel contextMenu; - - /** - * Service that allows to export data of the map into other formats. - */ - @ManagedProperty(value = "#{ExporterService}") - private transient IExporterService exporterService; - - /** - * Service that allows to access data abaout users. - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * Service that deal with {@link Layout layouts}. - */ - @ManagedProperty(value = "#{LayoutService}") - private transient ILayoutService layoutService; - - /** - * Bean used for accessing information about currently browsed map. - */ - @ManagedProperty(value = "#{mapMB}") - private transient MapBean mapBean; - - /** - * Bean managing currently logged user. - */ - @ManagedProperty(value = "#{userMB}") - private transient UserBean userBean; - - /** - * Default constructor. - */ - public ExportBean() { - } - - /** - * Fills lists with {@link MiriamType miriam types} and number of occurences - * of this annotations in the parameter model. - * - * @param model - * model from which annotations should be counted - */ - private void fillAnnotationNumbers(Model model) { - List<Model> models = new ArrayList<>(); - models.add(model); - models.addAll(model.getSubmodels()); - - Map<MiriamType, Integer> annotations = new HashMap<>(); - for (MiriamType mt : MiriamType.values()) { - annotations.put(mt, 0); - } - for (Model model2 : models) { - for (Element alias : model2.getElements()) { - for (MiriamData md : alias.getMiriamData()) { - Integer amount = annotations.get(md.getDataType()); - amount += 1; - annotations.put(md.getDataType(), amount); - } - } - } - List<Pair<MiriamType, String>> list = new ArrayList<>(); - for (MiriamType mt : MiriamType.values()) { - list.add(new Pair<MiriamType, String>(mt, annotations.get(mt) + "")); - } - elementAvailableMiriam = new DualListModel<Pair<MiriamType, String>>(list, new ArrayList<>()); - - annotations = new HashMap<>(); - for (MiriamType mt : MiriamType.values()) { - annotations.put(mt, 0); - } - for (Model model2 : models) { - for (Reaction reaction : model2.getReactions()) { - for (MiriamData md : reaction.getMiriamData()) { - Integer amount = annotations.get(md.getDataType()); - amount += 1; - annotations.put(md.getDataType(), amount); - } - } - } - list = new ArrayList<>(); - for (MiriamType mt : MiriamType.values()) { - list.add(new Pair<MiriamType, String>(mt, annotations.get(mt) + "")); - } - networkAvailableMiriam = new DualListModel<Pair<MiriamType, String>>(list, new ArrayList<>()); - - } - - /** - * Method that exports elements. - * - * @throws IOException - * thrown when there are some problems with sending file - */ - public void downloadElements() throws IOException { - Model model = getCurrentTopModel(); - if (model == null) { - logger.warn("Unknown model. Skipping..."); - return; - } - - List<Class<?>> speciesList = new ArrayList<Class<?>>(); - for (String string : selectedSpeciesType) { - speciesList.add(getSpeciesTypeMap().get(string)); - } - - List<ExportColumn> speciesColumnList = new ArrayList<ExportColumn>(); - for (String string : selectedSpeciesColumn) { - speciesColumnList.add(speciesColumnMap.get(string)); - } - - ExporterParameters params = new ExporterParameters().model(model).// - included(elementIncludedComponent.getTarget()).// - excluded(elementExcludedComponent.getTarget()).// - column(speciesColumnList).// - fileType(ExportFileType.TAB_SEPARATED).// - type(speciesList); - - for (Pair<MiriamType, String> el : elementAvailableMiriam.getTarget()) { - params.miriamType(el.getLeft()); - } - - // create a string with the repsonse - String result = exporterService.getExportSpeciesString(params); - - // and send it as response - sendFileAsResponse(result, "elements.txt", MimeType.TEXT); - } - - /** - * Method that exports network. - * - * @throws IOException - * thrown when there are some problems with sending file - */ - public void downloadNetwork() throws IOException { - Model model = getCurrentTopModel(); - - if (model == null) { - logger.warn("Unknown model. Skipping..."); - return; - } - - List<Class<?>> nodeTypes = new ArrayList<Class<?>>(); - for (String string : selectedNetworkType) { - nodeTypes.add(getSpeciesTypeMap().get(string)); - } - - ExportFileType fileType = networkFileTypeMap.get(selectedNetworkFileType); - ExporterParameters params = new ExporterParameters().model(model).// - included(networkIncludedComponent.getTarget()).// - excluded(networkExcludedComponent.getTarget()).// - fileType(fileType).// - type(nodeTypes).// - column(ExportColumn.REACTION_ID).// - column(ExportColumn.REACTION_TYPE); - - for (Pair<MiriamType, String> el : networkAvailableMiriam.getTarget()) { - params.miriamType(el.getLeft()); - } - - // create a string with the repsonse - String result = exporterService.getExportInteractionString(params); - - sendFileAsResponse(result, "network.txt", MimeType.TEXT); - } - - /** - * Methods that export model into svg format. - * - * @throws IOException - * thrown when there are problems with intermediate file or the - * output - */ - public void downloadSvg() throws IOException { - if (selectedModelString == null) { - sendError("No model was selected"); - return; - } - - Model model = getCurrentTopModel().getSubmodelByName(selectedModelString); - if (selectedModelString.equals("null")) { - model = getCurrentTopModel(); - } - - if (model == null) { - sendError("Unknown model."); - return; - } - - // create svg file - Params params = new Params().height(model.getHeight()).width(model.getWidth()).model(model).sbgn(getCurrentTopModel().getProject().isSbgnFormat()); - try { - SvgImageGenerator sig = new SvgImageGenerator(params); - File file = File.createTempFile("map", ".svg"); - sig.saveToFile(file.getAbsolutePath()); - - sendFileAsResponse(file, "model.svg", MimeType.TEXT); - - // after finishing remove the file - file.delete(); - } catch (Exception e) { - logger.error(e, e); - sendError("Internal server error. More information can be found in logs."); - } - } - - /** - * Refresh list of submodel names. - * - * @param model - * model for which list will be generated - */ - private void fillSubmodelList(Model model) { - models.clear(); - models.add(model.getName()); - for (Model m : model.getSubmodels()) { - models.add(m.getName()); - } - setSelectedModelString(model.getName()); - } - - /** - * This method exports part of the model bounded by the polygon in - * CellDesigner or SBGN-ML format. - * - * @param sbgnmlFormat - * defines whether the model part is exported in CellDesigner or - * SBGN-ML format - * @throws IOException - * thrown when there are some problems with sending file - */ - public void downloadSelectedPart(boolean sbgnmlFormat) throws IOException { - Model part = getSelectedPartOfSubmodel(); - if (part == null) { - sendError("Unknown model."); - return; - } - - // export to CD format - try { - IConverter parser; - if (sbgnmlFormat) { - parser = new SbgnmlXmlConverter(); - } else { - parser = new CellDesignerXmlParser(); - } - InputStream is = parser.exportModelToInputStream(part); - StringWriter strWriter = new StringWriter(); - IOUtils.copy(is, strWriter); - String result = strWriter.toString(); - - String fileExtension = parser.getFileExtension(); - MimeType mimeType = parser.getMimeType(); - - sendFileAsResponse(result, "model.".concat(fileExtension), mimeType); - } catch (InconsistentModelException e) { - sendError(e.getMessage(), e); - } catch (ConverterException e) { - sendError("Internal server error.", e); - } - - } - - /** - * Returns part of the model that is currently selected on the client side. - * - * @return partial {@link Model} that is currently selected on the client side - */ - public Model getSelectedPartOfSubmodel() { - Model model = getCurrentTopModel().getSubmodelById(selectedModelId); - - if (model == null) { - return null; - } - - // transform polygon - CoordinationConverter cc = new CoordinationConverter(model); - Path2D polygon = cc.latLngToPolygon(selectedPolygon); - - // create model bounded by the polygon - SubModelCommand subModelCommand = new SubModelCommand(model, polygon); - Model part = subModelCommand.execute(); - return part; - } - - @Override - public void clear() { - throw new NotImplementedException(); - } - - /** - * @return the selectedSpeciesType - * @see #selectedSpeciesType - */ - public List<String> getSelectedSpeciesType() { - return selectedSpeciesType; - } - - /** - * @param selectedSpeciesType - * the selectedSpeciesType to set - * @see #selectedSpeciesType - */ - public void setSelectedSpeciesType(List<String> selectedSpeciesType) { - this.selectedSpeciesType = selectedSpeciesType; - } - - /** - * @return the selectedSpeciesColumn - * @see #selectedSpeciesColumn - */ - public List<String> getSelectedSpeciesColumn() { - return selectedSpeciesColumn; - } - - /** - * @param selectedSpeciesColumn - * the selectedSpeciesColumn to set - * @see #selectedSpeciesColumn - */ - public void setSelectedSpeciesColumn(List<String> selectedSpeciesColumn) { - this.selectedSpeciesColumn = selectedSpeciesColumn; - } - - /** - * @return the selectedNetworkType - * @see #selectedNetworkType - */ - public List<String> getSelectedNetworkType() { - return selectedNetworkType; - } - - /** - * @param selectedNetworkType - * the selectedNetworkType to set - * @see #selectedNetworkType - */ - public void setSelectedNetworkType(List<String> selectedNetworkType) { - this.selectedNetworkType = selectedNetworkType; - } - - /** - * @return the selectedNetworkFileType - * @see #selectedNetworkFileType - */ - public String getSelectedNetworkFileType() { - return selectedNetworkFileType; - } - - /** - * @param selectedNetworkFileType - * the selectedNetworkFileType to set - * @see #selectedNetworkFileType - */ - public void setSelectedNetworkFileType(String selectedNetworkFileType) { - this.selectedNetworkFileType = selectedNetworkFileType; - } - - /** - * @return the speciesTypeList - * @see #speciesTypeList - */ - public List<String> getSpeciesTypeList() { - if (speciesTypeList == null) { - speciesTypeList = new ArrayList<>(); - for (String string : getSpeciesTypeMap().keySet()) { - speciesTypeList.add(string); - } - } - return speciesTypeList; - } - - /** - * @param speciesTypeList - * the speciesTypeList to set - * @see #speciesTypeList - */ - public void setSpeciesTypeList(List<String> speciesTypeList) { - this.speciesTypeList = speciesTypeList; - } - - /** - * @return the speciesColumnList - * @see #speciesColumnList - */ - public List<String> getSpeciesColumnList() { - return speciesColumnList; - } - - /** - * @param speciesColumnList - * the speciesColumnList to set - * @see #speciesColumnList - */ - public void setSpeciesColumnList(List<String> speciesColumnList) { - this.speciesColumnList = speciesColumnList; - } - - /** - * @return the networkFileTypeList - * @see #networkFileTypeList - */ - public List<String> getNetworkFileTypeList() { - return networkFileTypeList; - } - - /** - * @param networkFileTypeList - * the networkFileTypeList to set - * @see #networkFileTypeList - */ - public void setNetworkFileTypeList(List<String> networkFileTypeList) { - this.networkFileTypeList = networkFileTypeList; - } - - /** - * @return the selectedPolygon - * @see #selectedPolygon - */ - public String getSelectedPolygon() { - return selectedPolygon; - } - - /** - * @param selectedPolygon - * the selectedPolygon to set - * @see #selectedPolygon - */ - public void setSelectedPolygon(String selectedPolygon) { - this.selectedPolygon = selectedPolygon; - } - - /** - * @return the exporter - * @see #exporterService - */ - public IExporterService getExporterService() { - return exporterService; - } - - /** - * @param exporter - * the exporter to set - * @see #exporterService - */ - public void setExporterService(IExporterService exporter) { - this.exporterService = exporter; - } - - /** - * Creates list of components available for client. - * - * @param model - * model used for components (compartments and pathways) generation - */ - private void computeComponentMap(Model model) { - if (model == null) { - logger.warn("Unknown model. Skipping..."); - return; - } - - Set<String> components = new HashSet<String>(); - for (Compartment alias : model.getCompartments()) { - components.add(alias.getName()); - } - for (ModelSubmodelConnection submodel : model.getSubmodelConnections()) { - for (Compartment alias : submodel.getSubmodel().getModel().getCompartments()) { - components.add(alias.getName()); - } - } - List<String> comp = new ArrayList<String>(); - comp.addAll(components); - Collections.sort(comp); - - networkIncludedComponent = new DualListModel<String>(comp, new ArrayList<String>()); - networkExcludedComponent = new DualListModel<String>(comp, new ArrayList<String>()); - elementIncludedComponent = new DualListModel<String>(comp, new ArrayList<String>()); - elementExcludedComponent = new DualListModel<String>(comp, new ArrayList<String>()); - } - - /** - * @return the selectedModelId - * @see #selectedModelId - */ - public String getSelectedModelId() { - return selectedModelId; - } - - /** - * @param selectedModelId - * the selectedModelId to set - * @see #selectedModelId - */ - public void setSelectedModelId(String selectedModelId) { - this.selectedModelId = selectedModelId; - } - - /** - * @return the selectedModelString - * @see #selectedModelString - */ - public String getSelectedModelString() { - return selectedModelString; - } - - /** - * @param selectedModelString - * the selectedModelString to set - * @see #selectedModelString - */ - public void setSelectedModelString(String selectedModelString) { - this.selectedModelString = selectedModelString; - } - - /** - * @return the models - * @see #models - */ - public List<String> getModels() { - if (models.size() == 0) { - Model model = getCurrentTopModel(); - computeComponentMap(model); - fillSubmodelList(model); - fillAnnotationNumbers(model); - } - return models; - } - - /** - * @param models - * the models to set - * @see #models - */ - public void setModels(List<String> models) { - this.models = models; - } - - /** - * @return the networkAvailableMiriam - * @see #networkAvailableMiriam - */ - public DualListModel<Pair<MiriamType, String>> getNetworkAvailableMiriam() { - return networkAvailableMiriam; - } - - /** - * @param networkAvailableMiriam - * the networkAvailableMiriam to set - * @see #networkAvailableMiriam - */ - public void setNetworkAvailableMiriam(DualListModel<Pair<MiriamType, String>> networkAvailableMiriam) { - this.networkAvailableMiriam = networkAvailableMiriam; - } - - /** - * @return the elementAvailableMiriam - * @see #elementAvailableMiriam - */ - public DualListModel<Pair<MiriamType, String>> getElementAvailableMiriam() { - return elementAvailableMiriam; - } - - /** - * @param elementAvailableMiriam - * the elementAvailableMiriam to set - * @see #elementAvailableMiriam - */ - public void setElementAvailableMiriam(DualListModel<Pair<MiriamType, String>> elementAvailableMiriam) { - this.elementAvailableMiriam = elementAvailableMiriam; - } - - /** - * @return the elementIncludedComponent - * @see #elementIncludedComponent - */ - public DualListModel<String> getElementIncludedComponent() { - return elementIncludedComponent; - } - - /** - * @param elementIncludedComponent - * the elementIncludedComponent to set - * @see #elementIncludedComponent - */ - public void setElementIncludedComponent(DualListModel<String> elementIncludedComponent) { - this.elementIncludedComponent = elementIncludedComponent; - } - - /** - * @return the elementExcludedComponent - * @see #elementExcludedComponent - */ - public DualListModel<String> getElementExcludedComponent() { - return elementExcludedComponent; - } - - /** - * @param elementExcludedComponent - * the elementExcludedComponent to set - * @see #elementExcludedComponent - */ - public void setElementExcludedComponent(DualListModel<String> elementExcludedComponent) { - this.elementExcludedComponent = elementExcludedComponent; - } - - /** - * @return the networkExcludedComponent - * @see #networkExcludedComponent - */ - public DualListModel<String> getNetworkExcludedComponent() { - return networkExcludedComponent; - } - - /** - * @param networkExcludedComponent - * the networkExcludedComponent to set - * @see #networkExcludedComponent - */ - public void setNetworkExcludedComponent(DualListModel<String> networkExcludedComponent) { - this.networkExcludedComponent = networkExcludedComponent; - } - - /** - * @return the networkIncludedComponent - * @see #networkIncludedComponent - */ - public DualListModel<String> getNetworkIncludedComponent() { - return networkIncludedComponent; - } - - /** - * @param networkIncludedComponent - * the networkIncludedComponent to set - * @see #networkIncludedComponent - */ - public void setNetworkIncludedComponent(DualListModel<String> networkIncludedComponent) { - this.networkIncludedComponent = networkIncludedComponent; - } - - @Override - public void init() { - - PropertyChangeListener modelPropertyChangeListener = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (MapBean.CURRENT_MODEL_PROPERTY.equals(arg0.getPropertyName())) { - computeComponentMap((Model) arg0.getNewValue()); - fillSubmodelList((Model) arg0.getNewValue()); - fillAnnotationNumbers((Model) arg0.getNewValue()); - } - } - - }; - mapBean.addPropertyChangeListener(modelPropertyChangeListener); - - for (ExportColumn type : ExportColumn.values()) { - if (type.getClazz().isAssignableFrom(Species.class)) { - speciesColumnMap.put(type.getTitle(), type); - speciesColumnList.add(type.getTitle()); - } - } - - selectedNetworkFileType = ExportFileType.TAB_SEPARATED.getTitle(); - networkFileTypeMap.put(ExportFileType.TAB_SEPARATED.getTitle(), ExportFileType.TAB_SEPARATED); - networkFileTypeList.add(ExportFileType.TAB_SEPARATED.getTitle()); - - imageGenerator = new ImageGenerators(); - imageGenerators = imageGenerator.getAvailableImageGenerators(); - - imageExportMenu = createImageSelectMenu(); - - contextMenu = createContextMenu(); - - // trigger event handler manually to initialize the data - modelPropertyChangeListener - .propertyChange(new PropertyChangeEvent(this, MapBean.CURRENT_MODEL_PROPERTY, mapBean.getCurrentTopModel(), mapBean.getCurrentTopModel())); - } - - /** - * Creates context menu that is active when clicking on some selected region - * on the map. - * - * @return context menu that is active when clicking on some selected region - * on the map - */ - public MenuModel createImageSelectMenu() { - MenuModel result = new DefaultMenuModel(); - - DefaultMenuItem item = new DefaultMenuItem("Remove selection"); - item.setOnclick("customMap.removeSelection(); customMap.turnOnOffDrawing();"); - item.setStyleClass("addCommentContext"); - item.setAjax(false); - item.setUrl("#"); - result.addElement(item); - - DefaultSubMenu exportModelSubmenu = new DefaultSubMenu("Export as model"); - - item = new DefaultMenuItem("CellDesigner"); - item.setCommand("#{exportMB.downloadSelectedPart(false)}"); - item.setAjax(false); - item.setStyleClass("addCommentContext"); - exportModelSubmenu.addElement(item); - - item = new DefaultMenuItem("SBGN-ML"); - item.setCommand("#{exportMB.downloadSelectedPart(true)}"); - item.setAjax(false); - item.setStyleClass("addCommentContext"); - exportModelSubmenu.addElement(item); - result.addElement(exportModelSubmenu); - - DefaultSubMenu exportImageSubmenu = new DefaultSubMenu("Export as image"); - for (Pair<String, Class<? extends AbstractImageGenerator>> element : imageGenerators) { - item = new DefaultMenuItem(element.getLeft()); - item.setCommand("#{exportMB.downloadImage(\"" + element.getRight().getCanonicalName() + "\")}"); - item.setAjax(false); - item.setStyleClass("addCommentContext"); - exportImageSubmenu.addElement(item); - } - result.addElement(exportImageSubmenu); - - return result; - } - - /** - * Creates context menu that is active when clicking on any place in the map - * (except of some selected region). - * - * @return context menu that is active when clicking on any place in the map - * (except of some selected region). - */ - public MenuModel createContextMenu() { - MenuModel result = new DefaultMenuModel(); - - DefaultMenuItem addCommentItem = new DefaultMenuItem("Add comment"); - addCommentItem.setOncomplete("jsfCommentDialog.show();customMap.openCommentDialog();"); - addCommentItem.setStyleClass("addCommentContext"); - addCommentItem.setCommand("#{exportMB.nop()}"); - addCommentItem.setAjax(true); - addCommentItem.setId("commentButton"); - result.addElement(addCommentItem); - - DefaultMenuItem item = new DefaultMenuItem("Select mode"); - item.setId("selectModeButton"); - item.setUrl("#"); - item.setOnclick("customMap.turnOnOffDrawing();"); - item.setAjax(false); - item.setStyleClass("addCommentContext"); - result.addElement(item); - - DefaultSubMenu exportModelSubmenu = new DefaultSubMenu("Export as model"); - - item = new DefaultMenuItem("CellDesigner"); - item.setCommand("#{exportMB.downloadSelectedPart(false)}"); - item.setAjax(false); - item.setStyleClass("addCommentContext"); - exportModelSubmenu.addElement(item); - - item = new DefaultMenuItem("SBGN-ML"); - item.setCommand("#{exportMB.downloadSelectedPart(true)}"); - item.setAjax(false); - item.setStyleClass("addCommentContext"); - exportModelSubmenu.addElement(item); - result.addElement(exportModelSubmenu); - - DefaultSubMenu exportImageSubmenu = new DefaultSubMenu("Export as image"); - for (Pair<String, Class<? extends AbstractImageGenerator>> element : imageGenerators) { - item = new DefaultMenuItem(element.getLeft()); - item.setCommand("#{exportMB.downloadImage(\"" + element.getRight().getCanonicalName() + "\")}"); - item.setAjax(false); - item.setStyleClass("addCommentContext"); - exportImageSubmenu.addElement(item); - } - result.addElement(exportImageSubmenu); - - return result; - } - - /** - * @return the imageGenerators - * @see #imageGenerators - */ - public List<Pair<String, Class<? extends AbstractImageGenerator>>> getImageGenerators() { - return imageGenerators; - } - - /** - * @param imageGenerators - * the imageGenerators to set - * @see #imageGenerators - */ - public void setImageGenerators(List<Pair<String, Class<? extends AbstractImageGenerator>>> imageGenerators) { - this.imageGenerators = imageGenerators; - } - - /** - * @return the imageExportMenu - * @see #imageExportMenu - */ - public MenuModel getImageExportMenu() { - return imageExportMenu; - } - - /** - * @param imageExportMenu - * the imageExportMenu to set - * @see #imageExportMenu - */ - public void setImageExportMenu(MenuModel imageExportMenu) { - this.imageExportMenu = imageExportMenu; - } - - /** - * @return the speciesTypeMap - * @see #speciesTypeMap - */ - protected Map<String, Class<?>> getSpeciesTypeMap() { - if (speciesTypeMap == null) { - speciesTypeMap = new LinkedHashMap<>(); - speciesTypeMap.put("Antisense RNA", AntisenseRna.class); - speciesTypeMap.put("Complex", Complex.class); - speciesTypeMap.put("Degraded", Degraded.class); - speciesTypeMap.put("Drug", Drug.class); - speciesTypeMap.put("Gene", Gene.class); - speciesTypeMap.put("Ion", Ion.class); - speciesTypeMap.put("Phenotype", Phenotype.class); - speciesTypeMap.put("Protein", Protein.class); - speciesTypeMap.put("RNA", Rna.class); - speciesTypeMap.put("Molecule", SimpleMolecule.class); - speciesTypeMap.put("Unknown", Unknown.class); - speciesTypeMap.put("All", Species.class); - } - return speciesTypeMap; - } - - /** - * @param speciesTypeMap - * the speciesTypeMap to set - * @see #speciesTypeMap - */ - protected void setSpeciesTypeMap(Map<String, Class<?>> speciesTypeMap) { - this.speciesTypeMap = speciesTypeMap; - } - - /** - * @return the speciesColumnMap - * @see #speciesColumnMap - */ - protected Map<String, ExportColumn> getSpeciesColumnMap() { - return speciesColumnMap; - } - - /** - * @param speciesColumnMap - * the speciesColumnMap to set - * @see #speciesColumnMap - */ - protected void setSpeciesColumnMap(Map<String, ExportColumn> speciesColumnMap) { - this.speciesColumnMap = speciesColumnMap; - } - - /** - * @return the networkFileTypeMap - * @see #networkFileTypeMap - */ - protected Map<String, ExportFileType> getNetworkFileTypeMap() { - return networkFileTypeMap; - } - - /** - * @param networkFileTypeMap - * the networkFileTypeMap to set - * @see #networkFileTypeMap - */ - protected void setNetworkFileTypeMap(Map<String, ExportFileType> networkFileTypeMap) { - this.networkFileTypeMap = networkFileTypeMap; - } - - /** - * Downloads image that will be created by {@link AbstractImageGenerator} - * implementation for which class name is given in the parameter. - * - * @param generatorClass - * class name of {@link AbstractImageGenerator} to be used - */ - public void downloadImage(String generatorClass) { - try { - Model originalModel = getCurrentTopModel().getSubmodelById(selectedModelId); - ClientMapData clientData = mapBean.getMapDataByMapIdentifier(selectedModelId); - - if (originalModel == null) { - sendError("Unknown model"); - return; - } - - Layout layout = getCurrentTopModel().getLayoutByIdentifier(mapBean.getSelectedLayoutIdentifier()); - if (layout == null) { - sendError("Unknown layout in model. Layout.id=" + mapBean.getSelectedLayoutIdentifier()); - return; - } - - Model colorModel = new CopyCommand(originalModel).execute(); - if (layout.getInputData() != null) { - ColorSchemaReader reader = new ColorSchemaReader(); - Collection<ColorSchema> schemas = reader.readColorSchema(layout.getInputData().getFileContent()); - - new ColorModelCommand(colorModel, schemas, userService.getColorExtractorForUser(userBean.getLoggedUser())).execute(); - } else if (layout.getTitle().equals(BuildInLayout.CLEAN.getTitle())) { - // this might not return true if we change CLEAN.title in future... - - // if it's clean then remove coloring - new ClearColorModelCommand(colorModel).execute(); - } - for (Element alias : colorModel.getElements()) { - alias.setVisibilityLevel(0); - } - - Integer level = Configuration.MIN_ZOOM_LEVEL; - try { - level = Integer.valueOf(clientData.getZoomLevel()); - } catch (NumberFormatException e) { - logger.error("Problem with getting zoom level", e); - } - - // transform polygon - CoordinationConverter cc = new CoordinationConverter(colorModel); - Path2D polygon = cc.latLngToPolygon(selectedPolygon); - - Double minX = originalModel.getWidth(); - Double minY = originalModel.getHeight(); - Double maxX = 0.0; - Double maxY = 0.0; - PathIterator pathIter = polygon.getPathIterator(null); - while (!pathIter.isDone()) { - final double[] segment = new double[PATH_ITERATOR_SEGMENT_SIZE]; - if (pathIter.currentSegment(segment) != PathIterator.SEG_CLOSE) { - minX = Math.min(minX, segment[0]); - maxX = Math.max(maxX, segment[0]); - minY = Math.min(minY, segment[1]); - maxY = Math.max(maxY, segment[1]); - } - pathIter.next(); - } - Double scale = Math.max(originalModel.getHeight(), originalModel.getWidth()) / (originalModel.getTileSize()); - - for (int i = level; i > Configuration.MIN_ZOOM_LEVEL; i--) { - scale /= 2; - } - - ColorExtractor colorExtractor = userService.getColorExtractorForUser(userBean.getLoggedUser()); - - Params params = new Params().// - x(minX).// - y(minY).// - height((maxY - minY) / scale).// - width((maxX - minX) / scale).// - level(level).// - nested(false).// automatically set nested view as invalid - scale(scale).// - minColor(colorExtractor.getMinColor()).// - maxColor(colorExtractor.getMaxColor()).// - sbgn(getCurrentTopModel().getProject().isSbgnFormat()).// - model(colorModel); - List<Integer> visibleLayoutIds = deserializeIdList(visibleLayouts); - for (Integer integer : visibleLayoutIds) { - Map<Object, ColorSchema> map = getLayoutService().getElementsForLayout(colorModel, integer, userBean.getAuthenticationToken()); - params.addVisibleLayout(map); - } - - String extension = imageGenerator.getExtension(generatorClass); - File file = File.createTempFile("map", "." + extension); - - MimeType type = imageGenerator.generate(generatorClass, params, file.getAbsolutePath()); - sendFileAsResponse(file, "model." + extension, type); - - // after finishing remove the file - file.delete(); - } catch (Exception e) { - sendError("Internal server error", e); - } - - } - - /** - * @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 pubmedModelSummary - * @see #pubmedModelSummary - */ - public List<PubmedAnnotatedElementsView> getPubmedModelSummary() { - if (pubmedModelSummary == null) { - pubmedModelSummary = exporterService.getPublicationModelSummary(getCurrentTopModel()); - } - return pubmedModelSummary; - } - - /** - * @param pubmedModelSummary - * the pubmedModelSummary to set - * @see #pubmedModelSummary - */ - public void setPubmedModelSummary(List<PubmedAnnotatedElementsView> pubmedModelSummary) { - this.pubmedModelSummary = pubmedModelSummary; - } - - /** - * @return the visibleLayouts - * @see #visibleLayouts - */ - public String getVisibleLayouts() { - return visibleLayouts; - } - - /** - * @param visibleLayouts - * the visibleLayouts to set - * @see #visibleLayouts - */ - public void setVisibleLayouts(String visibleLayouts) { - this.visibleLayouts = visibleLayouts; - } - - /** - * Deserialize list of integer identifiers encoded as an json array. Example - * input string for two identifiers (123, 44) looks like: - * - * <pre> - * "["123","44"]" - * </pre> - * - * @param jsonString - * list of identifiers as a json string array - * @return list of integer identifiers - */ - protected List<Integer> deserializeIdList(String jsonString) { - return new Gson().fromJson(jsonString, new TypeToken<List<Integer>>() { - }.getType()); - } - - /** - * @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; - } - - /** - * Returns currently browsed map. - * - * @return currently browsed map - */ - private Model getCurrentTopModel() { - return mapBean.getCurrentTopModel(); - } - - /** - * @return the contextMenu - * @see #contextMenu - */ - public MenuModel getContextMenu() { - return contextMenu; - } - - /** - * @param contextMenu - * the contextMenu to set - * @see #contextMenu - */ - public void setContextMenu(MenuModel contextMenu) { - this.contextMenu = contextMenu; - } - - /** - * Method that does nothing (workaround for menu buttons). - */ - public void nop() { - } - - /** - * @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; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/FeedbackBean.java b/web/src/main/java/lcsb/mapviewer/bean/FeedbackBean.java deleted file mode 100644 index 6aaba2b3815fa466a1fb8f8b45306f91f5530307..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/FeedbackBean.java +++ /dev/null @@ -1,300 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.event.ActionEvent; - -import org.apache.log4j.Logger; - -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.interfaces.ICommentService; -import lcsb.mapviewer.services.interfaces.ISearchService; -import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.view.CommentView; - -/** - * Bean used for managing comments. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "feedbackMB") -@ViewScoped -public class FeedbackBean extends AbstractManagedBean implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(FeedbackBean.class); - - /** - * List of comments available for current project. - */ - private List<CommentView> commentList = null; - - /** - * 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; - - /** - * Service that manages comments. - */ - @ManagedProperty(value = "#{CommentService}") - private transient ICommentService commentService; - - /** - * Service that allows to query the database to find elements in the model. - */ - @ManagedProperty(value = "#{SearchService}") - private transient ISearchService searchService; - - /** - * Service used to access information about users. - * - * @see IUserService - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * Method called to remove comment from the map. - * - * @param actionEvent - * event from thefrom the client - */ - public void removeComment(final ActionEvent actionEvent) { - try { - logger.debug("Remove comment"); - if (getUserHasCommentPrivilege()) { - String commentId = getRequestParameter("missingConnectionForm:commentId"); - String reason = getRequestParameter("missingConnectionForm:removeCommentContent"); - commentService.deleteComment(userBean.getLoggedUser(), commentId, reason); - } else { - logger.error("Somebody try to hack the system: " + userBean.getLogin(), new Exception()); - } - } catch (InvalidArgumentException e) { - logger.error(e.getMessage(), e); - } - refreshCommentList(); - } - - - /** - * Method called to remove comment from the map. - * - * @param comment - * comment to be removed - */ - public void removeComment(CommentView comment) { - try { - logger.debug("Remove comment"); - if (getUserHasCommentPrivilege()) { - String commentId = comment.getIdObject() + ""; - commentService.deleteComment(userBean.getLoggedUser(), commentId, ""); - } else { - sendError("You don't have privilege to remove comment"); - } - } catch (InvalidArgumentException e) { - sendError("Internal server error", e); - } - refreshCommentList(); - } - - /** - * Returns true if user can manage current comments. - * - * @return <code>true</code> if user has privilege to manage the comments, - * <code>false</code> otherwise - */ - public boolean getUserHasCommentPrivilege() { - Project project = getCurrentProject(); - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.EDIT_COMMENTS_PROJECT, project); - return result; - } - - /** - * This method refresh the list of comments for the current model and put it. - * on the list - */ - public void refreshCommentList() { - try { - if (getCurrentTopModel() == null) { - logger.warn("Unknown map"); - return; - } - if (!getUserHasCommentPrivilege()) { - commentList = new ArrayList<>(); - logger.warn("User has not privilages"); - return; - } else { - commentList = commentService.getCommentsByMap(getCurrentTopModel(), userBean.getAuthenticationToken()); - } - } catch (Exception e) { - sendError("Internal server error. More info in logs.", e); - } - } - - @Override - public void clear() { - setCommentList(new ArrayList<>()); - } - - /** - * @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 commentService - * @see #commentService - */ - public ICommentService getCommentService() { - return commentService; - } - - /** - * @param commentService - * the commentService to set - * @see #commentService - */ - public void setCommentService(ICommentService commentService) { - this.commentService = commentService; - } - - /** - * @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; - } - - /** - * @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 commentList - * @see #commentList - */ - public List<CommentView> getCommentList() { - if (commentList == null) { - refreshCommentList(); - } - return commentList; - } - - /** - * @param commentList - * the commentList to set - * @see #commentList - */ - public void setCommentList(List<CommentView> commentList) { - this.commentList = commentList; - } - - /** - * Returns currently browsed map. - * - * @return currently browsed map - */ - private Model getCurrentTopModel() { - return mapBean.getCurrentTopModel(); - } - - /** - * Returns identifier of browsed map (if such map wasn't setup it will be - * default identifier). - * - * @return identifier of browsed map - */ - private Project getCurrentProject() { - return getCurrentTopModel().getProject(); - } - - /** - * @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; - } - - @Override - public void init() { - clear(); - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/GalaxyBean.java b/web/src/main/java/lcsb/mapviewer/bean/GalaxyBean.java deleted file mode 100644 index b3b6c2e1f3907eacc517e577959233942f258be6..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/GalaxyBean.java +++ /dev/null @@ -1,221 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.Serializable; -import java.nio.charset.StandardCharsets; -import java.util.Map; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.RequestScoped; -import javax.faces.context.FacesContext; - -import org.apache.log4j.Logger; - -import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.user.User; -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; - -/** - * Bean used for galaxy connector. - * - * @author Piotr Gawron - * - */ -@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() { - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java b/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java deleted file mode 100644 index 2c866c388497b506597d22ffce6ceeb5519128c1..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java +++ /dev/null @@ -1,811 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.List; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.event.ActionEvent; - -import org.apache.commons.io.FilenameUtils; -import org.apache.log4j.Logger; -import org.primefaces.event.FileUploadEvent; -import org.primefaces.model.UploadedFile; - -import lcsb.mapviewer.common.MimeType; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.converter.zip.LayoutZipEntryFile; -import lcsb.mapviewer.converter.zip.ZipEntryFileFactory; -import lcsb.mapviewer.events.Listener; -import lcsb.mapviewer.events.ObjectAddedEvent; -import lcsb.mapviewer.events.ObjectRemovedEvent; -import lcsb.mapviewer.model.map.layout.InvalidColorSchemaException; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.SecurityException; -import lcsb.mapviewer.services.interfaces.ILayoutService; -import lcsb.mapviewer.services.interfaces.ILayoutService.CreateLayoutParams; -import lcsb.mapviewer.services.interfaces.IModelService; -import lcsb.mapviewer.services.search.layout.FullLayoutAliasView; -import lcsb.mapviewer.services.search.layout.FullLayoutAliasViewFactory; -import lcsb.mapviewer.services.search.layout.LightLayoutAliasView; -import lcsb.mapviewer.services.search.layout.LightLayoutAliasViewFactory; -import lcsb.mapviewer.services.search.layout.LightLayoutReactionView; -import lcsb.mapviewer.services.search.layout.LightLayoutReactionViewFactory; -import lcsb.mapviewer.services.utils.data.ColorSchemaType; -import lcsb.mapviewer.services.view.LayoutView; -import lcsb.mapviewer.services.view.ProjectView; - -/** - * Bean used to managing different layouts on current map. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "layoutMB") -@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(); - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/MapBean.java b/web/src/main/java/lcsb/mapviewer/bean/MapBean.java deleted file mode 100644 index d8c6f2d8d8ebf90c7f09148860a4c804f208f192..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/MapBean.java +++ /dev/null @@ -1,1023 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.awt.geom.Point2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.component.UIComponent; -import javax.faces.event.ActionEvent; - -import org.apache.log4j.Logger; -import org.primefaces.component.dialog.Dialog; -import org.primefaces.context.RequestContext; -import org.primefaces.model.map.LatLng; - -import com.google.gson.Gson; - -import lcsb.mapviewer.annotation.services.TaxonomyBackend; -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.model.Model; -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.interfaces.IConfigurationService; -import lcsb.mapviewer.services.interfaces.IModelService; -import lcsb.mapviewer.services.interfaces.IProjectService; -import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.search.data.FullAliasView; -import lcsb.mapviewer.services.search.data.FullAliasViewFactory; -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.search.data.LightReactionViewFactory; -import lcsb.mapviewer.services.utils.gmap.CoordinationConverter; -import lcsb.mapviewer.services.view.ModelView; -import lcsb.mapviewer.services.view.ProjectView; - -/** - * This bean is responsible for providing general data about current map and - * receiving general information from client javascript. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "mapMB") -@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; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/MiriamBean.java b/web/src/main/java/lcsb/mapviewer/bean/MiriamBean.java deleted file mode 100644 index 40783c58b4eb7a81fb7289d3c1e982b239550146..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/MiriamBean.java +++ /dev/null @@ -1,284 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; - -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamRelationType; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.services.interfaces.IMiriamService; - -import org.apache.log4j.Logger; - -/** - * Bean used to redirect client to proper external site from miriam data uri. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "miriamMB") -@ViewScoped -public class MiriamBean extends AbstractManagedBean implements Serializable { - - /** - * String representing {@link #type} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String TYPE_PROPERTY = "TYPE"; - - /** - * String representing {@link #resource} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String RESOURCE_PROPERTY = "RESOURCE"; - - /** - * String representing {@link #linkDescription} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String LINK_DESCRIPTION_PROPERTY = "LINK_DESCRIPTION"; - - /** - * String representing {@link #redirectLink} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String REDIRECTION_LINK_PROPERTY = "REDIRECTION_LINK"; - - /** - * String representing {@link #message} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String MESSAGE_PROPERTY = "MESSAGE"; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(MiriamBean.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Type of the resource. - */ - private String type = ""; - - /** - * Resource identrifier. - */ - private String resource = ""; - - /** - * Link where user should be redirected. - */ - private String redirectLink = null; - - /** - * Description of the link. - */ - private String linkDescription = ""; - - /** - * Message to the client (OK/ERROR). - */ - private String message = ""; - - /** - * Service accessing <a href= "http://www.ebi.ac.uk/miriam/main/" >miriam - * registry</a>. - */ - @ManagedProperty(value = "#{MiriamService}") - private transient IMiriamService miriamService; - - /** - * List of all supported miriamTypes. - */ - private List<MiriamType> miriamTypes = new ArrayList<MiriamType>(); - - @Override - public void init() { - // when type or resource id changes we have to update redirect link - PropertyChangeListener selectedModelChanged = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (TYPE_PROPERTY.equals(arg0.getPropertyName()) || RESOURCE_PROPERTY.equals(arg0.getPropertyName())) { - if (type != null && resource != null) { - try { - MiriamData md = new MiriamData(MiriamRelationType.BQ_BIOL_IS_DESCRIBED_BY, miriamService.getTypeForUri(type), resource); - setRedirectLink(miriamService.getUrlForMiriamData(md)); - if (redirectLink == null || redirectLink.trim().equals("")) { - setMessage("Invalid miriam data: " + type + ":" + resource); - setLinkDescription(""); - } else { - setMessage("You should be redirected in 5 seconds. If the page does not reload you can use direct "); - setLinkDescription("link"); - } - } catch (Exception e) { - logger.error(e.getMessage(), e); - setRedirectLink(null); - setLinkDescription(""); - setMessage("Internal server error"); - } - } else { - setRedirectLink(null); - setLinkDescription(""); - setMessage("Invalid miriam data: " + type + ":" + resource); - } - } - } - }; - addPropertyChangeListener(selectedModelChanged); - - for (MiriamType type : MiriamType.values()) { - miriamTypes.add(type); - } - } - - /** - * - * @return {@link #linkDescription} - */ - public String getLinkDescription() { - return linkDescription; - } - - /** - * Sets {@link #linkDescription}. Property change listeners will be thrown - * after value change. - * - * @param linkDescription - * new {@link #linkDescription} - */ - public void setLinkDescription(final String linkDescription) { - String oldValue = this.linkDescription; - this.linkDescription = linkDescription; - firePropertyChange(LINK_DESCRIPTION_PROPERTY, oldValue, linkDescription); - } - - /** - * - * @return {@link #type} - */ - public String getType() { - return type; - } - - /** - * Sets {@link #type}. Property change listeners will be thrown after value - * change. - * - * @param type - * new {@link #type} - */ - public void setType(final String type) { - String oldValue = this.type; - this.type = type; - firePropertyChange(TYPE_PROPERTY, oldValue, type); - } - - /** - * - * @return {@link #resource} - */ - public String getResource() { - return resource; - } - - /** - * Sets {@link #resource}. Property change listeners will be thrown after - * value change. - * - * @param resource - * new {@link #resource} - */ - public void setResource(final String resource) { - String oldValue = this.resource; - this.resource = resource; - firePropertyChange(RESOURCE_PROPERTY, oldValue, resource); - } - - /** - * - * @return {@link #message} - */ - public String getMessage() { - return message; - } - - /** - * Sets {@link #message}. Property change listeners will be thrown after value - * change. - * - * @param message - * new {@link #message} - */ - public void setMessage(final String message) { - String oldValue = this.message; - this.message = message; - firePropertyChange(MESSAGE_PROPERTY, oldValue, message); - } - - /** - * - * @return {@link #redirectLink} - */ - public String getRedirectLink() { - return redirectLink; - } - - /** - * Sets {@link #redirectLink}. Property change listeners will be thrown after - * value change. - * - * @param redirectLink - * new {@link #redirectLink} - */ - public void setRedirectLink(final String redirectLink) { - String oldValue = this.redirectLink; - this.redirectLink = redirectLink; - firePropertyChange(REDIRECTION_LINK_PROPERTY, oldValue, redirectLink); - } - - @Override - public void clear() { - setType(""); - setResource(""); - setRedirectLink(null); - setLinkDescription(""); - setMessage(""); - } - - /** - * @return the miriamService - * @see #miriamService - */ - public IMiriamService getMiriamService() { - return miriamService; - } - - /** - * @param miriamService - * the miriamService to set - * @see #miriamService - */ - public void setMiriamService(IMiriamService miriamService) { - this.miriamService = miriamService; - } - - /** - * @return the miriamTypes - * @see #miriamTypes - */ - public List<MiriamType> getMiriamTypes() { - return miriamTypes; - } -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/MissingConnectionBean.java b/web/src/main/java/lcsb/mapviewer/bean/MissingConnectionBean.java deleted file mode 100644 index 482e9cf4606a4d9427cf763446bf5d534195d71d..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/MissingConnectionBean.java +++ /dev/null @@ -1,228 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.IOException; -import java.io.Serializable; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.event.ActionEvent; - -import org.apache.log4j.Logger; - -import lcsb.mapviewer.common.MimeType; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.map.graph.DataMiningType; -import lcsb.mapviewer.services.interfaces.IDataMiningService; -import lcsb.mapviewer.services.search.ElementIdentifierDetails; -import lcsb.mapviewer.services.search.ISearchResultView; -import lcsb.mapviewer.services.search.data.ElementIdentifier; -import lcsb.mapviewer.services.view.DataMiningSetView; - -/** - * This bean is responsible for providing information about suggested - * connections between nodes (for now genes only) that doesn't exist on the map. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "missingConnectionMB") -@ViewScoped -public class MissingConnectionBean extends AbstractMarkerManagerBean<ISearchResultView> implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(MissingConnectionBean.class); - - /** - * Gene name for which we want to find suggested connections. - */ - private String geneName = ""; - - /** - * List of all {@link DataMiningType}. - */ - private List<DataMiningType> dataMiningTypes = new ArrayList<DataMiningType>(); - - /** - * Bean used for communication with the client side about the map currently - * visualized. - * - * @see MapBean - */ - @ManagedProperty(value = "#{mapMB}") - private transient MapBean mapBean; - - /** - * Service that manages data mining information. - */ - @ManagedProperty(value = "#{DataMiningService}") - private transient IDataMiningService dataMiningService; - - /** - * This method is looking for suggested connections for the specified gene. - * name - * - * @param actionEvent - * event from thefrom the client - */ - public void search(final ActionEvent actionEvent) { - logger.error("Not Implemented"); - // if (getCurrentTopModel() == null) { - // logger.warn("Unknown model. Skipping..."); - // return; - // } - // - // clearResults(); - // // find species that probably shoud be connected with the geneName - // Collection<Element> connections = - // dataMiningService.getSpeciesWithMissingConnectionsByGeneName(getCurrentTopModel(), - // geneName); - // - // List<SpeciesAlias> aliases = new ArrayList<SpeciesAlias>(); - // for (Element element : connections) { - // if (element instanceof Species) { - // Species species = (Species) element; - // - // List<SpeciesAlias> tmp = - // getCurrentTopModel().getAliasesBySpeciesId(species.getIdSpecies()); - // aliases.addAll(tmp); - // - // } else { - // logger.warn("Unknown class type: " + element.getClass()); - // } - // ConverterParams params = mapBean.getOverlayConverter().new - // ConverterParams() - // .model(getCurrentTopModel()).icon(IconManager.getInstance().getEmpyIcon()).border(true).addObjects(aliases); - // addResults(mapBean.getOverlayConverter().objectsToSearchResults(params)); - // } - // // and send it to the client - // refreshOverlayCollection(); - } - - @Override - public void clear() { - setGeneName(""); - clearResults(); - refreshDataInJavascript(); - } - - /** - * @return the geneName - * @see #geneName - */ - public String getGeneName() { - return geneName; - } - - /** - * @param geneName - * the geneName to set - * @see #geneName - */ - public void setGeneName(String geneName) { - this.geneName = geneName; - } - - /** - * @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 dataMiningService - * @see #dataMiningService - */ - public IDataMiningService getDataMiningService() { - return dataMiningService; - } - - /** - * @param dataMiningService - * the dataMiningService to set - * @see #dataMiningService - */ - public void setDataMiningService(IDataMiningService dataMiningService) { - this.dataMiningService = dataMiningService; - } - - @Override - public void init() { - for (DataMiningType type : DataMiningType.values()) { - dataMiningTypes.add(type); - } - } - - /** - * @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; - } - - /** - * Method that allows to donlwoad input data for given data mining set. - * - * @param dms - * data minig set for which input data will be downloaded - * - * @throws IOException - * thrown when there are some problems with sending file - */ - public void downloadInputData(DataMiningSetView dms) throws IOException { - // get input data from database - byte[] data = dataMiningService.getInputDataForLayout(dms); - String string = new String(data, StandardCharsets.UTF_8); - - sendFileAsResponse(string, "data_mining_" + dms.getIdObject() + ".txt", MimeType.TEXT); - } - - @Override - protected List<ElementIdentifier> getLightElementsForSearchResult(ISearchResultView result) { - logger.error("Not implemented"); - return new ArrayList<>(); - } - - @Override - protected ElementIdentifierDetails getElementInformationForResult(ElementIdentifier element, ISearchResultView result) { - throw new NotImplementedException(); - } - - @Override - protected List<Pair<String, ElementIdentifierDetails>> getElementInformationForResult(ElementIdentifier element) { - throw new NotImplementedException(); - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/ProjectBean.java b/web/src/main/java/lcsb/mapviewer/bean/ProjectBean.java deleted file mode 100644 index 2dc3e22ad04d8d13be320d3621936042a2e1fa8f..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/ProjectBean.java +++ /dev/null @@ -1,1509 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.event.ActionEvent; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.log4j.Logger; -import org.primefaces.event.FileUploadEvent; -import org.primefaces.event.TransferEvent; -import org.primefaces.model.DualListModel; -import org.primefaces.model.TreeNode; -import org.primefaces.model.UploadedFile; - -import lcsb.mapviewer.common.MimeType; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.converter.zip.DataMiningZipEntryFile; -import lcsb.mapviewer.converter.zip.ImageZipEntryFile; -import lcsb.mapviewer.converter.zip.InputFileType; -import lcsb.mapviewer.converter.zip.LayoutZipEntryFile; -import lcsb.mapviewer.converter.zip.ModelZipEntryFile; -import lcsb.mapviewer.converter.zip.ZipEntryFile; -import lcsb.mapviewer.converter.zip.ZipEntryFileFactory; -import lcsb.mapviewer.events.Listener; -import lcsb.mapviewer.events.ObjectAddedEvent; -import lcsb.mapviewer.events.ObjectModifiedEvent; -import lcsb.mapviewer.events.ObjectRemovedEvent; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.graph.DataMiningType; -import lcsb.mapviewer.model.map.model.SubmodelType; -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.UserAccessException; -import lcsb.mapviewer.services.interfaces.IConfigurationService; -import lcsb.mapviewer.services.interfaces.IModelService; -import lcsb.mapviewer.services.interfaces.IProjectService; -import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.overlay.AnnotatedObjectTreeRow; -import lcsb.mapviewer.services.utils.CreateProjectParams; -import lcsb.mapviewer.services.view.LayoutView; -import lcsb.mapviewer.services.view.ProjectView; - -/** - * This bean is responsible for managing projects. It allows to - * create/modify/remove project. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "projectMB") -@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; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/ReferenceGenomeBean.java b/web/src/main/java/lcsb/mapviewer/bean/ReferenceGenomeBean.java deleted file mode 100644 index ded4cc6c881eaee65e2f36590eb0218c5dd75ed9..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/ReferenceGenomeBean.java +++ /dev/null @@ -1,738 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.io.IOException; -import java.io.Serializable; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.event.ActionEvent; - -import org.apache.log4j.Logger; - -import com.google.gson.Gson; - -import lcsb.mapviewer.annotation.services.TaxonomyBackend; -import lcsb.mapviewer.annotation.services.TaxonomySearchException; -import lcsb.mapviewer.annotation.services.genome.ReferenceGenomeConnectorException; -import lcsb.mapviewer.model.map.MiriamData; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.layout.ReferenceGenome; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeGeneMapping; -import lcsb.mapviewer.model.map.layout.ReferenceGenomeType; -import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.interfaces.IReferenceGenomeService; -import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.utils.ReferenceGenomeExistsException; -import lcsb.mapviewer.services.view.ReferenceGenomeView; - -/** - * This bean is responsible for managing reference genome and related data. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "referenceGenomeMB") -@ViewScoped -public class ReferenceGenomeBean extends AbstractManagedBean implements Serializable { - - /** - * String representing {@link #selectedReferenceGenomeType} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String REFERENCE_GENOME_TYPE_PROPERTY = "TYPE"; - - /** - * String representing {@link #selectedOrganism} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - public static final String SELECTED_ORGANISM_PROPERTY = "ORGANISM"; - - /** - * String representing {@link #selectedVersion} property used by - * {@link #firePropertyChange(String, Object, Object)}. - */ - protected static final String SELECTED_VERSION_PROPERTY = "VERSION"; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(ReferenceGenomeBean.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Selected reference genome type used during uploading reference genome. - */ - private ReferenceGenomeType selectedReferenceGenomeType = null; - - /** - * Selected organism used during uploading reference genome. - */ - private MiriamData selectedOrganism = null; - - /** - * Selected version of reference genome used during uploading reference - * genome. - */ - private String selectedVersion = null; - - /** - * Url of uploaded genome. - */ - private String selectedUrl = null; - - /** - * List of currently available genome types. - */ - private List<ReferenceGenomeType> genomeTypes = new ArrayList<>(); - - /** - * List of available organism for currenntly selected genome type. - */ - private List<MiriamData> availableOrganisms = new ArrayList<>(); - - /** - * List of available genome version for selected organism and genome type. - */ - private List<String> availableVersions = new ArrayList<>(); - - /** - * List of all downloaded genomes. - */ - private List<ReferenceGenome> downloadedGenomes = new ArrayList<>(); - - /** - * Mapping between organism taxonomy id and name. - */ - private Map<MiriamData, String> organismName = new HashMap<>(); - - /** - * {@link ReferenceGenome} that is currently edited. - */ - private ReferenceGenome editedReferenceGenome = null; - - /** - * Name of gene mapping that is going to be added. - */ - private String selectedReferenceGenomeGeneMappingName = null; - - /** - * Url to the gene mapping that is going to be added. - */ - private String selectedReferenceGenomeGeneMappingUrl = null; - - /** - * Service that manages reference genomes. - */ - @ManagedProperty(value = "#{ReferenceGenomeService}") - private transient IReferenceGenomeService referenceGenomeService; - - /** - * Object that allows to access information about taxonomy. - */ - @ManagedProperty(value = "#{TaxonomyBackend }") - private transient TaxonomyBackend taxonomyBackend; - - /** - * Service used to access information about users. - * - * @see IUserService - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * 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() { - PropertyChangeListener selectedReferenceGenomeTypePropertyChangeListener = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (REFERENCE_GENOME_TYPE_PROPERTY.equals(arg0.getPropertyName())) { - try { - setAvailableOrganisms(referenceGenomeService.getOrganismsByReferenceGenomeType((ReferenceGenomeType) arg0.getNewValue())); - if (availableOrganisms.size() > 0) { - setSelectedOrganism(availableOrganisms.get(0)); - } - } catch (ReferenceGenomeConnectorException e) { - sendError("Problem with accessing information about available organisms", e); - } catch (Exception e) { - sendError("Internal Server Error", e); - } - } - } - }; - addPropertyChangeListener(selectedReferenceGenomeTypePropertyChangeListener); - - PropertyChangeListener selectedOrganismPropertyChangeListener = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (SELECTED_ORGANISM_PROPERTY.equals(arg0.getPropertyName())) { - try { - setAvailableVersions(referenceGenomeService.getAvailableGenomeVersions(selectedReferenceGenomeType, (MiriamData) arg0.getNewValue())); - if (getAvailableVersions().size() > 0) { - setSelectedVersion(availableVersions.get(0)); - } - } catch (ReferenceGenomeConnectorException e) { - sendError("Problem with accessing information about available organism versions", e); - } catch (Exception e) { - sendError("Internal Server Error", e); - } - } - } - }; - addPropertyChangeListener(selectedOrganismPropertyChangeListener); - - VetoableChangeListener selectedOrganismVetoablePropertyChangeListener = new VetoableChangeListener() { - @Override - public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { - if (SELECTED_ORGANISM_PROPERTY.equals(evt.getPropertyName())) { - if (!getAvailableOrganisms().contains(evt.getNewValue())) { - throw new PropertyVetoException("Cannot change organism to: " + evt.getNewValue() + ". Organism is not available in current organisms list.", evt); - } - } - - } - }; - addVetoablePropertyChangeListener(selectedOrganismVetoablePropertyChangeListener); - - PropertyChangeListener selectedVersionPropertyChangeListener = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (SELECTED_VERSION_PROPERTY.equals(arg0.getPropertyName())) { - setSelectedUrl(referenceGenomeService.getUrlForGenomeVersion(selectedReferenceGenomeType, selectedOrganism, (String) arg0.getNewValue())); - } - } - }; - addPropertyChangeListener(selectedVersionPropertyChangeListener); - - VetoableChangeListener selectedVersionVetoablePropertyChangeListener = new VetoableChangeListener() { - @Override - public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException { - if (SELECTED_VERSION_PROPERTY.equals(evt.getPropertyName())) { - if (!getAvailableVersions().contains(evt.getNewValue())) { - throw new PropertyVetoException( - "Cannot change organism version to to: " + evt.getNewValue() + ". Version is not available in current organisms list.", evt); - } - } - } - }; - addVetoablePropertyChangeListener(selectedVersionVetoablePropertyChangeListener); - - for (ReferenceGenomeType type : ReferenceGenomeType.values()) { - genomeTypes.add(type); - } - - setSelectedReferenceGenomeType(ReferenceGenomeType.UCSC); - - refreshDownloadedGenomes(); - } - - @Override - public void clear() { - } - - /** - * @return the selectedReferenceGenomeType - * @see #selectedReferenceGenomeType - */ - public ReferenceGenomeType getSelectedReferenceGenomeType() { - return selectedReferenceGenomeType; - } - - /** - * @param selectedReferenceGenomeType - * the selectedReferenceGenomeType to set - * @see #selectedReferenceGenomeType - */ - public void setSelectedReferenceGenomeType(ReferenceGenomeType selectedReferenceGenomeType) { - ReferenceGenomeType oldValue = this.selectedReferenceGenomeType; - this.selectedReferenceGenomeType = selectedReferenceGenomeType; - firePropertyChange(REFERENCE_GENOME_TYPE_PROPERTY, oldValue, selectedReferenceGenomeType); - } - - /** - * @return the selectedOrganism - * @see #selectedOrganism - */ - public MiriamData getSelectedOrganism() { - return selectedOrganism; - } - - /** - * @param selectedOrganism - * the selectedOrganism to set - * @see #selectedOrganism - */ - public void setSelectedOrganism(MiriamData selectedOrganism) { - MiriamData oldValue = this.selectedOrganism; - - try { - fireVetoableChange(SELECTED_ORGANISM_PROPERTY, oldValue, selectedOrganism); - this.selectedOrganism = selectedOrganism; - firePropertyChange(SELECTED_ORGANISM_PROPERTY, oldValue, selectedOrganism); - } catch (PropertyVetoException e) { - } - } - - /** - * @return the selectedVersion - * @see #selectedVersion - */ - public String getSelectedVersion() { - return selectedVersion; - } - - /** - * @param selectedVersion - * the selectedVersion to set - * @see #selectedVersion - */ - public void setSelectedVersion(String selectedVersion) { - String oldValue = this.selectedVersion; - try { - fireVetoableChange(SELECTED_VERSION_PROPERTY, oldValue, selectedVersion); - this.selectedVersion = selectedVersion; - firePropertyChange(SELECTED_VERSION_PROPERTY, oldValue, selectedVersion); - } catch (PropertyVetoException e) { - } - - } - - /** - * @return the selectedUrl - * @see #selectedUrl - */ - public String getSelectedUrl() { - return selectedUrl; - } - - /** - * @param selectedUrl - * the selectedUrl to set - * @see #selectedUrl - */ - public void setSelectedUrl(String selectedUrl) { - this.selectedUrl = selectedUrl; - } - - /** - * @return the genomeTypes - * @see #genomeTypes - */ - public List<ReferenceGenomeType> getGenomeTypes() { - return genomeTypes; - } - - /** - * @param genomeTypes - * the genomeTypes to set - * @see #genomeTypes - */ - public void setGenomeTypes(List<ReferenceGenomeType> genomeTypes) { - this.genomeTypes = genomeTypes; - } - - /** - * @return the referenceGenomeService - * @see #referenceGenomeService - */ - public IReferenceGenomeService getReferenceGenomeService() { - return referenceGenomeService; - } - - /** - * @param referenceGenomeService - * the referenceGenomeService to set - * @see #referenceGenomeService - */ - public void setReferenceGenomeService(IReferenceGenomeService referenceGenomeService) { - this.referenceGenomeService = referenceGenomeService; - } - - /** - * @return the availableOrganisms - * @see #availableOrganisms - */ - public List<MiriamData> getAvailableOrganisms() { - return availableOrganisms; - } - - /** - * @param availableOrganisms - * the availableOrganisms to set - * @see #availableOrganisms - */ - public void setAvailableOrganisms(List<MiriamData> availableOrganisms) { - logger.debug("set available org"); - this.availableOrganisms = availableOrganisms; - } - - /** - * @return the availableVersions - * @see #availableVersions - */ - public List<String> getAvailableVersions() { - return availableVersions; - } - - /** - * @param availableVersions - * the availableVersions to set - * @see #availableVersions - */ - public void setAvailableVersions(List<String> availableVersions) { - this.availableVersions = availableVersions; - } - - /** - * @return the downloadedGenomes - * @see #downloadedGenomes - */ - public List<ReferenceGenome> getDownloadedGenomes() { - return downloadedGenomes; - } - - /** - * @param downloadedGenomes - * the downloadedGenomes to set - * @see #downloadedGenomes - */ - public void setDownloadedGenomes(List<ReferenceGenome> downloadedGenomes) { - this.downloadedGenomes = downloadedGenomes; - } - - /** - * Downloads genome and adds it to the project (download will be processed - * asynchronously). - */ - public void downloadGenome() { - try { - referenceGenomeService.addReferenceGenome(selectedReferenceGenomeType, selectedOrganism, selectedVersion, selectedUrl); - } catch (IOException e) { - sendError("Problem with downloading file...", e); - } catch (URISyntaxException e) { - sendError("Provided url is invalid: " + selectedUrl, e); - } catch (ReferenceGenomeExistsException e) { - sendError(e.getMessage(), e); - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Downloads genome mapping and adds it to the project (download will be - * processed asynchronously). - */ - public void downloadGenomeGeneMapping() { - try { - referenceGenomeService - .addReferenceGenomeGeneMapping(editedReferenceGenome, selectedReferenceGenomeGeneMappingName, selectedReferenceGenomeGeneMappingUrl); - } catch (IOException e) { - sendError("Problem with downloading file...", e); - } catch (URISyntaxException e) { - sendError("Provided url is invalid: " + selectedUrl, e); - } catch (ReferenceGenomeConnectorException e) { - sendError(e.getMessage(), e); - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Refresh list of downloaded genomes. - */ - public void refreshDownloadedGenomes() { - setDownloadedGenomes(referenceGenomeService.getDownloadedGenomes()); - if (editedReferenceGenome != null) { - for (ReferenceGenome genome : downloadedGenomes) { - if (genome.getId() == editedReferenceGenome.getId()) { - setEditedReferenceGenome(genome); - } - } - } - } - - /** - * Gets name of organism by {@link MiriamType#TAXONOMY} id. - * - * @param md - * identifier of the organism - * @return name of organism - */ - public String getOrganismName(MiriamData md) { - if (md == null) { - return null; - } else { - if (organismName.containsKey(md)) { - return organismName.get(md); - } - try { - String result = taxonomyBackend.getNameForTaxonomy(md); - organismName.put(md, result); - return result; - } catch (TaxonomySearchException e) { - sendError("Problem with accesing taxonomy database", e); - return null; - } - } - } - - /** - * @return the taxonomyBackend - * @see #taxonomyBackend - */ - public TaxonomyBackend getTaxonomyBackend() { - return taxonomyBackend; - } - - /** - * @param taxonomyBackend - * the taxonomyBackend to set - * @see #taxonomyBackend - */ - public void setTaxonomyBackend(TaxonomyBackend taxonomyBackend) { - this.taxonomyBackend = taxonomyBackend; - } - - /** - * @return the editedReferenceGenome - * @see #editedReferenceGenome - */ - public ReferenceGenome getEditedReferenceGenome() { - return editedReferenceGenome; - } - - /** - * @param editedReferenceGenome - * the editedReferenceGenome to set - * @see #editedReferenceGenome - */ - public void setEditedReferenceGenome(ReferenceGenome editedReferenceGenome) { - this.editedReferenceGenome = editedReferenceGenome; - } - - /** - * @return the selectedReferenceGenomeGeneMappingName - * @see #selectedReferenceGenomeGeneMappingName - */ - public String getSelectedReferenceGenomeGeneMappingName() { - return selectedReferenceGenomeGeneMappingName; - } - - /** - * @param selectedReferenceGenomeGeneMappingName - * the selectedReferenceGenomeGeneMappingName to set - * @see #selectedReferenceGenomeGeneMappingName - */ - public void setSelectedReferenceGenomeGeneMappingName(String selectedReferenceGenomeGeneMappingName) { - this.selectedReferenceGenomeGeneMappingName = selectedReferenceGenomeGeneMappingName; - } - - /** - * @return the selectedReferenceGenomeGeneMappingUrl - * @see #selectedReferenceGenomeGeneMappingUrl - */ - public String getSelectedReferenceGenomeGeneMappingUrl() { - return selectedReferenceGenomeGeneMappingUrl; - } - - /** - * @param selectedReferenceGenomeGeneMappingUrl - * the selectedReferenceGenomeGeneMappingUrl to set - * @see #selectedReferenceGenomeGeneMappingUrl - */ - public void setSelectedReferenceGenomeGeneMappingUrl(String selectedReferenceGenomeGeneMappingUrl) { - this.selectedReferenceGenomeGeneMappingUrl = selectedReferenceGenomeGeneMappingUrl; - } - - /** - * Checks if currently logged user has privilege for managing genomes. - * - * @return <code>true</code> if user has access to manage privileges - */ - public boolean getUserHasManageGenomesPrivilege() { - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.MANAGE_GENOMES); - return result; - } - - /** - * @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; - } - - /** - * Adds genome mapping to genome. - * - * @param genome - * genome to which genome mapping will be added - */ - public void addGeneMapping(ReferenceGenome genome) { - try { - referenceGenomeService.addReferenceGenomeGeneMapping(genome, selectedReferenceGenomeGeneMappingName, selectedReferenceGenomeGeneMappingUrl); - refreshDownloadedGenomes(); - } catch (IOException e) { - sendError("Problem with downloading file...", e); - } catch (URISyntaxException e) { - sendError("Provided url is invalid: " + selectedUrl, e); - } catch (ReferenceGenomeConnectorException e) { - sendError(e.getMessage(), e); - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Removes genome mapping from the system. - * - * @param genomeMapping - * genome mapping to be removed - */ - public void removeGeneMapping(ReferenceGenomeGeneMapping genomeMapping) { - try { - referenceGenomeService.removeReferenceGenomeGeneMapping(genomeMapping); - refreshDownloadedGenomes(); - } catch (IOException e) { - sendError("Problem with removing file...", e); - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Removes genome from the system. - * - * @param genome - * genome to be removed - */ - public void removeGenome(ReferenceGenome genome) { - try { - referenceGenomeService.removeGenome(genome); - refreshDownloadedGenomes(); - } catch (IOException e) { - sendError("Problem with removing file...", e); - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Sends information about genome to javacsript code. - * - * @param actionEvent - * JSF event - */ - public final void requestJavasciptGenomeDetails(final ActionEvent actionEvent) { - try { - // get the request params - String type = getRequestParameter("type"); - String version = getRequestParameter("version"); - - String organismId = getRequestParameter("organismId"); - MiriamData organism = null; - if (organismId != null && !organismId.isEmpty()) { - organism = new MiriamData(MiriamType.TAXONOMY, organismId); - } else { - organism = mapBean.getCurrentProject().getOrganism(); - } - ReferenceGenomeView result = null; - if (organism == null) { - logger.warn("Organism not defined"); - } else { - try { - ReferenceGenomeType genomeType = ReferenceGenomeType.valueOf(type); - result = referenceGenomeService.getReferenceGenomeViewByParams(organism, genomeType, version); - } catch (IllegalArgumentException e) { - logger.warn("Cannot find type: " + type); - } - } - String json = "null"; - if (result != null) { - json = new Gson().toJson(result); - } - String javascriptCode = "ServerConnector.updateReferenceGenomeData('" + organismId + "','" + type + "','" + version + "'," + json + ");\n"; - executeJavascript(javascriptCode.toString()); - } catch (Exception e) { - sendError("Internal server error", e); - } - - } - - /** - * @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; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/SearchBean.java b/web/src/main/java/lcsb/mapviewer/bean/SearchBean.java deleted file mode 100644 index 012985286262fda410348e98d18e6a380fbb9a79..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/SearchBean.java +++ /dev/null @@ -1,589 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.awt.geom.Point2D; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.event.ActionEvent; - -import org.apache.log4j.Logger; -import org.primefaces.event.SelectEvent; -import org.primefaces.model.map.LatLng; - -import lcsb.mapviewer.bean.MapBean.ClientMapData; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.interfaces.IConfigurationService; -import lcsb.mapviewer.services.interfaces.IDataMiningService; -import lcsb.mapviewer.services.interfaces.ISearchService; -import lcsb.mapviewer.services.interfaces.ISearchService.CoordinatesSearchParams; -import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.search.ElementIdentifierDetails; -import lcsb.mapviewer.services.search.IHeavyView; -import lcsb.mapviewer.services.search.data.ElementIdentifier; -import lcsb.mapviewer.services.search.data.ElementIdentifier.ElementIdentifierType; -import lcsb.mapviewer.services.search.data.FullAliasView; -import lcsb.mapviewer.services.search.data.FullReactionView; -import lcsb.mapviewer.services.search.data.SearchElementResult; -import lcsb.mapviewer.services.utils.gmap.CoordinationConverter; - -/** - * Bean used for searching elements in the current map. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "searchMB") -@ViewScoped -public class SearchBean extends AbstractMarkerManagerBean<SearchElementResult> implements Serializable { - - /** - * Name of the session field that store last query. - */ - public static final String STRING_SEARCH_SESSION_PARAM = "SEARCH_QUERY"; - - /** - * Name of the session field that store coordinates of last click. - */ - public static final String COORDINATE_SEARCH_SESSION_PARAM = "SEARCH_COORD"; - - /** - * Name of the session field that store model identifier where the last click - * was performed. - */ - public static final String COORDINATE_SEARCH_MODEL_ID_SESSION_PARAM = "SEARCH_COORD_MODEL_ID"; - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(SearchBean.class); - - /** - * Should search by name be perfectly matched. - */ - private String perfectMatchParam = ""; - - /** - * This parameter define the maximum distance between reaction and coordinates - * that is acceptable in search. - */ - private double searchDistance = 0; - - /** - * Maximum number of search results. - */ - private Integer maxNumberOfResults; - - /** - * Bean used for communication with the client side about the map currently - * visualized. - * - * @see MapBean - */ - @ManagedProperty(value = "#{mapMB}") - private transient MapBean mapBean; - - /** - * 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 managing data mining information. - */ - @ManagedProperty(value = "#{missingConnectionMB}") - private transient MissingConnectionBean missingConnectionBean; - - /** - * Service used to access information about users. - * - * @see IUserService - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * Service that allows to query the database to find elements in the model. - */ - @ManagedProperty(value = "#{SearchService}") - private transient ISearchService searchService; - - /** - * Service that manages data mining information. - */ - @ManagedProperty(value = "#{DataMiningService}") - private transient IDataMiningService dataMiningService; - - /** - * Service used to access configuration parameters. - * - * @see IConfigurationService - */ - @ManagedProperty(value = "#{ConfigurationService}") - private transient IConfigurationService configurationService; - - @Override - public void init() { - // set the default max distance - String dist = configurationService.getConfigurationValue(ConfigurationElementType.SEARCH_DISTANCE); - try { - setSearchDistance(Double.valueOf(dist)); - } catch (NumberFormatException e) { - logger.error("Problem with distance param: " + dist, e); - } - - // set the max number of results - String results = configurationService.getConfigurationValue(ConfigurationElementType.SEARCH_RESULT_NUMBER); - try { - setMaxNumberOfResults(Integer.valueOf(results)); - } catch (NumberFormatException e) { - logger.error("Problem with max number of search results: " + results, e); - } - - // if by chance we already opened this model in pur session then restore - // search results - try { - refreshSearch(); - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Method called when client selects element from autocomplete in search field - * (call search method). - * - * @param event - * select event send by the client - */ - public void autocompleteHandleSelect(final SelectEvent event) { - String searchText = getRequestParameter("tabView:mainForm:searchText_input"); - search(searchText); - } - - /** - * This method search the model with a string query. - * - * @param actionEvent - * event from thefrom the client - */ - public void search(final ActionEvent actionEvent) { - String searchText = getRequestParameter("tabView:mainForm:searchText_input"); - search(searchText); - } - - /** - * Look for elements using query given in the parameter. - * - * @param query - * search query - */ - protected void search(String query) { - addSessionParam(STRING_SEARCH_SESSION_PARAM + getCurrentMapId(), query); - addSessionParam(COORDINATE_SEARCH_SESSION_PARAM + getCurrentMapId(), null); - - String ipAddress = getClientIpAddress(); - logger.debug("Search: " + query); - - // clear results - clearResults(); - - boolean perfectMatch = perfectMatchParam.equalsIgnoreCase("true"); - - try { - - // clear suggested connections (it should be refactorized to listeners) - missingConnectionBean.setGeneName(null); - missingConnectionBean.search(null); - - // find all matching objects - int set = 0; - for (String string : splitQuery(query, false)) { - SearchElementResult result = searchService.searchByQuery(getCurrentTopModel(), string, maxNumberOfResults, perfectMatch, ipAddress); - searchService.assignIcons(result, set++); - super.addResult(result); - } - - // send markers to client - refreshDataInJavascript(true); - - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * This method is invoked by client when map is clicked. - * - * @param actionEvent - * event data - */ - public void mapClicked(final ActionEvent actionEvent) { - String modelIdentifier = getRequestParameter("submodelId"); - String latCoord = getRequestParameter("latCoord"); - String lngCoord = getRequestParameter("lngCoord"); - logger.debug("Submap clicked (id=" + modelIdentifier + ")"); - Integer id = null; - try { - id = Integer.valueOf(modelIdentifier); - } catch (NumberFormatException e) { - sendError("Model identifier is invalid: " + modelIdentifier); - return; - } - Model model = getCurrentTopModel().getSubmodelById(id); - if (model == null) { - sendError("SubModel with id: " + modelIdentifier + " doesn't exist."); - return; - } - LatLng latLng = null; - if (latCoord != null && lngCoord != null) { - try { - double lat = Double.parseDouble(latCoord); - double lng = Double.parseDouble(lngCoord); - latLng = new LatLng(lat, lng); - } catch (NumberFormatException e) { - sendError("Invalid latLng coordinates: " + latCoord + "," + lngCoord); - return; - } - } else { - sendError("Invalid latLng coordinates: " + latCoord + "," + lngCoord); - return; - } - CoordinationConverter converter = mapBean.getMapDataByMapIdentifier(modelIdentifier).getcConverter(); - - addSessionParam(STRING_SEARCH_SESSION_PARAM + getCurrentMapId(), null); - Point2D coord = converter.toPoint(latLng); - addSessionParam(COORDINATE_SEARCH_SESSION_PARAM + getCurrentMapId(), coord); - addSessionParam(COORDINATE_SEARCH_MODEL_ID_SESSION_PARAM + getCurrentMapId(), model.getId()); - searchByCoordinates(coord, model); - } - - /** - * Find something on the map close to coordinates. - * - * @param coordinates - * point where we are looking for something - * @param model - * map on which we search for an element - */ - private void searchByCoordinates(final Point2D coordinates, Model model) { - try { - ClientMapData mapData = mapBean.getMapDataByMapIdentifier(model.getId()); - // clear results - clearResults(); - - // clear suggested connections (it should be refactorized to listeners) - missingConnectionBean.setGeneName(null); - missingConnectionBean.search(null); - - // compute the distance on the map (it depends a little on the zoomLevel) - double distance = mapData.getcConverter().scale(searchDistance, mapData.getZoomLevel()); - - // set search params - CoordinatesSearchParams searchParams = new CoordinatesSearchParams(); - searchParams.model(model); - searchParams.point(coordinates); - searchParams.distance(distance); - searchParams.layoutIdentifier(mapBean.getSelectedLayoutIdentifier()); - searchParams.level(mapBean.getLevel(mapData)); - - // find objects on the map - SearchElementResult result = searchService.searchByCoordinates(searchParams); - searchService.assignIcons(result, 0); - addResult(result); - - // send markers to the map - refreshDataInJavascript(false); - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Refresh search result using data stored in the session as search input (for - * instance when the webpage is refreshed). - */ - private void refreshSearch() { - String query = (String) getSessionParam(STRING_SEARCH_SESSION_PARAM + getCurrentMapId()); - if (query != null) { - search(query); - } else { - Point2D coord = (Point2D) getSessionParam(COORDINATE_SEARCH_SESSION_PARAM + getCurrentMapId()); - Integer modelId = (Integer) getSessionParam(COORDINATE_SEARCH_MODEL_ID_SESSION_PARAM + getCurrentMapId()); - Model model = getCurrentTopModel().getSubmodelById(modelId); - if (coord != null && model != null) { - searchByCoordinates(coord, model); - } - } - } - - /** - * Returns list of autocomple strings for the string query. - * - * @param query - * query for which autocomplete is returned - * @return list of autocomple strings - */ - public List<String> autocomplete(final String query) { - return searchService.getAutocompleteList(getCurrentTopModel(), query); - } - - @Override - public void clear() { - setPerfectMatchParam("false"); - addSessionParam(STRING_SEARCH_SESSION_PARAM + getCurrentMapId(), null); - addSessionParam(COORDINATE_SEARCH_SESSION_PARAM + getCurrentMapId(), null); - addSessionParam(COORDINATE_SEARCH_MODEL_ID_SESSION_PARAM + getCurrentMapId(), null); - clearResults(); - refreshDataInJavascript(); - } - - /** - * @return the mapBean - * @see #mapBean - */ - public MapBean getMapBean() { - if (mapBean == null) { - mapBean = findBean(MapBean.class); - } - return mapBean; - } - - /** - * @param mapBean - * the mapBean to set - * @see #mapBean - */ - public void setMapBean(MapBean mapBean) { - this.mapBean = mapBean; - } - - /** - * @return the dataMiningService - * @see #dataMiningService - */ - public IDataMiningService getDataMiningService() { - return dataMiningService; - } - - /** - * @param dataMiningService - * the dataMiningService to set - * @see #dataMiningService - */ - public void setDataMiningService(IDataMiningService dataMiningService) { - this.dataMiningService = dataMiningService; - } - - /** - * @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 searchService - * @see #searchService - */ - public ISearchService getSearchService() { - return searchService; - } - - /** - * @param searchService - * the searchService to set - * @see #searchService - */ - public void setSearchService(ISearchService searchService) { - this.searchService = searchService; - } - - /** - * @return the perfectMatchParam - * @see #perfectMatchParam - */ - public String getPerfectMatchParam() { - return perfectMatchParam; - } - - /** - * @param perfectMatchParam - * the perfectMatchParam to set - * @see #perfectMatchParam - */ - public void setPerfectMatchParam(String perfectMatchParam) { - this.perfectMatchParam = perfectMatchParam; - } - - /** - * @return the searchDistance - * @see #searchDistance - */ - public double getSearchDistance() { - return searchDistance; - } - - /** - * @param searchDistance - * the searchDistance to set - * @see #searchDistance - */ - public void setSearchDistance(double searchDistance) { - this.searchDistance = searchDistance; - } - - /** - * @return the missingConnectionBean - * @see #missingConnectionBean - */ - public MissingConnectionBean getMissingConnectionBean() { - return missingConnectionBean; - } - - /** - * @param missingConnectionBean - * the missingConnectionBean to set - * @see #missingConnectionBean - */ - public void setMissingConnectionBean(MissingConnectionBean missingConnectionBean) { - this.missingConnectionBean = missingConnectionBean; - } - - /** - * @return the maxNumberOfResults - * @see #maxNumberOfResults - */ - public Integer getMaxNumberOfResults() { - return maxNumberOfResults; - } - - /** - * @param maxNumberOfResults - * the maxNumberOfResults to set - * @see #maxNumberOfResults - */ - public void setMaxNumberOfResults(Integer maxNumberOfResults) { - this.maxNumberOfResults = maxNumberOfResults; - } - - @Override - protected List<ElementIdentifier> getLightElementsForSearchResult(SearchElementResult searchResult) { - SearchElementResult searchElementResult = (SearchElementResult) searchResult; - List<ElementIdentifier> result = new ArrayList<>(); - for (IHeavyView element : searchElementResult.getElements()) { - if (element instanceof FullAliasView) { - FullAliasView alias = (FullAliasView) element; - result.add(new ElementIdentifier(alias.getUniqueId(), alias.getModelId(), ElementIdentifierType.ALIAS, alias.getIcon())); - } else if (element instanceof FullReactionView) { - FullReactionView reaction = (FullReactionView) element; - result.add(new ElementIdentifier(reaction.getUniqueId(), reaction.getModelId(), ElementIdentifierType.REACTION, null)); - } else { - throw new InvalidArgumentException("ISearchResultView conatins invalid object: " + element.getClass()); - } - } - return result; - } - - @Override - protected ElementIdentifierDetails getElementInformationForResult(ElementIdentifier element, SearchElementResult result) { - throw new NotImplementedException(); - } - - @Override - protected List<Pair<String, ElementIdentifierDetails>> getElementInformationForResult(ElementIdentifier element) { - throw new NotImplementedException(); - } - - /** - * Returns currently browsed map. - * - * @return currently browsed map - */ - private Model getCurrentTopModel() { - return getMapBean().getCurrentTopModel(); - } - - /** - * Returns identifier of browsed map (if such map wasn't setup it will be - * default identifier). - * - * @return identifier of browsed map - */ - private String getCurrentMapId() { - return mapBean.getCurrentMapId(); - } - - /** - * Returns curently browsed project. - * - * @return curently browsed project - */ - private Project getCurrentProject() { - return getCurrentTopModel().getProject(); - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/StatusBean.java b/web/src/main/java/lcsb/mapviewer/bean/StatusBean.java deleted file mode 100644 index 87a74b5ebae0058d58b223e358b6f64809d469c6..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/StatusBean.java +++ /dev/null @@ -1,116 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.event.ActionEvent; - -import lcsb.mapviewer.annotation.services.ExternalServiceStatus; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.services.interfaces.IExternalServicesService; - -import org.apache.log4j.Logger; - -/** - * Bean used for checking the status of different services used by the system. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "statusMB") -@ViewScoped -public class StatusBean extends AbstractManagedBean implements Serializable { - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(StatusBean.class); - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * List of statuses of modules that use external resources. - */ - private transient List<ExternalServiceStatus> statuses = new ArrayList<ExternalServiceStatus>(); - - /** - * Service used for getting the statuses of modules that used external - * resources. - */ - @ManagedProperty(value = "#{ExternalServicesService}") - private transient IExternalServicesService externalServicesService; - - /** - * Refresh statuses. - * - * @param actionEvent - * event from thefrom the client - */ - public void refreshStatuses(final ActionEvent actionEvent) { - try { - statuses = externalServicesService.getExternalServiceStatuses(); - // if the status list is empty then add default list of services to check - if (statuses.size() == 0) { - externalServicesService.registerDefaultServices(); - statuses = externalServicesService.getExternalServiceStatuses(); - if (statuses.size() == 0) { - sendError("List of know services is empty"); - } - } - } catch (Exception e) { - logger.error(e); - sendError("Internal server error. More info in logs."); - } - } - - @Override - public void clear() { - throw new NotImplementedException(); - } - - /** - * @return the externalServicesService - * @see #externalServicesService - */ - public IExternalServicesService getExternalServicesService() { - return externalServicesService; - } - - /** - * @param externalServicesService - * the externalServicesService to set - * @see #externalServicesService - */ - public void setExternalServicesService(IExternalServicesService externalServicesService) { - this.externalServicesService = externalServicesService; - } - - /** - * @return the statuses - * @see #statuses - */ - public List<ExternalServiceStatus> getStatuses() { - return statuses; - } - - /** - * @param statuses - * the statuses to set - * @see #statuses - */ - public void setStatuses(List<ExternalServiceStatus> statuses) { - this.statuses = statuses; - } - - @Override - public void init() { - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/UserBean.java b/web/src/main/java/lcsb/mapviewer/bean/UserBean.java deleted file mode 100644 index 7d5f68b00d6eae0ba16a3206661f592b6dd068ff..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/UserBean.java +++ /dev/null @@ -1,603 +0,0 @@ -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; -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.SessionScoped; -import javax.faces.component.UIComponent; -import javax.faces.component.UIInput; -import javax.faces.context.ExternalContext; -import javax.faces.context.FacesContext; -import javax.faces.event.ActionEvent; -import javax.faces.validator.ValidatorException; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - -import org.apache.log4j.Logger; -import org.primefaces.context.RequestContext; - -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.events.ObjectModifiedEvent; -import lcsb.mapviewer.model.log.LogType; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; -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; - -/** - * Bean used for managing logged user data. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "userMB") -@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, ""); - } - Calendar now = Calendar.getInstance(); - now.add(Calendar.MINUTE, -1); - if (authenticationToken.getExpires().before(now)) { - authenticationToken = getUserService().login(Configuration.ANONYMOUS_LOGIN, ""); - } - return authenticationToken; - } - - /** - * @param authenticationToken - * the authenticationToken to set - * @see #authenticationToken - */ - public void setAuthenticationToken(AuthenticationToken authenticationToken) { - this.authenticationToken = authenticationToken; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/UsersBean.java b/web/src/main/java/lcsb/mapviewer/bean/UsersBean.java deleted file mode 100644 index 286acd8d7107b8e0baef21134c5fe71f37280a03..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/UsersBean.java +++ /dev/null @@ -1,390 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import javax.faces.bean.ManagedBean; -import javax.faces.bean.ManagedProperty; -import javax.faces.bean.ViewScoped; -import javax.faces.event.ActionEvent; - -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.exception.NotImplementedException; -import lcsb.mapviewer.events.Listener; -import lcsb.mapviewer.events.ObjectAddedEvent; -import lcsb.mapviewer.events.ObjectModifiedEvent; -import lcsb.mapviewer.events.ObjectRemovedEvent; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.interfaces.IUserService; -import lcsb.mapviewer.services.view.UserView; -import lcsb.mapviewer.services.view.UserView.UserProjectPrivilegeView; - -import org.apache.log4j.Logger; - -/** - * Bean used for managing users. - * - * @author Piotr Gawron - * - */ -@ManagedBean(name = "usersMB") -@ViewScoped -public class UsersBean extends AbstractManagedBean implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(UsersBean.class); - - /** - * List of all users to be managed in the client. - */ - private List<UserView> userList = new ArrayList<UserView>(); - - /** - * List of all available {@link PrivilegeType} for any {@link Project}. - */ - private List<PrivilegeType> projectPrivilegeTypes = new ArrayList<PrivilegeType>(); - - /** - * User selected for updating/removing in the client. - */ - private UserView selectedUser; - - /** - * Privilege for the map selected on the manage page. - */ - private UserProjectPrivilegeView projectPrivilege; - - /** - * Bean used for communication with the client side about the data related to - * currently logged user. - * - * @see UserBean - */ - @ManagedProperty(value = "#{userMB}") - private transient UserBean userBean; - - /** - * Bean resposnisble for managing projects. - * - * @see ProjectBean - */ - @ManagedProperty(value = "#{projectMB}") - private transient ProjectBean projectBean; - - /** - * Service used to access information about users. - * - * @see IUserService - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - @Override - public void init() { - setSelectedUser(userService.createEmptyUserRow()); - setProjectPrivilege(selectedUser.new UserProjectPrivilegeView()); - - for (PrivilegeType pt : PrivilegeType.values()) { - if (pt.getPrivilegeObjectType() != null && pt.getPrivilegeObjectType().equals(Project.class)) { - projectPrivilegeTypes.add(pt); - } - } - Collections.sort(projectPrivilegeTypes, new Comparator<PrivilegeType>() { - @Override - public int compare(PrivilegeType o1, PrivilegeType o2) { - return o1.getCommonName().compareTo(o2.getCommonName()); - } - }); - - // after user was modified, refresh user list - this.registerListener(new Listener<ObjectModifiedEvent>(ObjectModifiedEvent.class) { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(ObjectModifiedEvent event) { - refreshUserList(null); - } - }); - - // after user was added, refresh user list - this.registerListener(new Listener<ObjectAddedEvent>(ObjectAddedEvent.class) { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(ObjectAddedEvent event) { - refreshUserList(null); - } - }); - - // after user was removed, refresh user list - this.registerListener(new Listener<ObjectRemovedEvent>(ObjectRemovedEvent.class) { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(ObjectRemovedEvent event) { - refreshUserList(null); - } - }); - - // after project is added refresh information about users (to include - // privileges for new project) - projectBean.registerListener(new Listener<ObjectAddedEvent>(ObjectAddedEvent.class) { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(ObjectAddedEvent event) { - refreshUserList(null); - } - }); - - refreshUserList(null); - } - - /** - * Refresh list of users. - * - * @param actionEvent - * event from thefrom the client - */ - public void refreshUserList(final ActionEvent actionEvent) { - try { - userList.clear(); - List<UserView> localUserList = userService.getAllUserRows(); - userList.addAll(localUserList); - Collections.sort(userList); - } catch (Exception e) { - logger.error(e); - sendError("Internal server error. More info in logs."); - } - } - - /** - * - * @return {@link #selectedUser} - */ - public UserView getSelectedUser() { - return selectedUser; - } - - /** - * Sets new selectedUser value. Property change listeners for "selectedUser" - * property will be thrown after setting this value. - * - * @param selectedUser - * new {@link #selectedUser} value - */ - public void setSelectedUser(final UserView selectedUser) { - this.selectedUser = selectedUser; - this.selectedUser.getPdm().setRowIndex(-1); - this.projectPrivilege = null; - } - - /** - * Update selected user. - * - * @param actionEvent - * event from thefrom the client - */ - public void updateSelectedUser(final ActionEvent actionEvent) { - userService.updateUser(this.selectedUser); - ObjectModifiedEvent event = new ObjectModifiedEvent(this.selectedUser); - callListeners(event); - } - - /** - * Update users. - * - * @param users - * users to update - */ - public void updateUsers(Collection<UserView> users) { - userService.updateUsers(users); - ObjectModifiedEvent event = new ObjectModifiedEvent(users); - callListeners(event); - } - - /** - * Remove selected user. - * - * @param actionEvent - * event from thefrom the client - */ - public void removeSelectedUser(final ActionEvent actionEvent) { - if (Configuration.ANONYMOUS_LOGIN.equals(this.selectedUser.getLogin())) { - sendError("Cannot remove guest account"); - return; - } - userService.deleteUser(this.selectedUser); - ObjectRemovedEvent event = new ObjectRemovedEvent(this.selectedUser); - callListeners(event); - } - - /** - * Creates new empty user view and set it for editing. - * - * @param actionEvent - * clients side action event - */ - public void prepareEmptyUser(final ActionEvent actionEvent) { - this.selectedUser = userService.createEmptyUserRow(); - } - - /** - * Adds new user (stored in {@link #selectedUser} field) to the database. - * - * @param actionEvent - * client side action event - */ - public void addSelectedUser(final ActionEvent actionEvent) { - userService.addUser(this.selectedUser); - ObjectAddedEvent event = new ObjectAddedEvent(this.selectedUser); - callListeners(event); - } - - /** - * 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 = userBean.getLoggedUser(); - if (user == null) { - return false; - } - boolean result = userService.userHasPrivilege(user, PrivilegeType.USER_MANAGEMENT); - return result; - } - - @Override - public void clear() { - throw new NotImplementedException(); - } - - /** - * @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 userList - * @see #userList - */ - public List<UserView> getUserList() { - return userList; - } - - /** - * @param userList - * the userList to set - * @see #userList - */ - public void setUserList(List<UserView> userList) { - this.userList = userList; - } - - /** - * @return the projectPrivilege - * @see #projectPrivilege - */ - public UserProjectPrivilegeView getProjectPrivilege() { - return projectPrivilege; - } - - /** - * @param projectPrivilege - * the projectPrivilege to set - * @see #projectPrivilege - */ - public void setProjectPrivilege(UserProjectPrivilegeView projectPrivilege) { - this.projectPrivilege = projectPrivilege; - } - - /** - * @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 projectPrivilegeTypes - * @see #projectPrivilegeTypes - */ - public List<PrivilegeType> getProjectPrivilegeTypes() { - return projectPrivilegeTypes; - } - - /** - * @param projectPrivilegeTypes - * the projectPrivilegeTypes to set - * @see #projectPrivilegeTypes - */ - public void setProjectPrivilegeTypes(List<PrivilegeType> projectPrivilegeTypes) { - this.projectPrivilegeTypes = projectPrivilegeTypes; - } - - /** - * @return the projectBean - * @see #projectBean - */ - public ProjectBean getProjectBean() { - return projectBean; - } - - /** - * @param projectBean - * the projectBean to set - * @see #projectBean - */ - public void setProjectBean(ProjectBean projectBean) { - this.projectBean = projectBean; - } -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/package-info.java b/web/src/main/java/lcsb/mapviewer/bean/package-info.java deleted file mode 100644 index 0936e7b1e30ba9204d6ff1ff5b9b434b915dd7fe..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Provides beans to communicate with client side. - */ -package lcsb.mapviewer.bean; - diff --git a/web/src/main/java/lcsb/mapviewer/bean/utils/StartupBean.java b/web/src/main/java/lcsb/mapviewer/bean/utils/StartupBean.java index 20dad609ea8eccaf77c5e4527fd8ef37ba478f65..ba6523f3beff9fda6f4661d34775c3926e3ca8de 100644 --- a/web/src/main/java/lcsb/mapviewer/bean/utils/StartupBean.java +++ b/web/src/main/java/lcsb/mapviewer/bean/utils/StartupBean.java @@ -15,7 +15,6 @@ import lcsb.mapviewer.model.Project; import lcsb.mapviewer.model.ProjectStatus; import lcsb.mapviewer.model.map.layout.ReferenceGenome; import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.persist.dao.ProjectDao; import lcsb.mapviewer.services.interfaces.IConfigurationService; import lcsb.mapviewer.services.interfaces.IProjectService; import lcsb.mapviewer.services.interfaces.IReferenceGenomeService; diff --git a/web/src/main/java/lcsb/mapviewer/security/MvInvalidSessionStrategy.java b/web/src/main/java/lcsb/mapviewer/security/MvInvalidSessionStrategy.java deleted file mode 100644 index e3c433620d78980b1e66eeae73f7a604ec160eae..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/security/MvInvalidSessionStrategy.java +++ /dev/null @@ -1,108 +0,0 @@ -package lcsb.mapviewer.security; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.Logger; -import org.springframework.security.web.session.InvalidSessionStrategy; -import org.springframework.util.StringUtils; - -import lcsb.mapviewer.common.Configuration; - -/** - * Implementation of the Spring invalidation startegy. Class used when user - * session was invalidated (expired). - * - * @author Piotr Gawron - * - */ -public class MvInvalidSessionStrategy implements InvalidSessionStrategy { - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(MvInvalidSessionStrategy.class); - - /** - * String identifier of the faces request header. - */ - private static final String FACES_REQUEST_HEADER = "faces-request"; - - /** - * Default constructor. - * - * @param invalidSessionUrl - * url that should be used when session was invalidated - */ - public MvInvalidSessionStrategy(String invalidSessionUrl) { - logger.debug("Invalid session url (not used): " + invalidSessionUrl); - } - - @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; - } - - /** - * Returns request url. - * - * @param request - * request object - * @return request url - */ - private String getRequestUrl(HttpServletRequest request) { - StringBuffer requestURL = request.getRequestURL(); - - String queryString = request.getQueryString(); - if (StringUtils.hasText(queryString)) { - requestURL.append("?").append(queryString); - } - - logger.info("Url: " + requestURL.toString()); - return requestURL.toString(); - } - - /** - * Creates ajax string that reload site in the client browser. - * - * @return ajax string that reload browser - */ - private String createAjaxReloadPageXml() { - return "<partial-response><changes><eval><![CDATA[location.reload(true);]]></eval></changes></partial-response>"; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/security/MvJsfRedirectStrategy.java b/web/src/main/java/lcsb/mapviewer/security/MvJsfRedirectStrategy.java deleted file mode 100644 index d643c8da222aa9a1e940e353f25d305790cc7917..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/security/MvJsfRedirectStrategy.java +++ /dev/null @@ -1,103 +0,0 @@ -package lcsb.mapviewer.security; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.log4j.Logger; -import org.springframework.security.web.RedirectStrategy; -import org.springframework.security.web.util.UrlUtils; - -/** - * Spring redirect strategy (Not sure if it of any use). - * - * @author Piotr Gawron - * - */ -public class MvJsfRedirectStrategy implements RedirectStrategy { - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(MvJsfRedirectStrategy.class); - - /** - * Are we interested in relative or absolute urls. - */ - private boolean contextRelative; - - @Override - public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException { - - if (!response.isCommitted()) { - String redirectUrl = calculateRedirectUrl(request.getContextPath(), url); - redirectUrl = response.encodeRedirectURL(redirectUrl); - - logger.debug("Redirecting to '" + redirectUrl + "'"); - - // we should redirect using ajax response if the case warrants - boolean ajaxRedirect = request.getHeader("faces-request") != null && request.getHeader("faces-request").toLowerCase().indexOf("ajax") > -1; - - if (ajaxRedirect) { - - String ajaxRedirectXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<partial-response><redirect url=\"" + redirectUrl - + "\"></redirect></partial-response>"; - response.setContentType("text/xml"); - response.getWriter().write(ajaxRedirectXml); - } else { - response.sendRedirect(redirectUrl); - } - } - return; - } - - /** - * Creates redirect url. - * - * @param contextPath - * context in which the webpage operates - * @param url - * url - * @return context (in)dependent url - */ - private String calculateRedirectUrl(String contextPath, String url) { - if (!UrlUtils.isAbsoluteUrl(url)) { - if (contextRelative) { - return url; - } else { - return contextPath + url; - } - } - - // Full URL, including http(s):// - - if (!contextRelative) { - return url; - } - - // Calculate the relative URL from the fully qualified URL, minus the scheme - // and base context. - // CHECKSTYLE:OFF - url = url.substring(url.indexOf("://") + 3); // strip off scheme - // CHECKSTYLE:ON - url = url.substring(url.indexOf(contextPath) + contextPath.length()); - - if (url.length() > 1 && url.charAt(0) == '/') { - url = url.substring(1); - } - - return url; - } - - /** - * If <tt>true</tt>, causes any redirection URLs to be calculated minus the - * protocol and context path (defaults to <tt>false</tt>). - * - * @param useRelativeContext - * the contextRelative value - */ - public void setContextRelative(boolean useRelativeContext) { - this.contextRelative = useRelativeContext; - } - -} \ No newline at end of file diff --git a/web/src/main/java/lcsb/mapviewer/security/MvSecurityServiceImpl.java b/web/src/main/java/lcsb/mapviewer/security/MvSecurityServiceImpl.java index 9e8f207ce343ee02dec76bc58139f82a6de2bc18..109a881dfa63c9e7796ecd1a5bd0365ee76834f7 100644 --- a/web/src/main/java/lcsb/mapviewer/security/MvSecurityServiceImpl.java +++ b/web/src/main/java/lcsb/mapviewer/security/MvSecurityServiceImpl.java @@ -1,8 +1,5 @@ package lcsb.mapviewer.security; -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.services.interfaces.IUserService; - import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; @@ -10,8 +7,12 @@ import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.transaction.annotation.Transactional; +import lcsb.mapviewer.common.Configuration; +import lcsb.mapviewer.services.interfaces.IUserService; + /** * Spring implementation of class accessing user details. * @@ -20,49 +21,52 @@ import org.springframework.transaction.annotation.Transactional; */ @Transactional(readOnly = false) public class MvSecurityServiceImpl implements UserDetailsService { - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = Logger.getLogger(MvSecurityServiceImpl.class); + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = Logger.getLogger(MvSecurityServiceImpl.class); + + /** + * Service used for accessing user data. + */ + @Autowired + private IUserService userService; - /** - * Service used for accessing user data. - */ - @Autowired - private IUserService userService; + @Autowired + private PasswordEncoder passwordEncoder; - @Override - public UserDetails loadUserByUsername(String login) { - if (login.equals(Configuration.ANONYMOUS_LOGIN)) { - throw new UsernameNotFoundException("Guest account is disabled."); - } + @Override + public UserDetails loadUserByUsername(String login) { + if (login == null || login.trim().isEmpty() || login.equals(Configuration.ANONYMOUS_LOGIN)) { + return new User(login, passwordEncoder.encode(""), AuthorityUtils.commaSeparatedStringToAuthorityList("")); + } - lcsb.mapviewer.model.user.User user; - user = userService.getUserByLogin(login); - if (user == null) { - throw new UsernameNotFoundException("Invalid username or password."); - } - StringBuilder credentials = new StringBuilder(); + lcsb.mapviewer.model.user.User user = userService.getUserByLogin(login); + if (user == null) { + throw new UsernameNotFoundException("Invalid username or password."); + } + StringBuilder credentials = new StringBuilder(); - return new User(user.getLogin(), user.getCryptedPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(credentials.toString())); - } + return new User(user.getLogin(), user.getCryptedPassword(), + AuthorityUtils.commaSeparatedStringToAuthorityList(credentials.toString())); + } - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } + /** + * @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; - } + /** + * @param userService + * the userService to set + * @see #userService + */ + public void setUserService(IUserService userService) { + this.userService = userService; + } } diff --git a/web/src/main/webapp/WEB-INF/components/admin/footer.xhtml b/web/src/main/webapp/WEB-INF/components/admin/footer.xhtml deleted file mode 100644 index 3d995f9d3243b6d61d0c19ba0d25c9e2f6ea0ca5..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/WEB-INF/components/admin/footer.xhtml +++ /dev/null @@ -1,22 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:ui="http://java.sun.com/jsf/facelets" - xmlns:p="http://primefaces.org/ui"> - - -<div id="footerTable"> -<table width="100%" border="0" cellspacing="0" cellpadding="0"> - <tr> - <td align="left"><a href="#{configurationMB.logoLink}" title="#{configurationMB.logoText}" target="_blank"> - <h:graphicImage library="images" name="#{configurationMB.logoImg}" width="80" height="80" border="0" alt="#{configurationMB.logoText}"/> - </a></td> - <td align="center" class="footerText">MiNERVA version #{configurationMB.version.version};<br/> build #{configurationMB.version.time};<br/>git: #{configurationMB.version.gitVersion}</td> - <td align="right"><a href="http://wwwen.uni.lu/lcsb/" title="LCSB - Luxembourg Centre for Systems Biomedicine" target="_blank"> - <h:graphicImage library="images" name="lcsb.png" width="80" height="80" border="0" alt="LCSB - Luxembourg Centre for Systems Biomedicine"/> - </a></td> - </tr> -</table> -</div> -</html> - diff --git a/web/src/main/webapp/WEB-INF/components/admin/header.xhtml b/web/src/main/webapp/WEB-INF/components/admin/header.xhtml deleted file mode 100644 index 3f4bf95ce2fd7a0df3814e6ac9ac802808ca0da0..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/WEB-INF/components/admin/header.xhtml +++ /dev/null @@ -1,14 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:ui="http://java.sun.com/jsf/facelets" - xmlns:p="http://primefaces.org/ui"> - - <h:outputStylesheet library="css" name="minerva.css" /> - - <div class="minerva-header"> - <a href="#{request.contextPath}/?id=#{mapMB.currentMapId}" class="mainTitle"><i class="fa fa-home" style="font-size:17px"></i> #{mapMB.currentProject.name}</a> - </div> - -</html> - diff --git a/web/src/main/webapp/WEB-INF/components/admin/menu.xhtml b/web/src/main/webapp/WEB-INF/components/admin/menu.xhtml deleted file mode 100644 index 1314c0e9dfaf875e289075a044b6da956879b884..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/WEB-INF/components/admin/menu.xhtml +++ /dev/null @@ -1,56 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:ui="http://java.sun.com/jsf/facelets" - xmlns:p="http://primefaces.org/ui"> - -<ui:include src="/WEB-INF/components/admin/header.xhtml" /> -<h:form id="menuForm"> - <p:menubar > - <p:menuitem value="Comments" - url="/admin/comments.xhtml?id=#{mapMB.currentMapId}"/> - <p:menuitem value="Map manager" - url="/admin/projects.xhtml?id=#{mapMB.currentMapId}"/> - <p:menuitem value="User manager" - url="/admin/users.xhtml?id=#{mapMB.currentMapId}"/> - <p:menuitem value="Service status" - url="/admin/status.xhtml?id=#{mapMB.currentMapId}"/> - <p:menuitem value="Configuration" - url="/admin/configuration.xhtml?id=#{mapMB.currentMapId}"/> - <p:menuitem value="Miriam" - url="/admin/miriam.xhtml?id=#{mapMB.currentMapId}"/> -<!-- <p:menuitem value="Genome" - url="/admin/genomes.xhtml?id=#{mapMB.currentMapId}"/> --> - <p:menuitem value="Manual" - onclick="window.open('#{request.contextPath}/javax.faces.resource/admin_guide.pdf.xhtml?ln=other','_admin_manual_');"/> - <p:menuitem value="Logout" actionListener="#{userMB.doLogout}" - oncomplete="location.reload();" - style="position: absolute; right: 6px; color:#ffffff; "/> - </p:menubar> -</h:form> - -<script type="text/javascript"> -$(window).load(function(){ -var url=$(location).attr('href'); -var active=-1; -if(url.indexOf('comments.xhtml')>0) active=0; -if(url.indexOf('projects.xhtml')>0) active=1; -if(url.indexOf('users.xhtml')>0) active=2; -if(url.indexOf('status.xhtml')>0) active=3; -if(url.indexOf('configuration.xhtml')>0) active=4; -if(url.indexOf('miriam.xhtml')>0) active=5; - -if(active>-1){ -var counter=0; - var tabs = $("a.ui-menuitem-link").each(function(){ - if (counter==active) $(this).attr('class', 'ui-menuitem-link ui-corner-all ui-state-active'); - counter++; - }); -} - -}); -</script> - -</html> - - diff --git a/web/src/main/webapp/WEB-INF/components/admin/statistics.xhtml b/web/src/main/webapp/WEB-INF/components/admin/statistics.xhtml deleted file mode 100644 index 4a4c3a1c9480d7e439a6a8958e5fa2f960617332..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/WEB-INF/components/admin/statistics.xhtml +++ /dev/null @@ -1,28 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:ui="http://java.sun.com/jsf/facelets" - xmlns:p="http://primefaces.org/ui"> - -<!-- This component contains short code used for Google Analytics statistics. --> - -<script type="text/javascript"> - var googleAnalyticsId = "#{configurationMB.googleAnalyticsIdentifier}"; - - - //enable statistics only when there is identifier defined - if (googleAnalyticsId != "") { - var _gaq = _gaq || []; - _gaq.push(['_setAccount', googleAnalyticsId]); - _gaq.push(['_trackPageview']); - - (function() { - var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; - ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; - var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); - })(); - } -</script> - - -</html> diff --git a/web/src/main/webapp/WEB-INF/components/admin/template.xhtml b/web/src/main/webapp/WEB-INF/components/admin/template.xhtml deleted file mode 100644 index 97fa8b13c8ba36153db5cd88768cca71717a288f..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/WEB-INF/components/admin/template.xhtml +++ /dev/null @@ -1,48 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" -"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:p="http://primefaces.org/ui" - xmlns:ui="http://java.sun.com/jsf/facelets"> - - <h:head> - <link rel="shortcut icon" href="../resources/images/favicon.png" type="image/png" /> - - <ui:include src="/WEB-INF/components/admin/statistics.xhtml" /> - - <ui:insert name="css"></ui:insert> - - <title>#{mapMB.currentProject.name} - <ui:insert name="title">Default title</ui:insert></title> - - </h:head> - - <h:body> - <h:outputStylesheet library="css" name="style.css"/> - <h:outputStylesheet library="css" name="admin.css"/> - - <p:layout fullPage="true" resizeTitle="resize"> - <p:layoutUnit styleClass="layoutUnitCenter" position="center" border="0"> - - <!-- menu --> - <ui:include src="/WEB-INF/components/admin/menu.xhtml" /> - - <!-- content --> - <h:panelGroup layout="block" id="content" rendered="#{access}"> - <ui:insert name="content">Default content</ui:insert> - </h:panelGroup> - <h:panelGroup layout="block" id="no-content" rendered="#{not access}"> - <center><h1>Access denied</h1></center> - </h:panelGroup> - </p:layoutUnit> - - <p:layoutUnit position="south" resizable="true" id="south" size="95"> - <!-- footer --> - <ui:include src="/WEB-INF/components/admin/footer.xhtml" /> - </p:layoutUnit> - </p:layout> - - <div id="dialog"><ui:insert name="dialog"></ui:insert></div> - </h:body> -</html> 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/main/webapp/WEB-INF/web.xml b/web/src/main/webapp/WEB-INF/web.xml index 8bc3a2044e28e013e9031372d0425bdfd20f66c7..e5bdde9887143378115fb88f8aa02e458522cba8 100644 --- a/web/src/main/webapp/WEB-INF/web.xml +++ b/web/src/main/webapp/WEB-INF/web.xml @@ -185,6 +185,10 @@ <session-config> <session-timeout>120</session-timeout> <tracking-mode>COOKIE</tracking-mode> + <cookie-config> + <name>MINERVA_AUTH_TOKEN</name><!-- default is jsessionid --> + <http-only>false</http-only> + </cookie-config> </session-config> <filter> <filter-name>cssContentTypeFix</filter-name> diff --git a/web/src/main/webapp/admin.xhtml b/web/src/main/webapp/admin.xhtml index 1cce7a8d8dab8bd3fd6b3f74e7bdc15c959a8372..cb45340c660f3040f0d47f6f9cc75f7235142210 100644 --- a/web/src/main/webapp/admin.xhtml +++ b/web/src/main/webapp/admin.xhtml @@ -38,8 +38,10 @@ function initMap(){ return minerva.createAdmin({ element : element, }).then(function(result){ - customMap = result; - document.title = result.getProject().getName(); + if (result!==undefined) { + customMap = result; + document.title = result.getProject().getName(); + } }).catch(function(rejectReason){ minerva.GuiConnector.alert(rejectReason); }); diff --git a/web/src/main/webapp/admin/comments.xhtml b/web/src/main/webapp/admin/comments.xhtml deleted file mode 100644 index e589f05e12f83cfd2e8e3f1fcad12d856dd2eb43..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/admin/comments.xhtml +++ /dev/null @@ -1,72 +0,0 @@ -<ui:composition template="/WEB-INF/components/admin/template.xhtml" - xmlns="http://www.w3.org/1999/xhtml" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:p="http://primefaces.org/ui" - xmlns:cc="http://java.sun.com/jsf/composite/pfcomp" - xmlns:ui="http://java.sun.com/jsf/facelets"> - - <ui:define name="css"> - </ui:define> - - <ui:define name="title"> - Admin panel - Comments - </ui:define> - - <ui:param name="access" value="#{feedbackMB.userHasCommentPrivilege}"/> - - <ui:define name="content"> - - <h1>COMMENTS</h1> - - <h:form id="commentForm"> - <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> - - <p:panelGrid columns="2" style="width:100%;height:100%;" > - <p:dataTable id="commentsDataTable" var="comment" value="#{feedbackMB.commentList}" paginator="true" rows="20" styleClass="paginated" paginatorAlwaysVisible="false"> - <p:column sortBy="idObject" headerText="Id"> - <h:outputText id="commentId" value="#{comment.idObject}" /> - </p:column> - - <p:column sortBy="title" headerText="Title"> - <h:link value="#{comment.title}" - outcome="/index.xhtml?id=#{mapMB.currentMapId}&x=#{comment.xCoord}&y=#{comment.yCoord}&zoom=#{comment.zoom}&comments=on&submap=#{comment.submap}" - target="_map"/> - </p:column> - - <p:column sortBy="author" headerText="Author"> - <h:outputText value="#{comment.author}" /> - </p:column> - - <p:column sortBy="email" headerText="Email"> - <h:outputText value="#{comment.email}"/> - </p:column> - - <p:column sortBy="content" headerText="Content"> - <h:outputText value="#{comment.content}" /> - </p:column> - - <p:column sortBy="removed" headerText="Removed"> - <h:outputText value="#{comment.removed}"/> - <p:commandButton actionListener="#{feedbackMB.removeComment(comment)}" icon="ui-icon-closethick" update="commentsDataTable" rendered="#{comment.removed=='NO'}" value="remove"/> - </p:column> - - <p:column sortBy="pinned" headerText="Pinned"> - <h:outputText value="#{comment.pinned}"/> - </p:column> - </p:dataTable> - - <p:dataList value="#{projectMB.projects}" var="project" type="unordered" itemType="none" paginator="true" rows="10" styleClass="paginated" paginatorAlwaysVisible="false"> - <f:facet name="header"> - Projects - </f:facet> - <p:commandButton id="selectButton" icon="ui-icon-search" title="View" onclick="window.location.href='#{request.contextPath}/admin/comments.xhtml?id=#{project.projectId}';"/> - <h:link value="#{project.projectName} (#{project.projectId})" outcome="/index.xhtml?id=#{project.projectId}" target="_map_#{project.idObject}" style="#{project.projectId ==mapMB.currentMapId? 'background-color:#2DCAFF;':''}"/> - </p:dataList> - </p:panelGrid> - <center> - <p:commandButton id="refreshCommentButton" actionListener="#{feedbackMB.refreshCommentList}" icon="ui-icon-refresh" update="commentsDataTable"/> - </center> - </h:form> - </ui:define> -</ui:composition> diff --git a/web/src/main/webapp/admin/configuration.xhtml b/web/src/main/webapp/admin/configuration.xhtml deleted file mode 100644 index 7c63080fcaff4eed72e339864048b1951a29717f..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/admin/configuration.xhtml +++ /dev/null @@ -1,71 +0,0 @@ -<ui:composition template="/WEB-INF/components/admin/template.xhtml" - xmlns="http://www.w3.org/1999/xhtml" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:p="http://primefaces.org/ui" - xmlns:cc="http://java.sun.com/jsf/composite/pfcomp" - xmlns:ui="http://java.sun.com/jsf/facelets"> - - <ui:define name="css"> - </ui:define> - - <ui:define name="title"> - Admin panel - Configuration - </ui:define> - - <ui:param name="access" value="#{configurationMB.userHasConfigurationView}"/> - - <ui:define name="content"> - <cc:helpButton style="float:right" helpText='Configuration tab provides a summary of the current version of your MINERVA instance. Moreover, it allows privileged users to configure -global parameters of the MINERVA instance. More information can be found in the <a href="#{request.contextPath}/javax.faces.resource/admin_guide.pdf.xhtml?ln=other" target="_admin_manual_" >manual</a>.'/> - - <h1>CONFIGURATION</h1> - - <h:form id="configurationForm"> - <h:outputText value="System version: " class="text"/> - <h:outputText value="#{configurationMB.version.version}" class="text"/> - <br/> - <h:outputText value="Git build version: " /> - <h:outputText value="#{configurationMB.version.gitVersion}" class="bold"/> - <br/> - <h:outputText value="Build date: " /> - <h:outputText value="#{configurationMB.version.time}" class="bold"/> - <br/> - <br/> - <h:outputText value="PrimeFaces version: " /> - <h:outputText value="#{configurationMB.primefacesVersion}" class="bold"/> - <br/> - <br/> - <h:outputText value="Memory usage: " /> - <h:outputText value="#{configurationMB.memoryUsage}" class="bold"/> - <br/> - <h:outputText value="Max memory available: " /> - <h:outputText value="#{configurationMB.maxMemory}" class="bold"/> - <br/> - <br/> - - <h:outputText value="System parameters: " class="textLighter"/> - <p:dataTable id="configurationDataTable" var="configuration" value="#{configurationMB.values}"> - <p:column sortBy="idObject" headerText="Id"> - <h:outputText id="configurationId" value="#{configuration.idObject}" /> - </p:column> - - <p:column sortBy="title" headerText="Title"> - <h:outputText value="#{configuration.type.commonName}" /> - </p:column> - - <p:column sortBy="value" headerText="Value"> - <p:inputText value="#{configuration.value}" /> - <p:colorPicker value="#{configuration.value}" rendered="#{configuration.type.editType == 'COLOR'}"/> - </p:column> - - </p:dataTable> - <center> - <p:commandButton id="refreshConfigurationButton" actionListener="#{configurationMB.refreshValues}" - icon="ui-icon-refresh" update="configurationDataTable"/> - <p:commandButton id="saveConfigurationButton" actionListener="#{configurationMB.saveValues}" - icon="ui-icon-disk" update="configurationDataTable"/> - </center> - </h:form> - </ui:define> -</ui:composition> diff --git a/web/src/main/webapp/admin/genomes.xhtml b/web/src/main/webapp/admin/genomes.xhtml deleted file mode 100644 index ec62f1b842a6df3ee65848c6211d41732b525e32..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/admin/genomes.xhtml +++ /dev/null @@ -1,204 +0,0 @@ -<ui:composition template="/WEB-INF/components/admin/template.xhtml" - xmlns="http://www.w3.org/1999/xhtml" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:p="http://primefaces.org/ui" - xmlns:cc="http://java.sun.com/jsf/composite/pfcomp" - xmlns:ui="http://java.sun.com/jsf/facelets"> - - <ui:define name="css"> - <h:outputStylesheet library="css" name="genomes.css"/> - </ui:define> - - <ui:define name="title"> - Admin panel - Reference genomes - </ui:define> - - <ui:param name="access" value="#{referenceGenomeMB.userHasManageGenomesPrivilege}"/> - - <ui:define name="content"> - - <h1>Configured reference genomes</h1> - - <h:form id="genomesForm"> - <h:panelGroup layout="block" id="referenceGenomes"> - <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> - <p:dataTable id="referenceGenomesTable" var="genome" value="#{referenceGenomeMB.downloadedGenomes}"> - <p:column sortBy="name" headerText="Genome type"> - <h:outputText id="name" value="#{genome.type}" /> - </p:column> - - <p:column headerText="organism"> - <h:outputText id="organism" value="#{referenceGenomeMB.getOrganismName(genome.organism)}" /> - </p:column> - - <p:column headerText="version"> - <h:outputText id="version" value="#{genome.version}" /> - </p:column> - - <p:column headerText="progress"> - <h:outputText value="Downloading " rendered="#{genome.downloadProgress < 100.0}"/> - <h:outputText id="progressBar" value="#{genome.downloadProgress}" rendered="#{genome.downloadProgress < 100.0}"> - <f:convertNumber pattern="#0.00" /> - </h:outputText> - <h:outputText value="%" rendered="#{genome.downloadProgress < 100.0}"/> - <h:outputText id="progressReady" value="READY" rendered="#{genome.downloadProgress >= 100.0}" /> - </p:column> - - <p:column headerText="source"> - <h:outputText id="source" value="#{genome.sourceUrl}" /> - </p:column> - <p:column style="width:4%"> - <p:commandButton update=":#{p:component('genomeDlg')}" id="selectButton" oncomplete="PF('genomeDialog').show()" icon="ui-icon-search" title="View"> - <f:setPropertyActionListener value="#{genome}" target="#{referenceGenomeMB.editedReferenceGenome}" /> - </p:commandButton> - </p:column> - - </p:dataTable> - <center> - <p:commandButton id="refreshGenomesButton" actionListener="#{referenceGenomeMB.refreshDownloadedGenomes}" - icon="ui-icon-refresh" update="referenceGenomesTable"/> - </center> - </h:panelGroup> - </h:form> - - <h2>Add reference genome</h2> - <h:form id="addGenomeForm"> - <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> - <h:panelGrid id="addPanelGrid" columns="2" cellpadding="1"> - <h:outputText value="Type: " /> - <h:selectOneMenu value="#{referenceGenomeMB.selectedReferenceGenomeType}"> - <f:selectItems value="#{referenceGenomeMB.genomeTypes}" var="genome" - itemLabel="#{genome}" itemValue="#{genome}" /> - <f:ajax event="change" execute="@this" render="organismMenu"/> - <f:ajax event="change" execute="@this" render="versionMenu"/> - <f:ajax event="change" execute="@this" render="urlText"/> - </h:selectOneMenu> - - <h:outputText value="Organism: " /> - <h:selectOneMenu id="organismMenu" value="#{referenceGenomeMB.selectedOrganism}" - converter="miriamTypeConverter"> - <f:selectItems value="#{referenceGenomeMB.availableOrganisms}" var="organism" - itemLabel="#{referenceGenomeMB.getOrganismName(organism)}" itemValue="#{organism}" /> - <f:ajax event="change" execute="@this" render="versionMenu"/> - <f:ajax event="change" execute="@this" render="urlText"/> - </h:selectOneMenu> - - <h:outputText value="Version: " /> - <h:selectOneMenu id="versionMenu" value="#{referenceGenomeMB.selectedVersion}"> - <f:selectItems value="#{referenceGenomeMB.availableVersions}" var="version" - itemLabel="#{version}" itemValue="#{version}" /> - <f:ajax event="change" execute="@this" render="urlText"/> - </h:selectOneMenu> - - <h:outputText value="Url to file (2bit): " /> - <p:inputText id="urlText" value="#{referenceGenomeMB.selectedUrl}" style="width:400px !important;" /> - </h:panelGrid> - <center> - <p:commandButton id="downloadGenomeButton" actionListener="#{referenceGenomeMB.downloadGenome}" value="Download" update=":genomesForm:referenceGenomesTable" - icon="ui-icon-save" /> - </center> - </h:form> - -</ui:define> -<ui:define name="dialog"> - -<h:form id="genomeDetailForm"> - <p:dialog header="Genome Detail" widgetVar="genomeDialog" resizable="false" id="genomeDlg" - showEffect="fade" modal="true"> - <p:tabView id="genomeDetailPanel"> - <p:tab title="General"> - <p:panelGrid columns="2"> - <h:outputText value="Type:" /> - <p:inputText value="#{referenceGenomeMB.editedReferenceGenome.type}" - readonly="true" styleClass="genomeValueField"/> - - <h:outputText value="Organism:" /> - <p:inputText value="#{referenceGenomeMB.getOrganismName(referenceGenomeMB.editedReferenceGenome.organism)}" - readonly="true" styleClass="genomeValueField"/> - - <h:outputText value="Version: " /> - <p:inputText value="#{referenceGenomeMB.editedReferenceGenome.version}" - readonly="true" styleClass="genomeValueField" /> - - <h:outputText value="Url to file:" /> - <p:inputText value="#{referenceGenomeMB.editedReferenceGenome.sourceUrl}" - readonly="true" styleClass="genomeValueField" style="width:400px !important;"/> - - </p:panelGrid> - - <p:separator /> - - <p:commandButton update=":#{p:component('referenceGenomesTable')}" - actionListener="#{referenceGenomeMB.removeGenome(referenceGenomeMB.editedReferenceGenome)}" - id="removeButton" oncomplete="PF('genometDialog').hide()" icon="ui-icon-trash" value="Remove" - title="Remove"/> - <p:commandButton update=":#{p:component('referenceGenomesTable')}" id="cancelButton" - oncomplete="PF('genomeDialog').hide()" icon="ui-icon-close" value="Cancel" title="Cancel"/> - - </p:tab> - - <p:tab id="layoutTab" title="Gene mapping"> - - <p:dataTable id="geneMappingDataTable" var="geneMapping" value="#{referenceGenomeMB.editedReferenceGenome.geneMapping}" - rows="10" - paginator="true" - paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"> - <p:column sortBy="name" headerText="Name"> - <p:inputText value="#{geneMapping.name}" readonly="true" /> - </p:column> - - <p:column sortBy="sourceUrl" headerText="Source"> - <p:inputText value="#{geneMapping.sourceUrl}" readonly="true" /> - </p:column> - - <p:column sortBy="downloadProgress" headerText="Progress"> - <h:outputText value="Downloading " rendered="#{geneMapping.downloadProgress < 100.0}"/> - <h:outputText id="progressBar" value="#{geneMapping.downloadProgress}" rendered="#{geneMapping.downloadProgress < 100.0}"> - <f:convertNumber pattern="#0.00" /> - </h:outputText> - <h:outputText value="%" rendered="#{geneMapping.downloadProgress < 100.0}"/> - <h:outputText id="progressReady" value="READY" rendered="#{geneMapping.downloadProgress >= 100.0}" /> - </p:column> - - <p:column headerText="Remove"> - <p:commandButton update="geneMappingDataTable" actionListener="#{referenceGenomeMB.removeGeneMapping(geneMapping)}" id="removeGeneMappingButton" icon="ui-icon-trash"/> - </p:column> - - </p:dataTable> - - <p:separator /> - <p:commandButton value="Add gene mapping" id="openAddGeneMapingButton" update=":#{p:component('geneMappingDlg')}" oncomplete="PF('geneMappingDialog').show()"/> - - </p:tab> - </p:tabView> - - </p:dialog> -</h:form> - -<h:form id="addGeneMappingForm"> - <p:dialog header="Add gene mapping" widgetVar="geneMappingDialog" resizable="false" id="geneMappingDlg" - showEffect="fade" modal="true" > - - <p:panelGrid id="layoutDataTable" columns="2"> - - <h:outputText value="Name" /> - <p:inputText value="#{referenceGenomeMB.selectedReferenceGenomeGeneMappingName}" /> - - <h:outputText value="File (url)" /> - <p:inputText value="#{referenceGenomeMB.selectedReferenceGenomeGeneMappingUrl}" /> - - </p:panelGrid> - <center> - <p:commandButton id="addLayoutButton" - actionListener="#{referenceGenomeMB.addGeneMapping(referenceGenomeMB.editedReferenceGenome)}" - update=":genomeDetailForm:genomeDetailPanel:geneMappingDataTable" icon="ui-icon-disk" - value="Save" title="Save" onclick="PF('geneMappingDialog').hide();"/> - </center> - </p:dialog> - -</h:form> - - - </ui:define> -</ui:composition> diff --git a/web/src/main/webapp/admin/miriam.xhtml b/web/src/main/webapp/admin/miriam.xhtml deleted file mode 100644 index f0083da89bff529d19180d9ecd40a06d37d1046b..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/admin/miriam.xhtml +++ /dev/null @@ -1,48 +0,0 @@ -<ui:composition template="/WEB-INF/components/admin/template.xhtml" - xmlns="http://www.w3.org/1999/xhtml" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:p="http://primefaces.org/ui" - xmlns:cc="http://java.sun.com/jsf/composite/pfcomp" - xmlns:ui="http://java.sun.com/jsf/facelets"> - - <ui:define name="css"> - </ui:define> - - <ui:define name="title"> - Admin panel - Miriam - </ui:define> - - <ui:param name="access" value="true"/> - - <ui:define name="content"> - - <cc:helpButton style="float:right" helpText='The MIRIAM panel lists all MIRIAM-supported resources (<a href="http://www.ebi.ac.uk/miriam/main/mdb?section=intro" target="_miriam_" >http://www.ebi.ac.uk/miriam/main/mdb?section=intro</a>) currently handled by MINERVA platform as shown in the figure below. More information can be found in the <a href="#{request.contextPath}/javax.faces.resource/admin_guide.pdf.xhtml?ln=other" target="_admin_manual_" >manual</a>.'/> - - <h1>MIRIAM</h1> - - <h:form id="miriamForm"> - <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> - - <h:outputText value="Supported Miriam types: " class="textLighter"/> - <p:dataTable id="miriamDataTable" var="type" value="#{miriamMB.miriamTypes}"> - <p:column sortBy="commonName" headerText="Annotation type"> - <a target="_blank" href="#{type.dbHomepage}"><h:outputText value="#{type.commonName}" /></a> - </p:column> - <p:column sortBy="registryIdentifier" headerText="Miriam identifier"> - <a target="_blank" href="http://www.ebi.ac.uk/miriam/main/collections/#{type.registryIdentifier}"><h:outputText value="#{type.registryIdentifier}" /></a> - </p:column> - <p:column headerText="Valid for elements:"> - <p:dataList value="#{type.validClass}" var="classEl"> - #{classEl.simpleName=="Object" ? "All": (classEl.simpleName=="ComplexSpecies" ? "Complex" : classEl.simpleName)} - </p:dataList> - </p:column> - <p:column headerText="Valid uri:"> - <p:dataList value="#{type.uris}" var="uri" > - #{uri} - </p:dataList> - </p:column> - </p:dataTable> - </h:form> - </ui:define> -</ui:composition> diff --git a/web/src/main/webapp/admin/projects.xhtml b/web/src/main/webapp/admin/projects.xhtml deleted file mode 100644 index 8c93d1fcc294a24d42682f9cd49799e119768fc4..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/admin/projects.xhtml +++ /dev/null @@ -1,574 +0,0 @@ -<ui:composition template="/WEB-INF/components/admin/template.xhtml" - xmlns="http://www.w3.org/1999/xhtml" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:p="http://primefaces.org/ui" - xmlns:cc="http://java.sun.com/jsf/composite/pfcomp" - xmlns:ui="http://java.sun.com/jsf/facelets"> - - <ui:define name="css"> - <h:outputStylesheet library="css" name="projects.css"/> - </ui:define> - - <ui:define name="title"> - Admin panel - Projects - </ui:define> - - <ui:param name="access" value="#{projectMB.userHasManagePrivileges}"/> - - <ui:define name="content"> - - <h1>PROJECTS</h1> - - <h:form id="projectForm"> - <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> - <p:commandButton value="Add project" title="Add project" id="openAddProjectButton" - update=":#{p:component('addProjectDlg')}" oncomplete="PF('addProjectDialog').show()" - disabled="#{not projectMB.userHasAddMapPrivileges}" styleClass="addButton"/> - <p:separator /> - - <p:dataTable id="projectDataTable" var="project" value="#{projectMB.projects}" > - <p:column sortBy="projectId" headerText="ProjectId"> - <h:link value="#{project.projectId}" outcome="/index.xhtml?id=#{project.projectId}" target="_map_#{project.idObject}"/> - </p:column> - - <p:column sortBy="projectName" headerText="Name"> - <h:outputText value="#{project.projectName}" /> - </p:column> - - <p:column sortBy="projectDisease" headerText="Disease"> - <cc:annotation element="#{project.projectDiseaseLink}" showDbName="false"/> - </p:column> - - <p:column sortBy="organismLink" headerText="Organism"> - <cc:annotation element="#{project.organismLink}"/> - </p:column> - - <p:column sortBy="status" headerText="Status"> - <h:outputText value="#{project.status}" /> - <h:outputText value=" (#{project.progress}%)" /> - - <p:commandLink update=":#{p:component('warningsDlg')}" - id="warningButton" oncomplete="PF('warningsDialog').show()" - title="#{project.warningsPreview}" - rendered="#{not empty project.warnings}" > - <h:graphicImage library="images" name="icons/warning.png" width="24px" class="imgMiddle" /> - <f:setPropertyActionListener value="#{project}" target="#{projectMB.selectedProject}" /> - </p:commandLink > - - <p:commandLink update=":#{p:component('errorDlg')}" - id="errorButton" oncomplete="PF('errorDialog').show()" - title="#{project.errors}" - rendered="#{not empty project.errors}" > - <h:graphicImage library="images" name="icons/error.png" width="24px" class="imgMiddle" /> - <f:setPropertyActionListener value="#{project}" target="#{projectMB.selectedProject}" /> - </p:commandLink > - </p:column> - <p:column style="width:4%"> - <p:commandButton update=":#{p:component('projectDlg')}" id="selectButton" oncomplete="PF('projectDialog').show()" icon="ui-icon-search" title="View"> - <f:setPropertyActionListener value="#{project}" target="#{projectMB.selectedProject}" /> - </p:commandButton> - <!-- if the last element in the list is not ok then we will try to refresh the list every 3 seconds --> - <h:panelGroup layout="block" rendered ="#{(project.idObject==projectMB.projects[projectMB.projects.size()-1].idObject) && (project.status !='Ok')}"> - <p:poll listener="#{projectMB.refreshProjectList(null)}" interval="3" update="projectDataTable"/> - </h:panelGroup> - </p:column> - </p:dataTable> - <center> - <p:commandButton id="refreshProjectsButton" - actionListener="#{projectMB.refreshProjectList}" icon="ui-icon-refresh" update="projectDataTable"> - </p:commandButton> - </center> - </h:form> - </ui:define> - <ui:define name="dialog"> - <h:form> - <p:dialog header="Warnings" widgetVar="warningsDialog" id="warningsDlg" modal="true"> - <p:dataTable binding="#{table}" id="warningDataTable" var="warning" - value="#{projectMB.selectedProject.warnings}" paginator="true" rows="20" > - <p:column headerText="No"> - <h:outputText value="#{table.rowIndex + SessionsController.firstRow + 1}" /> - </p:column> - <p:column headerText="Content"> - <h:outputText value="#{warning}" /> - </p:column> - </p:dataTable> - <h:commandButton action="#{projectMB.downloadWarnings}" value="Download"/> - </p:dialog> - - <p:dialog header="Error" widgetVar="errorDialog" id="errorDlg" modal="true"> - <h:outputText value="#{projectMB.selectedProject.errors}" /> - </p:dialog> - </h:form> - -<h:form id="addProjectForm" > - <p:dialog header="Add project" widgetVar="addProjectDialog" resizable="false" id="addProjectDlg" showEffect="fade" modal="true" height="500px"> - <h:panelGrid id="addPanelGrid" columns="3" cellpadding="1"> - <h:outputText value="File: " /> - <p:fileUpload fileUploadListener="#{projectMB.handleFileUpload}" mode="advanced" auto="true" allowTypes="/(\.|\/)(sbgn|xml|zip)$/" onstart="document.getElementById('addProjectForm:addProjectDlg').style.maxWidth=document.getElementById('addProjectForm:addProjectDlg').style.width;document.getElementById('addProjectForm:addProjectDlg').style.height= document.getElementById('addProjectForm:addProjectDlg').style.clientWidth;" - update=" submodels,layouts,dataMining,images,projectId, projectName, addPanelGrid"/> - <cc:helpButton helpText='File with the map. For a quick start, CellDesigner files are accepted directly. Available options and -configurations of the source file are discussed in <a href="#{request.contextPath}/javax.faces.resource/admin_guide.pdf.xhtml?ln=other" target="_admin_manual_" >manual</a>.'/> - - <h:outputText value="ProjectId: " /> - <p:inputText id="projectId" value="#{projectMB.newProjectId}" /> - <cc:helpButton helpText="A working name of the uploaded project on the MINERVA platform. Unique in the platform."/> - - <h:outputText value="Project name: " /> - <p:inputText id="projectName" value="#{projectMB.newProjectName}" /> - <cc:helpButton helpText="The name of the uploaded project displayed in the top left corner of the Admin and User panels; your official name of the project."/> - - <h:outputText value="Project Disease: " /> - <p:inputText id="projectDisease" - value="#{projectMB.newProjectDisease}" /> - <cc:helpButton helpText="Mesh ID identifying disease connected to this map (ie. for Parkinson's Disease it would be D010300)"/> - - <h:outputText value="Organism: " /> - <p:inputText id="organism" - value="#{projectMB.newProjectOrganism}" /> - <cc:helpButton helpText="Taxonomy ID identifying organism for which project is dedicated (ie. for Human map it would be 9606)"/> - - <h:outputText value="Complex: " /> - <p:dataTable id="submodels" var="submodel" value="#{projectMB.modelZipEntries}" editable="true" editMode="cell" widgetVar="cellSubmodels"> - <p:column headerText="Filename"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{submodel.filename}" /></f:facet> - <f:facet name="input"><p:inputText id="modelInput" value="#{submodel.filename}" style="width:96%" readonly="true"/></f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Name"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{submodel.name}" /></f:facet> - <f:facet name="input"><p:inputText value="#{submodel.name}" style="width:96%" label="Name"/></f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Root model"> - <p:cellEditor> - <f:facet name="output"><h:selectBooleanCheckbox value="#{submodel.root}" onclick="return false;" style="width:96%" label="Root model" readonly="true"/></f:facet> - <f:facet name="input"> - <h:inputHidden value="#{submodel.root}" /> - <h:selectBooleanCheckbox value="#{submodel.root}" onclick="$(this).prev().val(this.checked)" style="width:96%" /> - </f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Mapping file"> - <p:cellEditor> - <f:facet name="output"><h:selectBooleanCheckbox value="#{submodel.mapping}" onclick="return false;" style="width:96%" label="Root model" readonly="true"/></f:facet> - <f:facet name="input"> - <h:inputHidden value="#{submodel.mapping}" /> - <h:selectBooleanCheckbox value="#{submodel.mapping}" onclick="$(this).prev().val(this.checked)" style="width:96%" /> - </f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Model type"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{submodel.type}" /></f:facet> - <f:facet name="input"> - <h:selectOneMenu value="#{submodel.type}" style="width:100%"> - <f:selectItems value="#{projectMB.submodelTypes}" itemLabel="#{commonName}" itemValue="#{commonName}" /> - </h:selectOneMenu> - </f:facet> - </p:cellEditor> - </p:column> - <p:column headerText="File type"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{submodel.fileType.commonName}" /></f:facet> - <f:facet name="input"> - <h:selectOneMenu value="#{submodel.fileType}" style="width:100%"> - <f:selectItems value="#{projectMB.fileTypes}" var="typeObject" itemLabel="#{typeObject.commonName}" itemValue="#{typeObject}" /> - </h:selectOneMenu> - </f:facet> - </p:cellEditor> - </p:column> - </p:dataTable> - <cc:helpButton helpText='This section describes how main map and uploaded submaps (if any) are related. For more details refer to the <a href="#{request.contextPath}/javax.faces.resource/admin_guide.pdf.xhtml?ln=other" target="_admin_manual_" >manual</a>.'/> - - <h:outputText value="Additional overlays: " /> - <p:dataTable id="layouts" var="layout" value="#{projectMB.layoutZipEntries}" editable="true" editMode="cell" widgetVar="cellLayouts"> - <p:column headerText="Filename"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{layout.filename}" /></f:facet> - <f:facet name="input"><p:inputText id="modelInput" value="#{layout.filename}" style="width:96%" readonly="true"/></f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Name"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{layout.name}" /></f:facet> - <f:facet name="input"><p:inputText value="#{layout.name}" style="width:96%" label="Name"/></f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Description"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{layout.description}" /></f:facet> - <f:facet name="input"><p:inputText value="#{layout.description}" style="width:96%" label="Description"/></f:facet> - </p:cellEditor> - </p:column> - </p:dataTable> - <div/> - - <h:outputText value="Data mining: " /> - <p:dataTable id="dataMining" var="dm" value="#{projectMB.dataMiningZipEntries}" editable="true" editMode="cell" widgetVar="cellDataMining"> - <p:column headerText="Filename"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{dm.filename}" /></f:facet> - <f:facet name="input"><p:inputText id="modelInput" value="#{dm.filename}" style="width:96%" readonly="true"/></f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Name"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{dm.name}" /></f:facet> - <f:facet name="input"><p:inputText value="#{dm.name}" style="width:96%" label="Name"/></f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Description"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{dm.description}" /></f:facet> - <f:facet name="input"><p:inputText value="#{dm.description}" style="width:96%" label="Description"/></f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Source"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{dm.source}" /></f:facet> - <f:facet name="input"><p:inputText value="#{dm.source}" style="width:96%" label="Name"/></f:facet> - </p:cellEditor> - </p:column> - - <p:column headerText="Type"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{dm.type}" /></f:facet> - <f:facet name="input"> - <h:selectOneMenu value="#{dm.type}" style="width:100%"> - <f:selectItems value="#{missingConnectionMB.dataMiningTypes}"/> - </h:selectOneMenu> - </f:facet> - </p:cellEditor> - </p:column> - - </p:dataTable> - <cc:helpButton helpText='This section describes uploaded additional overlays. For more details refer to the <a href="#{request.contextPath}/javax.faces.resource/admin_guide.pdf.xhtml?ln=other" target="_admin_manual_" >manual</a>.'/> - - <h:outputText value="Overview images: " /> - <p:dataTable id="images" var="image" value="#{projectMB.imageZipEntries}" editable="true" editMode="cell" widgetVar="cellImages"> - <p:column headerText="Filename"> - <p:cellEditor> - <f:facet name="output"><h:outputText value="#{image.filename}" /></f:facet> - <f:facet name="input"><p:inputText id="modelInput" value="#{image.filename}" style="width:96%" readonly="true"/></f:facet> - </p:cellEditor> - </p:column> - </p:dataTable> - <cc:helpButton helpText='This section describes uploaded overview images and their configuration file. For more details refer to the <a href="#{request.contextPath}/javax.faces.resource/admin_guide.pdf.xhtml?ln=other" target="_admin_manual_" >manual</a>.'/> - - <h:outputText value="Version: " /> - <p:inputText value="#{projectMB.newMapVersion}" /> - <cc:helpButton helpText='A text field displayed next to the name of your project in the User panel.'/> - - <h:outputText value="Annotate model automatically: " /> - <h:panelGroup layout="block"> - <p:selectBooleanCheckbox value="#{projectMB.annotateModel}" styleClass="projectsAdvancedCheckbox"/> - <h:outputText value=" " /> - <p:commandButton value="Advanced" oncomplete="PF('annotatorDialog').show()" title="Advanced options"/> - </h:panelGroup> - <cc:helpButton helpText='If this checkbox is checked, elements of the uploaded map will be automatically annotated using built in annotators. Behavior of the annotators can be configured by clicking the Advanced button.'/> - - <h:outputText value="Verify manual annotations: " /> - <h:panelGroup layout="block"> - <p:selectBooleanCheckbox value="#{projectMB.verifyAnnotationsModel}" styleClass="projectsAdvancedCheckbox"/> - <h:outputText value=" " /> - <p:commandButton value="Advanced" oncomplete="PF('miriamDialog').show()" title="Advanced options"/> - </h:panelGroup> - <cc:helpButton helpText='If this checkbox is checked, elements and interactions of the uploaded map will be scanned for existing annotations; if present these existing annotations will be validated against a set of rules. Verification rules can be configured by clicking the Advanced button.'/> - - <h:outputText value="Cache data: " /> - <p:selectBooleanCheckbox value="#{projectMB.cacheModel}"/> - <cc:helpButton helpText='If this checkbox is checked, all hyperlinks in the project resolved by MIRIAM repository (e.g. cross-links to external bioinformatic databases) are resolved and cached'/> - - <h:outputText value="Auto margin: " /> - <p:selectBooleanCheckbox value="#{projectMB.newMapAutoResize}"/> - <cc:helpButton helpText='If this checkbox is checked, upon generation of the graphics, empty spaces surrounding elements and interactions will be cropped'/> - - <h:outputText value="Display as SBGN: " /> - <p:selectBooleanCheckbox value="#{projectMB.sbgnFormat}" /> - <cc:helpButton helpText='If this checkbox is checked, the uploaded model will be displayed in SBGN format, instead of default CellDesigner format.'/> - - <h:outputText value="Default network overlay: " /> - <p:selectBooleanCheckbox value="#{projectMB.networkLayoutAsDefault}" /> - <cc:helpButton helpText='If this checkbox is checked, the default overlay in User panel will present pure network. If the checkbox is unchecked then default overlay will present pathways and compartments view.'/> - - <h:outputText value="Semantic zooming: " /> - <p:selectBooleanCheckbox value="#{projectMB.semanticOverlay}" /> - <div/> - - </h:panelGrid> - <center> - <p:commandButton value="Submit" icon="ui-icon-disk" actionListener="#{projectMB.createProject}" onclick="PF('addProjectDialog').hide();" update=":projectForm:projectDataTable"/> - <p:commandButton value="Cancel" icon="ui-icon-close" onclick="PF('addProjectDialog').hide();"/> - </center> - </p:dialog> - -</h:form> -<h:form id="projectDetailForm"> - <p:dialog header="Project Detail" widgetVar="projectDialog" resizable="false" id="projectDlg" - showEffect="fade" modal="true"> - <p:tabView id="projectDetailPanel"> - <p:tab title="General"> - <p:panelGrid columns="2"> - <h:outputText value="ProjectId:" /> - <p:inputText value="#{projectMB.selectedProject.projectId}" readonly="true" styleClass="projectValueField"/> - - <h:outputText value="Name:" /> - <p:inputText value="#{projectMB.selectedProject.projectName}" styleClass="bold"/> - - <h:outputText value="Disease: " /> - <p:inputText value="#{projectMB.selectedProject.newDiseaseName}" - styleClass="bold" /> - - <h:outputText value="Organism: " /> - <p:inputText value="#{projectMB.selectedProject.newOrganismName}" - styleClass="bold" /> - - <h:outputText value="Version:" /> - <p:inputText value="#{projectMB.selectedProject.version}" styleClass="bold"/> - - <h:outputText value="Description:" /> - <p:inputText value="#{projectMB.selectedProject.description}" styleClass="bold"/> - - <h:outputText value="Notify email:" /> - <p:inputText value="#{projectMB.selectedProject.notifyEmail}" styleClass="bold"/> - </p:panelGrid> - - <p:separator /> - <p:commandButton update=":#{p:component('projectDataTable')}" actionListener="#{projectMB.updateSelectedProject}" id="saveButton" oncomplete="PF('projectDialog').hide()" icon="ui-icon-disk" value="Save" title="Save"/> - <p:commandButton update=":#{p:component('projectDataTable')}" actionListener="#{projectMB.removeSelectedProject}" id="removeButton" oncomplete="PF('projectDialog').hide()" icon="ui-icon-trash" value="Remove" title="Remove"/> - <p:commandButton update=":#{p:component('projectDataTable')}" id="cancelButton" oncomplete="PF('projectDialog').hide()" icon="ui-icon-close" value="Cancel" title="Cancel"/> - - </p:tab> - - <p:tab id="layoutTab" title="Overlays"> - - <p:dataTable id="layoutDataTable" var="layout" value="#{projectMB.selectedProject.layouts}" - rows="10" - paginator="true" - paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"> - <p:column sortBy="name" headerText="Name"> - <p:inputText value="#{layout.name}" /> - </p:column> - - <p:column sortBy="directory" headerText="Directory"> - <p:inputText value="#{layout.directory}" /> - </p:column> - - <p:column sortBy="description" headerText="Description"> - <p:inputTextarea value="#{layout.description}" /> - </p:column> - - <p:column sortBy="creator" headerText="Owner"> - <h:selectOneMenu value="#{layout.creator}"> - - <!-- for not defined user --> - <f:selectItem itemLabel="N/A" itemValue="" /> - - <f:selectItems value="#{usersMB.userList}" var="user" - itemLabel="#{user.name} #{user.surname}" itemValue="#{user.name} #{user.surname}" /> - </h:selectOneMenu> - </p:column> - - <p:column headerText="Data"> - <p:commandButton id="downloadLayoutButton" actionListener="#{layoutMB.downloadInputData(layout)}" icon="ui-icon-arrowthickstop-1-s" title='#{layout.inputDataAvailable?"":"Not available"}' disabled="#{not layout.inputDataAvailable}" ajax="false"/> - </p:column> - <p:column headerText="Update"> - <p:commandButton update=":#{p:component('layoutDataTable')}" actionListener="#{layoutMB.updateLayout(layout)}" id="updateLayoutButton" icon="ui-icon-disk"/> - </p:column> - <p:column headerText="Remove"> - <p:commandButton update=":#{p:component('layoutDataTable')}" actionListener="#{layoutMB.removeLayout(layout)}" id="removeLayoutButton" icon="ui-icon-trash"/> - </p:column> - - </p:dataTable> - - <p:separator /> - <p:commandButton value="Add overlay" id="openAddProjectButton" update=":#{p:component('layoutDlg')}" oncomplete="PF('layoutDialog').show()"/> - </p:tab> - - <p:tab id="dmTab" title="Data mining"> - - <p:dataTable id="dmDataTable" var="dataMiningSet" value="#{projectMB.selectedProject.dataMiningSets}"> - <p:column sortBy="name" headerText="Name"> - <h:outputText value="#{dataMiningSet.name}" /> - </p:column> - - <p:column sortBy="description" headerText="Description"> - <h:outputText value="#{dataMiningSet.description}" /> - </p:column> - - <p:column sortBy="source" headerText="Source"> - <h:outputLink value="#{dataMiningSet.source}" target="_dms_#{dataMiningSet.idObject}">#{dataMiningSet.source}</h:outputLink> - </p:column> - - <p:column sortBy="type" headerText="Type"> - <h:outputText value="#{dataMiningSet.type.commonName}" /> - </p:column> - - <p:column headerText="Data"> - <p:commandButton id="downloadDataMiningButton" actionListener="#{missingConnectionMB.downloadInputData(dataMiningSet)}" icon="ui-icon-arrowthickstop-1-s" ajax="false"/> - </p:column> - </p:dataTable> - </p:tab> - - <p:tab id="userTab" title="Users"> - <h:panelGroup layout="block" id="userComponent"> - <p:dataTable id="userDataTable" var="user" value="#{usersMB.userList}" - rows="10" - paginator="true" - paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"> - <p:column headerText="User"> - <h:outputText value="#{user.surname} #{user.name} (#{user.login})" /> - </p:column> - - <p:columns value="#{usersMB.projectPrivilegeTypes}" var="privilegeType" headerText="#{privilegeType.commonName}"> - <p:selectBooleanCheckbox value="#{user.getProjectPrivilegeByProjectId(projectMB.selectedProject.idObject).getProjectPrivilegeByPrivilegeType(privilegeType).selected}" styleClass="projectsAdvancedCheckbox"/> - </p:columns> - - </p:dataTable> - <p:commandButton value="Update privileges" id="updatePrivilegesButton" update="userDataTable" - actionListener="#{usersMB.updateUsers(usersMB.userList)}" - onclick="PF('updatingDlg').show();" oncomplete="PF('updatingDlg').hide();" onsuccess="PF('confirmDlg').show();" onerror="PF('errorDlg').show();" - /> - </h:panelGroup> - </p:tab> - </p:tabView> - - </p:dialog> - - <p:dialog header="Updating" widgetVar="updatingDlg" resizable="false" id="updatingDlg" - showEffect="fade" modal="true" closable="false"> - <p:graphicImage library="images" name="icons/ajax-loader.gif"/> - </p:dialog> - - <p:dialog header="Message" widgetVar="confirmDlg" id="confirmDialog" resizable="false" - showEffect="fade" modal="true" closable="true"> - <h:outputText id="messageText" value="Data updated successfully."/> - </p:dialog> - - <p:dialog header="Error" widgetVar="errorDlg" id="errorDialog" resizable="false" - showEffect="fade" modal="true" closable="true"> - <h:outputText id="errorMessageText" value="Unexpected error. More info in logs."/> - </p:dialog> -</h:form> - -<h:form id="annotationForm"> - <p:dialog header="Annotators Detail" widgetVar="annotatorDialog" resizable="false" id="annotatorDlg" - showEffect="fade" modal="true"> - <cc:helpButton style="float:right" helpText='By clicking on each element type (Object annotators) in the left panel, an annotator can be assigned in the right panel that will attempt to automatically retrieve information from external bioinformatic databases for each relevant element, and annotate them. There are a number annotators available, utilizing either the name, or existing identifier of an object.'/> - <h:panelGrid columns="2" cellpadding="1" columnClasses="projectsAnnotatorGridFirstColumn,projectsAnnotatorGridSecondColumn"> - - <p:treeTable value="#{projectMB.annotatorsTree}" var="row" scrollable="true" scrollHeight="520"> - <p:column headerText="Object Annotators"> - <p:commandLink update=":annotationForm:pickList,:annotationForm:pickListTitle"> - <f:setPropertyActionListener value="#{row}" target="#{projectMB.selectedAnnotatorTreeNodeData}" /> - <h:outputText value="#{row.name}" /> - <h:outputText value=" (#{row.validAnnotators.size()+row.usedAnnotators.size()})" rendered="#{row.validAnnotators.size()+row.usedAnnotators.size()>0}"/> - </p:commandLink> - </p:column> - </p:treeTable> - - <h:panelGroup layout="block" styleClass="projectsAnnotatorGrid" class="projectsAnnotatorGrid"> - <h:outputText id="pickListTitle" class="projectsAnnotatorCaption" value="#{projectMB.selectedAnnotatorTreeNodeData.name} annotators:"/> - - <p:pickList id="pickList" value="#{projectMB.annotators}" var="annotators" itemLabel="#{annotators}" itemValue="#{annotators}" > - <f:facet name="sourceCaption">Available</f:facet> - <f:facet name="targetCaption">In use</f:facet> - - <p:ajax event="transfer" listener="#{projectMB.onTransfer}" /> - - </p:pickList> - </h:panelGroup> - - </h:panelGrid> - - </p:dialog> - -</h:form> - -<h:form id="validationForm"> - <p:dialog header="Miriam validation detail" widgetVar="miriamDialog" resizable="false" id="miriamDlg" - showEffect="fade" modal="true" > - <h:panelGrid columns="2" cellpadding="1" columnClasses="projectsAnnotatorGridFirstColumn,projectsAnnotatorGridSecondColumn"> - - <p:treeTable value="#{projectMB.annotatorsTree}" var="row" scrollable="true" scrollHeight="520"> - <p:column headerText="Classes" style="width:200px;"> - <p:commandLink update=":validationForm:data"> - <f:setPropertyActionListener value="#{row}" target="#{projectMB.selectedAnnotatorTreeNodeData}" /> - <h:outputText value="#{row.name}" /> - </p:commandLink> - </p:column> - </p:treeTable> - - <h:panelGroup id="data" layout="block" styleClass="projectsAnnotatorGrid" class="projectsAnnotatorGrid"> - <h:outputText id="pickListTitle" class="projectsAnnotatorCaption" value="#{projectMB.selectedAnnotatorTreeNodeData.name}"/> - <br/> - <h:panelGroup layout="block"> - <h:outputText class="projectsAnnotatorSubtitle" value="Annotations to be considered as valid:"/> - <cc:helpButton style="float:right" helpText='By clicking on each element or interaction type (Classes) in the left panel a list of valid MIRIAM identifiers can be assigned. All elements or interactions in the uploaded model, annotated with an identifier outside of the **Valid** list will be flagged as warnings.'/> - </h:panelGroup> - - <p:pickList value="#{projectMB.validMiriam}" var="miriam" itemLabel="#{miriam.commonName}" itemValue="#{miriam}" converter="miriamTypeConverter"> - <f:facet name="sourceCaption">Available</f:facet> - <f:facet name="targetCaption">Valid</f:facet> - - <p:ajax event="transfer" listener="#{projectMB.onTransfer}" /> - - </p:pickList> - - <h:panelGroup layout="block"> - <p:selectBooleanCheckbox value="#{projectMB.selectedAnnotatorTreeNodeData.require}" styleClass="projectsAdvancedCheckbox"/> - <h:outputText class="projectsAnnotatorSubtitle" value="One of these miriam should be required:"/> - <cc:helpButton style="float:right" helpText='By clicking on each element or interaction type (Classes) in the left panel a list of mandatory MIRIAM identifiers can be assigned. If checkbox **Require annotations** is checked, all elements or interactions in the uploaded model, annotated without at least one identifier marked as **Required** list will be flagged as warnings.'/> - </h:panelGroup> - <br/> - - <p:pickList value="#{projectMB.requiredMiriam}" var="miriam" itemLabel="#{miriam.commonName}" itemValue="#{miriam}" converter="miriamTypeConverter" > - <f:facet name="sourceCaption">Available</f:facet> - <f:facet name="targetCaption">Required</f:facet> - - <p:ajax event="transfer" listener="#{projectMB.onTransfer}" /> - - </p:pickList> - </h:panelGroup> - - </h:panelGrid> - - </p:dialog> - -</h:form> - -<h:form id="addLayoutProjectForm5"> - <p:dialog header="Add overlay" widgetVar="layoutDialog" resizable="false" id="layoutDlg" - showEffect="fade" modal="true" > - - <p:panelGrid id="layoutDataTable" columns="2"> - - <h:outputText value="Name" /> - <p:inputText value="#{layoutMB.layoutName}" /> - - <h:outputText value="File" /> - <p:fileUpload fileUploadListener="#{layoutMB.handleFileUpload}" mode="advanced" auto="true" /> - - </p:panelGrid> - <center> - <p:commandButton id="addLayoutButton" actionListener="#{layoutMB.addAnonymousLayout(projectMB.selectedProject)}" update=":projectDetailForm:projectDetailPanel" icon="ui-icon-disk" disabled="#{not layoutMB.userHasAddLayoutPrivilege}" value="Generate" title="Generate" onclick="PF('layoutDialog').hide();"/> - </center> - </p:dialog> - -</h:form> - - </ui:define> -</ui:composition> - diff --git a/web/src/main/webapp/admin/status.xhtml b/web/src/main/webapp/admin/status.xhtml deleted file mode 100644 index 11343a8df99be9e23261d6340491b1443f8c1697..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/admin/status.xhtml +++ /dev/null @@ -1,51 +0,0 @@ -<ui:composition template="/WEB-INF/components/admin/template.xhtml" - xmlns="http://www.w3.org/1999/xhtml" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:p="http://primefaces.org/ui" - xmlns:cc="http://java.sun.com/jsf/composite/pfcomp" - xmlns:ui="http://java.sun.com/jsf/facelets"> - - <ui:define name="css"> - </ui:define> - - <ui:define name="title"> - Admin panel - Service status - </ui:define> - - <ui:param name="access" value="#{feedbackMB.userHasCommentPrivilege}"/> - - <ui:define name="content"> - - <cc:helpButton style="float:right" helpText='Service status tab lists all external services and databases cross-linked by MINERVA platform. The left column contains service name hyperlinked to the original website. The right column contains the status of the service. The checkup is invoked by the Refresh button at the bottom of the window.'/> - <h1>SERVICE STATUS</h1> - - <h:form id="serviceForm"> - <h:panelGroup layout="block" id="statusComponent"> - <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> - <p:dataTable id="statusesDataTable" var="service" value="#{statusMB.statuses}"> - <p:column sortBy="name" headerText="Name"> - <a href="#{service.page}" class="textBigger" target="_blank"> - <h:outputText id="name" value="#{service.name}" /> - </a> - </p:column> - - <p:column sortBy="status" headerText="status"> - <h:outputText id="status" value="#{service.status}" /> - </p:column> - </p:dataTable> - <center> - <p:commandButton id="refreshStatusButton" actionListener="#{statusMB.refreshStatuses}" - icon="ui-icon-refresh" update="statusesDataTable" onclick="PF('statusPanelBlock').show()" - oncomplete="PF('statusPanelBlock').hide()"> - </p:commandButton> - </center> - </h:panelGroup> - - <p:blockUI block="statusComponent" widgetVar="statusPanelBlock"> - CHECKING<br /> - <p:graphicImage library="images" name="icons/ajax-loader.gif"/> - </p:blockUI> - </h:form> - </ui:define> -</ui:composition> diff --git a/web/src/main/webapp/admin/users.xhtml b/web/src/main/webapp/admin/users.xhtml deleted file mode 100644 index ca235f5ae35553b0488c61e12fd51cef0f611d41..0000000000000000000000000000000000000000 --- a/web/src/main/webapp/admin/users.xhtml +++ /dev/null @@ -1,174 +0,0 @@ -<ui:composition template="/WEB-INF/components/admin/template.xhtml" - xmlns="http://www.w3.org/1999/xhtml" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:p="http://primefaces.org/ui" - xmlns:cc="http://java.sun.com/jsf/composite/pfcomp" - xmlns:ui="http://java.sun.com/jsf/facelets"> - - <ui:define name="css"> - </ui:define> - - <ui:define name="title"> - Admin panel - User management - </ui:define> - - <ui:param name="access" value="#{usersMB.userHasManagePrivileges}"/> - - <ui:define name="content"> - - <h1>USERS</h1> - - <h:form id="userForm"> - - <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> - <p:dataTable id="usersDataTable" var="user" value="#{usersMB.userList}"> - <p:column sortBy="id" headerText="Id"> - <h:outputText value="#{user.idObject}" /> - </p:column> - - <p:column sortBy="title" headerText="Name"> - <h:outputText value="#{user.name}" /> - </p:column> - - <p:column sortBy="author" headerText="Surname"> - <h:outputText value="#{user.surname}" /> - </p:column> - - <p:column sortBy="email" headerText="Email"> - <h:outputText value="#{user.email}"/> - </p:column> - - <p:column sortBy="content" headerText="Login"> - <h:outputText value="#{user.login}" /> - </p:column> - - <p:column style="width:4%"> - <p:commandButton update=":#{p:component('userDlg')}" id="selectButton" oncomplete="PF('userDialog').show()" icon="ui-icon-search" title="View"> - <f:setPropertyActionListener value="#{user}" target="#{usersMB.selectedUser}" /> - </p:commandButton> - </p:column> - - </p:dataTable> - <center> - <p:commandButton id="refreshUsersButton" actionListener="#{usersMB.refreshUserList}" icon="ui-icon-refresh" update="usersDataTable"/> - <p:commandButton id="addUserButton" actionListener="#{usersMB.prepareEmptyUser}" icon="ui-icon-document" update=":#{p:component('userDlg')}" oncomplete="PF('userDialog').show()"/> - </center> - </h:form> - </ui:define> - <ui:define name="dialog"> - <h:form id="userForm2" autocomplete="off"> - <p:dialog header="User Detail" widgetVar="userDialog" resizable="false" id="userDlg" - showEffect="fade" modal="true"> - <!-- fake fields are a workaround for chrome autofill getting the wrong fields --> - <input style="display:none" type="text" name="fakeusernameremembered"/> - <input style="display:none" type="password" name="fakepasswordremembered"/> - - <table> - <tr> - <td> - <h:outputText value="Id:" /> - </td> - <td> - <h:outputText value="#{usersMB.selectedUser.idObject}" class="bold"/> - </td> - </tr> - <tr> - <td> - <h:outputText value="Login:" /> - </td> - <td> - <p:inputText value="#{usersMB.selectedUser.login}" styleClass="bold" rendered="#{empty usersMB.selectedUser.login}" validator="loginValidator"/> - <h:outputText autocomplete="off" value="#{usersMB.selectedUser.login}" class="bold" rendered="#{not empty usersMB.selectedUser.login}"/> - </td> - </tr> - <tr> - <td> - <h:outputText value="Password:" /> - </td> - <td> - <p:password autocomplete="off" id="nonFeedback" value="#{usersMB.selectedUser.password}" /> - </td> - </tr> - <tr> - <td> - <h:outputText value="Name:" /> - </td> - <td> - <p:inputText value="#{usersMB.selectedUser.name}" styleClass="bold"/> - </td> - </tr> - <tr> - <td> - <h:outputText value="Surname:" /> - </td> - <td> - <p:inputText value="#{usersMB.selectedUser.surname}" styleClass="bold"/> - </td> - </tr> - <tr> - <td> - <h:outputText value="Email:" /> - </td> - <td> - <p:inputText value="#{usersMB.selectedUser.email}" styleClass="bold"/> - </td> - </tr> - <tr> - <td colspan="2"> - <h:outputText value="Privileges:" /> - </td> - </tr> - <tr> - <td colspan="2"> - - <p:dataTable id="basicPrivilegesDataTable" var="privilege" value="#{usersMB.selectedUser.basicPrivileges}" > - <p:column> - <h:outputText value="#{privilege.commonName}"/> - </p:column> - <p:column > - <p:selectBooleanCheckbox styleClass="smallCheckbox" value="#{privilege.selected}" rendered="#{not privilege.numeric}"/> - <p:inputText value="#{privilege.level}" rendered="#{privilege.numeric}"/> - </p:column> - </p:dataTable> - </td> - </tr> - <tr> - <td > - <h:outputText value="Project:" /> - <p:dataTable value="#{usersMB.selectedUser.pdm}" selection="#{usersMB.projectPrivilege}" var="project" selectionMode="single" style="height:180px" paginator="true" rows="5" styleClass="paginated" paginatorPosition="bottom"> - <p:ajax event="rowSelect" update=":#{p:component('tmpas')}"/> - <p:ajax event="rowUnselect" update=":#{p:component('tmpas')}"/> - <p:column> - <h:outputText value="#{project.projectId}" /> - </p:column> - </p:dataTable> - - </td> - <td > - <h:outputText value="Access:" /> - <h:panelGroup layout="block" id="tmpas" > - <p:dataTable value="#{usersMB.projectPrivilege.projectPrivileges}" selection="#{usersMB.projectPrivilege}" var="privilege" style="height:180px" > - <p:column > - <p:selectBooleanCheckbox styleClass="smallCheckbox" value="#{privilege.selected}"/> - </p:column> - <p:column> - <h:outputText value="#{privilege.commonName}" /> - </p:column> - </p:dataTable> - </h:panelGroup> - </td> - </tr> - - - </table> - <br/> - <center> - <p:commandButton update=":#{p:component('usersDataTable')}" actionListener="#{usersMB.updateSelectedUser}" id="saveUserButton" oncomplete="PF('userDialog').hide()" icon="ui-icon-disk" value="Save" title="Save"/> - <p:commandButton update=":#{p:component('usersDataTable')}" actionListener="#{usersMB.removeSelectedUser}" id="removeUserButton" oncomplete="PF('userDialog').hide()" icon="ui-icon-trash" value="Remove" title="Remove"/> - <p:commandButton update=":#{p:component('usersDataTable')}" id="cancelUserButton" oncomplete="PF('userDialog').hide()" icon="ui-icon-close" value="Cancel" title="Cancel"/> - </center> - </p:dialog> - </h:form> - </ui:define> -</ui:composition> diff --git a/web/src/main/webapp/login.xhtml b/web/src/main/webapp/login.xhtml index d2464a754bd423e87d55e7f32fcfa1324a767f89..2565b6395bf9c2533e11a37834003a882346df10 100644 --- a/web/src/main/webapp/login.xhtml +++ b/web/src/main/webapp/login.xhtml @@ -2,131 +2,51 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" - xmlns:h="http://java.sun.com/jsf/html" - xmlns:f="http://java.sun.com/jsf/core" - xmlns:ui="http://java.sun.com/jsf/facelets" -> + xmlns:h="http://java.sun.com/jsf/html" + xmlns:f="http://java.sun.com/jsf/core" + xmlns:ui="http://java.sun.com/jsf/facelets"> <h:head> - <title>minerva - Authorization form</title> - <link rel="shortcut icon" href="./resources/images/favicon.png" type="image/png"/> - <ui:include src="/WEB-INF/components/admin/statistics.xhtml"/> + <title>minerva - Authorization form</title> + <link rel="shortcut icon" href="./resources/images/favicon.png" + type="image/png" /> - <script src="https://maps.google.com/maps/api/js?libraries=drawing&v=3.26" type="text/javascript"/> + <script + src="https://maps.google.com/maps/api/js?libraries=drawing&v=3.26" + type="text/javascript" /> - <script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> - <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> - <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script> + <script src="https://code.jquery.com/jquery-1.12.1.min.js"></script> + <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> + <script + src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script> - <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css"/> - <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/> + <h:outputScript library="js" name="minerva.js" /> - <h:outputScript library="js" name="minerva.js"/> + <h:outputStylesheet library="css" name="style.css" /> + <h:outputStylesheet library="css" name="minerva.css" /> + <h:outputStylesheet library="css" name="admin.css" /> - <h:outputStylesheet library="css" name="style.css"/> - <h:outputStylesheet library="css" name="minerva.css"/> - <h:outputStylesheet library="css" name="admin.css"/> - - <script type="text/javascript"> - //<![CDATA[ - - var loggedIn = false; - - minerva.GuiConnector.init(); - minerva.ServerConnector.getSessionData(null); - minerva.ServerConnector.login().then(function () { - return minerva.ServerConnector.getProject() - }); - - - function login() { - var loginString = document.getElementById('username').value; - var passwordString = document.getElementById('password').value; - minerva.GuiConnector.init(); - minerva.ServerConnector.getSessionData(null); - return minerva.ServerConnector.login(loginString, passwordString); - } - - function init() { - var fromPage = minerva.GuiConnector.getParams["from"]; - if (fromPage !== undefined && fromPage !== null && fromPage !== "") { - $("#from")[0].value = minerva.GuiConnector.getParams["from"]; - } - $('#login').click(function (e) { - if (!loggedIn) { - e.preventDefault(); - return login().then(function () { - loggedIn = true; - $('#login').click(); - }, function (error) { - if (error.constructor.name === "InvalidCredentialsError") { - minerva.GuiConnector.alert("invalid credentials"); - } else { - minerva.GuiConnector.alert(error); - } - }); - } - }); - } - function requestAccount() { - var email, content; - return minerva.ServerConnector.getConfigurationParam("REQUEST_ACCOUNT_EMAIL").then(function(result){ - email = result; - return minerva.ServerConnector.getConfigurationParam("REQUEST_ACCOUNT_DEFAULT_CONTENT"); - }).then(function(result){ - content = encodeURIComponent(result); - url = 'mailto:'+email+'?subject=MINERVA account request&body='+content; - window.location.href=url; - }) - return false; - } - - //]]> - </script> + <script type="text/javascript"> + //<![CDATA[ + function init() { + var element = document.getElementById('minervaAppDiv'); + return minerva.createLogin({ + element : element, + }).catch(function(rejectReason){ + minerva.GuiConnector.alert(rejectReason, true); + }); + } + //]]> + </script> </h:head> <h:body onload="init();"> - <center> - <h:form name="loginForm" prependId="false" class="loginPanel" style="text-align:left"> - - <div class="headerFormTitle">AUTHORIZATION FORM</div> - - <h:panelGrid columns="2" styleClass="loginDataPanelGrid"> - <label for="username" class="labelText">LOGIN: </label> - <h:inputText id="username" name="username" value="#{userMB.login}" class="minerva-input-text"/> - - <label for="password" class="labelText">PASSWORD: </label> - <h:inputSecret id="password" name="password" value="#{userMB.password}" type="password" - class="minerva-input-password"/> - - <label class="labelText"> </label> - <h:commandButton type="submit" id="login" action="#{userMB.doLogin}" ajax="false" - value="LOGIN" styleClass="labelText" update="loginMessages"/> - </h:panelGrid> - - <input type="hidden" name="from" id="from" value=""/> - - <br/> - <br/> - <a href="javascript:;" id="go_to_map_button" - onClick="window.location.href='#{request.contextPath}/?id=#{mapMB.currentMapId}';" class="adminLink"><i - class="fa fa-chevron-right"></i> BACK TO MAP</a> - <br/> - - <a href="javascript:;" id="register_button" - onClick="requestAccount(); return false" - class="adminLink"><i class="fa fa-chevron-right"></i> REQUEST AN ACCOUNT</a> - - </h:form> - </center> - - <ui:include src="/WEB-INF/components/admin/footer.xhtml"/> + <div id="minervaAppDiv" /> </h:body> -</html> - +</html> \ No newline at end of file diff --git a/web/src/test/java/lcsb/mapviewer/AllWebTests.java b/web/src/test/java/lcsb/mapviewer/AllWebTests.java index c394dd619eb3f3fa9c10ec0ff7695787e7accc97..22334086463ca6538d7fb73e60a5d2f26b868e5b 100644 --- a/web/src/test/java/lcsb/mapviewer/AllWebTests.java +++ b/web/src/test/java/lcsb/mapviewer/AllWebTests.java @@ -4,12 +4,10 @@ import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; -import lcsb.mapviewer.bean.AllBeanTests; import lcsb.mapviewer.validator.AllValidatorTests; @RunWith(Suite.class) -@SuiteClasses({ AllBeanTests.class, // - AllValidatorTests.class,// +@SuiteClasses({ AllValidatorTests.class,// }) public class AllWebTests { diff --git a/web/src/test/java/lcsb/mapviewer/bean/AbstractManagedBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/AbstractManagedBeanTest.java deleted file mode 100644 index 48b0cf4118c75e2f37da185a05f18776b994ac9e..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/AbstractManagedBeanTest.java +++ /dev/null @@ -1,120 +0,0 @@ -package lcsb.mapviewer.bean; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.apache.commons.lang3.mutable.MutableInt; -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import lcsb.mapviewer.common.exception.InvalidArgumentException; -import lcsb.mapviewer.events.Event; -import lcsb.mapviewer.events.Listener; - -public class AbstractManagedBeanTest { - Logger logger = Logger.getLogger(AbstractManagedBeanTest.class); - - class AbstractManagedBeanMock extends AbstractManagedBean { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - public void clear() { - } - - public void callMockEvent(String data) { - callListeners(new EventMock(data)); - } - - @Override - public void init() { - // TODO Auto-generated method stub - - } - - }; - - class EventMock extends Event { - String data = ""; - - public EventMock(String d) { - data = d; - } - } - - AbstractManagedBeanMock mockBean; - - @Before - public void setUp() throws Exception { - mockBean = new AbstractManagedBeanMock(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testListeners() throws Exception { - final MutableInt called = new MutableInt(0); - try { - Listener<EventMock> listener = new Listener<EventMock>(EventMock.class) { - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(EventMock event) { - called.add(1); - } - }; - - mockBean.registerListener(listener); - assertEquals(new MutableInt(0), called); - mockBean.callMockEvent("hi"); - assertEquals(new MutableInt(1), called); - mockBean.callMockEvent("hi2"); - assertEquals(new MutableInt(2), called); - mockBean.unregisterListener(listener); - mockBean.callMockEvent("hi3"); - assertEquals(new MutableInt(2), called); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemoveListeners() throws Exception { - final MutableInt called = new MutableInt(0); - try { - Listener<EventMock> listener = new Listener<EventMock>(EventMock.class) { - - /** - * - */ - private static final long serialVersionUID = 1L; - - @Override - protected void handle(EventMock event) { - called.add(1); - } - }; - - try { - mockBean.unregisterListener(listener); - fail("Exception expected"); - } catch (InvalidArgumentException e) { - - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/AllBeanTests.java b/web/src/test/java/lcsb/mapviewer/bean/AllBeanTests.java deleted file mode 100644 index f63c521e6347238527d6ace674a9a233cb49da7b..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/AllBeanTests.java +++ /dev/null @@ -1,25 +0,0 @@ -package lcsb.mapviewer.bean; - -import org.junit.runner.RunWith; -import org.junit.runners.Suite; -import org.junit.runners.Suite.SuiteClasses; - -@RunWith(Suite.class) -@SuiteClasses({ // - AbstractManagedBeanTest.class, // - ConfigurationBeanTest.class, // - ExportBeanTest.class, // - FeedbackBeanTest.class, // - GalaxyBeanTest.class, // - LayoutBeanTest.class, // - MapBeanTest.class, // - MiriamBeanTest.class, // - MissingConnectionBeanTest.class, // - ProjectBeanTest.class, // - SearchBeanTest.class, // - UserBeanTest.class, // - UsersBeanTest.class,// -}) -public class AllBeanTests { - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/ConfigurationBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/ConfigurationBeanTest.java deleted file mode 100644 index 6e2f4dad0de63c7cdce591b54be5210b80d3919a..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/ConfigurationBeanTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.Serializable; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.services.view.ConfigurationViewFactory; - -public class ConfigurationBeanTest extends WebTestFunctions { - - ConfigurationBean cBean; - UserBean uBean; - String oldValue; - User user2; - - @Autowired - ConfigurationViewFactory configurationViewFactory; - - @Before - public void setUp() throws Exception { - dbUtils.setAutoFlush(true); - cBean = getConfigurationBean(); - - uBean = getUserBean(); - - user2 = new User(); - userService.addUser(user2); - userService.setUserPrivilege(user2, PrivilegeType.CONFIGURATION_MANAGE, 1); - userService.setUserPrivilege(user2, PrivilegeType.ADD_MAP, 1); - uBean.setLoggedUser(user2); - - oldValue = configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); - - } - - @After - public void tearDown() throws Exception { - userService.deleteUser(user2); - uBean.setLoggedUser(userService.getUserByLogin(Configuration.ANONYMOUS_LOGIN)); - configurationService.setConfigurationValue(ConfigurationElementType.DEFAULT_MAP, oldValue); - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(cBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/CustomPrimefacesUtils.java b/web/src/test/java/lcsb/mapviewer/bean/CustomPrimefacesUtils.java deleted file mode 100644 index 251761a3c183ecb90ef54946c19483527d9688bf..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/CustomPrimefacesUtils.java +++ /dev/null @@ -1,141 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.faces.component.UIComponent; - -import lcsb.mapviewer.bean.utils.IPrimefacesUtils; -import lcsb.mapviewer.common.exception.NotImplementedException; - -import org.apache.log4j.Logger; - -public class CustomPrimefacesUtils implements IPrimefacesUtils { - Logger logger = Logger.getLogger(CustomPrimefacesUtils.class); - - private String path = "tmp/"; - private String ip = "127.0.0.1"; - private String version = "unknown"; - - private Map<String, String> requestParams = new HashMap<>(); - private Map<String, Object> callbackObjects = new HashMap<>(); - - private Map<String, Object> sessionParams = new HashMap<>(); - - private List<String> errors = new ArrayList<>(); - private List<String> infos = new ArrayList<>(); - - @Override - public String getRequestParameter(String name) { - return requestParams.get(name); - } - - @Override - public String getPath() { - return path; - } - - @Override - public String getClientIpAddress() { - return ip; - } - - @Override - public void error(String message) { - errors.add(message); - logger.debug("PF ERROR message: " + message, new Exception()); - } - - @Override - public void info(String message) { - infos.add(message); - logger.debug("PF Info message: " + message); - } - - @Override - public String getVersion() { - return version; - } - - @Override - public UIComponent findComponent(String id) { - throw new NotImplementedException(); - } - - @Override - public void addCallbackParam(String key, Object value) { - callbackObjects.put(key, value); - } - - /** - * @return the errors - * @see #errors - */ - public List<String> getErrors() { - return errors; - } - - /** - * @param errors - * the errors to set - * @see #errors - */ - public void setErrors(List<String> errors) { - this.errors = errors; - } - - /** - * @return the infos - * @see #infos - */ - public List<String> getInfos() { - return infos; - } - - /** - * @param infos - * the infos to set - * @see #infos - */ - public void setInfos(List<String> infos) { - this.infos = infos; - } - - public Object getCallbackParam(String key) { - return callbackObjects.get(key); - } - - @Override - public Map<String, String> getRequestParameterMap() { - return requestParams; - } - - @Override - public void addSessionParam(String key, Object value) { - sessionParams.put(key, value); - - } - - @Override - public Object getSessionParam(String key) { - return sessionParams.get(key); - } - - @Override - public void createSession() { - - } - - @Override - public <T> T findBean(Class<T> clazz) { - throw new NotImplementedException(); - } - - @Override - public void executeJavascript(String javascript) { - logger.debug("Executing Javascript:\n\n-------------\n\n" + javascript + "\n\n-------------\n\n"); - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/ExportBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/ExportBeanTest.java deleted file mode 100644 index db4028633373275dfce531d2a0f4214f70e132a1..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/ExportBeanTest.java +++ /dev/null @@ -1,256 +0,0 @@ -package lcsb.mapviewer.bean; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.Serializable; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.SerializationUtils; -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.primefaces.model.DualListModel; - -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.MiriamType; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.services.utils.data.ExportColumn; -import lcsb.mapviewer.services.utils.data.ExportFileType; - -public class ExportBeanTest extends WebTestFunctions { - static Logger logger = Logger.getLogger(ExportBeanTest.class); - - private ExportBean exportBean; - String projectId = "Some_id"; - - @Before - public void setUp() throws Exception { - exportBean = getExportBean(); - - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetSpeciesTypeMap() { - try { - Map<String, Class<?>> types = exportBean.getSpeciesTypeMap(); - assertNotNull(types); - assertTrue(types.keySet().size() > 10); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetSpeciesTypeList() { - try { - List<String> types = exportBean.getSpeciesTypeList(); - assertNotNull(types); - assertTrue(types.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetSpeciesColumnList() { - try { - List<String> types = exportBean.getSpeciesColumnList(); - assertNotNull(types); - assertTrue(types.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetNetworkFileTypeList() { - try { - List<String> types = exportBean.getNetworkFileTypeList(); - assertNotNull(types); - assertTrue(types.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetModels() { - try { - List<String> types = exportBean.getModels(); - assertNotNull(types); - assertTrue(types.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetImageGenerators() { - try { - List<?> types = exportBean.getImageGenerators(); - assertNotNull(types); - assertTrue(types.size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetImageExportMenu() { - try { - Object obj = exportBean.getImageExportMenu(); - assertNotNull(obj); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetNetworkAvailableMiriam() throws Exception { - Project project = null; - try { - project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - - Model model = getModelForFile("testFiles/centeredAnchorInModifier.xml", false); - model.setTileSize(256); - project.addModel(model); - modelDao.add(model); - - getMapBean().setCurrentMapId(projectId); - DualListModel<Pair<MiriamType, String>> obj = exportBean.getNetworkAvailableMiriam(); - assertNotNull(obj); - assertTrue(obj.getSource().size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - if (project != null) { - projectService.removeProject(project, null, false, adminToken); - } - - } - } - - @Test - public void testGetElementAvailableMiriam() throws Exception { - Project project = null; - try { - project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - - Model model = getModelForFile("testFiles/centeredAnchorInModifier.xml", false); - model.setTileSize(256); - project.addModel(model); - modelDao.add(model); - - getMapBean().setCurrentMapId(projectId); - DualListModel<Pair<MiriamType, String>> obj = exportBean.getElementAvailableMiriam(); - assertNotNull(obj); - assertTrue(obj.getSource().size() > 0); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } finally { - if (project != null) { - projectService.removeProject(project, null, false, adminToken); - } - - } - } - - @Test - public void testGetComponentList() { - try { - DualListModel<String> obj = exportBean.getNetworkExcludedComponent(); - assertNotNull(obj); - obj = exportBean.getNetworkIncludedComponent(); - assertNotNull(obj); - obj = exportBean.getElementExcludedComponent(); - assertNotNull(obj); - obj = exportBean.getElementIncludedComponent(); - assertNotNull(obj); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetSpeciesColumnMap() { - try { - Map<String, ExportColumn> types = exportBean.getSpeciesColumnMap(); - assertNotNull(types); - assertTrue(types.keySet().size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetNetworkFileTypeMap() { - try { - Map<String, ExportFileType> types = exportBean.getNetworkFileTypeMap(); - assertNotNull(types); - assertTrue(types.keySet().size() > 0); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(exportBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testDesearializationIdList() { - try { - List<Integer> list = exportBean.deserializeIdList("[\"123\",\"346\"]"); - assertNotNull(list); - assertEquals(2, list.size()); - assertEquals((Integer) 123, list.get(0)); - assertEquals((Integer) 346, list.get(1)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/FeedbackBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/FeedbackBeanTest.java deleted file mode 100644 index e4bee4e7561ff82c9ea5953344071ce66f75dc84..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/FeedbackBeanTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.Serializable; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class FeedbackBeanTest extends WebTestFunctions { - - FeedbackBean feedbackBean; - - @Before - public void setUp() throws Exception { - feedbackBean = getFeedbackBean(); - } - - @After - public void tearDown() throws Exception { - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(feedbackBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/GalaxyBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/GalaxyBeanTest.java deleted file mode 100644 index 12824a17655664fa85b0a0bd6c9ac6576d99f6c2..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/GalaxyBeanTest.java +++ /dev/null @@ -1,48 +0,0 @@ -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; - -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; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/LayoutBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/LayoutBeanTest.java deleted file mode 100644 index d6295ff11d0abc3dbb42f1a13ede34cbee078f7b..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/LayoutBeanTest.java +++ /dev/null @@ -1,230 +0,0 @@ -package lcsb.mapviewer.bean; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.Serializable; - -import org.apache.commons.lang3.SerializationUtils; -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.layout.Layout; -import lcsb.mapviewer.model.map.layout.LayoutStatus; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.user.BasicPrivilege; -import lcsb.mapviewer.model.user.ObjectPrivilege; -import lcsb.mapviewer.model.user.PrivilegeType; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.persist.dao.map.LayoutDao; -import lcsb.mapviewer.services.view.ProjectView; - -public class LayoutBeanTest extends WebTestFunctions { - Logger logger = Logger.getLogger(LayoutBeanTest.class); - - LayoutBean layoutBean; - - UserBean userBean; - - ProjectBean projectBean; - - MapBean mapBean; - - @Autowired - LayoutDao layoutDao; - - String projectId = "Some_id"; - - @Before - public void setUp() throws Exception { - // we use custom threads because in layoutservice there is commit somewhere - // called, and because of that hibernate session injected by spring cannot - // commit at the end of the test case - dbUtils.createSessionForCurrentThread(); - - userBean = getUserBean(); - layoutBean = getLayoutBean(); - projectBean = getProjectBean(); - mapBean = getMapBean(); - - createUser(); - - Project p = projectService.getProjectByProjectId(projectId, adminToken); - if (p != null) { - projectService.removeProject(p, null, false, adminToken); - } - - } - - @After - public void tearDown() throws Exception { - userDao.delete(user); - - Project p = projectService.getProjectByProjectId(projectId, adminToken); - if (p != null) { - projectService.removeProject(p, null, false, adminToken); - } - - // close session - dbUtils.closeSessionForCurrentThread(); - - } - - @Ignore - @Test(timeout = 15000) - public void testAddLayout() throws Exception { - Project project = new Project(); - try { - dbUtils.setAutoFlush(true); - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/sample.xml")); - model.setTileSize(256); - - project.setProjectId(projectId); - project.addModel(model); - - projectDao.add(project); - projectDao.flush(); - projectDao.commit(); - projectDao.refresh(project); - model = project.getModels().iterator().next().getModel(); - - projectBean.refreshProjectList(null); - - layoutBean.setLayoutFile(new File("testFiles/layout.txt")); - - // set current map - getUserBean().setAuthenticationToken(adminToken); - mapBean.setCurrentMapId(project.getProjectId()); - getMapBean().setCurrentMapId(project.getProjectId()); - - User guest = userService.getUserByLogin(Configuration.ANONYMOUS_LOGIN); - // add user a privilege for viewing layouts - BasicPrivilege privilege = new ObjectPrivilege(project, 1, PrivilegeType.VIEW_PROJECT, guest); - userService.setUserPrivilege(guest, privilege); - userDao.flush(); - - // generate new layout - layoutBean.addAnonymousLayout(projectService.getProjectViewById(project.getId(), token)); - - // wait until layout is generated - Integer id = modelDao.getById(model.getId()).getLayouts().get(0).getId(); - Layout l = layoutDao.getById(id); - do { - Thread.sleep(200); - layoutDao.refresh(l); - logger.debug(l.getStatus()); - } while (l.getStatus().equals(LayoutStatus.NA) || l.getStatus().equals(LayoutStatus.GENERATING)); - - ProjectView projectView = projectBean.getProjects().get(projectBean.getProjects().size() - 1); - - assertEquals(1, projectView.getLayouts().size()); - assertTrue(projectView.getLayouts().get(0).getCreator().isEmpty()); - - assertEquals(0, layoutBean.getCustomLayouts().size()); - assertEquals(1, layoutBean.getGeneralLayouts().size()); - assertEquals(1, mapBean.getTopModelMapData().getMapConfig().getLayouts().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Ignore - @Test(timeout = 15000) - public void testAddLayoutForUser() throws Exception { - Project project = new Project(); - try { - dbUtils.setAutoFlush(true); - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - Model model = parser.createModel(new ConverterParams().filename("testFiles/sample.xml")); - model.setTileSize(256); - - project.setProjectId(projectId); - project.addModel(model); - - projectDao.add(project); - projectDao.flush(); - projectDao.commit(); - - projectBean.refreshProjectList(null); - - getUserBean().setAuthenticationToken(adminToken); - getMapBean().setCurrentMapId(projectId); - layoutBean.setLayoutFile(new File("testFiles/layout.txt")); - - // set current map - mapBean.setCurrentMapId(project.getProjectId()); - getMapBean().setCurrentMapId(project.getProjectId()); - - // add user a privilege for adding layouts - userBean.setLoggedUser(user); - BasicPrivilege privilege = new BasicPrivilege(1, PrivilegeType.CUSTOM_LAYOUTS, user); - userService.setUserPrivilege(user, privilege); - - // add user a privilege for viewing layouts - privilege = new ObjectPrivilege(project, 1, PrivilegeType.VIEW_PROJECT, user); - userService.setUserPrivilege(user, privilege); - userDao.flush(); - userDao.commit(); - - layoutBean.addLayout(null); - - // wait until layout is generated - Integer id = Integer.valueOf(layoutService.getCustomLayouts(model, user, true, user).get(0).getIdObject()); - Layout l = layoutDao.getById(id); - do { - Thread.sleep(200); - layoutDao.refresh(l); - } while (l.getStatus().equals(LayoutStatus.NA) || l.getStatus().equals(LayoutStatus.GENERATING)); - - ProjectView projectView = null; - for (ProjectView view : projectBean.getProjects()) { - if (view.getIdObject().equals(project.getId())) { - projectView = view; - } - } - - assertNotNull(projectView); - // check if layout appears on project list - assertEquals(1, projectView.getLayouts().size()); - assertFalse(projectView.getLayouts().get(0).getCreator().isEmpty()); - - // check if layout appears on layout list in current model (mapBean) - - assertEquals(1, layoutBean.getCustomLayouts().size()); - assertEquals(0, layoutBean.getGeneralLayouts().size()); - assertEquals(1, mapBean.getTopModelMapData().getMapConfig().getCustomLayouts().size()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test(timeout = 5000) - public void testSearialization() { - try { - SerializationUtils.serialize(layoutBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/MapBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/MapBeanTest.java deleted file mode 100644 index c2685289b27ee6c78c7feee9256a7bf62e9750e4..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/MapBeanTest.java +++ /dev/null @@ -1,102 +0,0 @@ -package lcsb.mapviewer.bean; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; - -import java.io.Serializable; -import java.util.List; - -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.common.Configuration; -import lcsb.mapviewer.common.Pair; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.model.user.ObjectPrivilege; -import lcsb.mapviewer.model.user.PrivilegeType; - -public class MapBeanTest extends WebTestFunctions { - - MapBean bean; - UserBean userBean; - ProjectBean projectBean; - - Project project; - - @Before - public void setUp() throws Exception { - projectBean = getProjectBean(); - - userBean = getUserBean(); - user = userService.getUserByLogin(Configuration.ANONYMOUS_LOGIN); - userBean.setLoggedUser(user); - - bean = getMapBean(); - - bean.setCurrentMapId(configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP)); - - project = new Project(); - project.setProjectId("Some_id"); - projectDao.add(project); - - Model model = getModelForFile("testFiles/centeredAnchorInModifier.xml", false); - project.addModel(model); - modelDao.add(model); - - userService.setUserPrivilege(user, new ObjectPrivilege(project, 1, PrivilegeType.VIEW_PROJECT, user)); - } - - @After - public void tearDown() throws Exception { - projectDao.delete(project); - } - - @Test - public void testVetoSelectedMap() { - String oldVal = bean.getCurrentMapId(); - bean.setCurrentMapId("test bla bl"); - assertEquals(oldVal, bean.getCurrentMapId()); - } - - @Test - @Ignore("Not valid anymore") - public void testVetoSelectedMap2() { - String oldVal = bean.getCurrentMapId(); - bean.setCurrentMapId(project.getProjectId()); - assertFalse(oldVal.equals(bean.getCurrentMapId())); - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(bean); - SerializationUtils.serialize(bean.getTopModelMapData()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testDeserializationOfIds() { - try { - String str = "[[863,\"58998\"],[863,\"59000\"],[863,\"59001\"],[863,\"59003\"],[863,\"59006\"],[863,\"59008\"],[863,\"59010\"],[863,\"59011\"]]"; - List<Pair<Integer, Integer>> list = bean.deserializeJsonIds(str); - assertEquals(8, list.size()); - assertEquals((Integer) 863, list.get(0).getLeft()); - assertEquals((Integer) 58998, list.get(0).getRight()); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/MiriamBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/MiriamBeanTest.java deleted file mode 100644 index 94e9728587e94f6b6bfbbf0b06481495da116b8e..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/MiriamBeanTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.Serializable; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class MiriamBeanTest extends WebTestFunctions { - MiriamBean miriamBean; - - @Before - public void setUp() throws Exception { - miriamBean = getMiriamBean(); - } - - @After - public void tearDown() throws Exception { - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(miriamBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/MissingConnectionBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/MissingConnectionBeanTest.java deleted file mode 100644 index 66ed01892862d689757e9668ea6f1d3190f183e0..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/MissingConnectionBeanTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.Serializable; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class MissingConnectionBeanTest extends WebTestFunctions { - MissingConnectionBean missingConnectionBean; - - @Before - public void setUp() throws Exception { - missingConnectionBean = getMissingConnectionBean(); - } - - @After - public void tearDown() throws Exception { - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(missingConnectionBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/ProjectBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/ProjectBeanTest.java deleted file mode 100644 index a958e652b7f813edd0818bc301af495432aca200..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/ProjectBeanTest.java +++ /dev/null @@ -1,194 +0,0 @@ -package lcsb.mapviewer.bean; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.Serializable; - -import org.apache.commons.lang3.SerializationUtils; -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.primefaces.event.FileUploadEvent; -import org.primefaces.model.UploadedFile; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.converter.zip.ModelZipEntryFile; -import lcsb.mapviewer.converter.zip.ZipEntryFile; -import lcsb.mapviewer.model.Project; -import lcsb.mapviewer.model.ProjectStatus; -import lcsb.mapviewer.model.user.ConfigurationElementType; -import lcsb.mapviewer.services.view.ProjectView; -import lcsb.mapviewer.services.view.ProjectViewFactory; - -public class ProjectBeanTest extends WebTestFunctions { - Logger logger = Logger.getLogger(ProjectBeanTest.class); - - ProjectBean projectBean; - UserBean userBean; - - String defaultMap; - - String projectId = "Some_id"; - - @Autowired - ProjectViewFactory projectViewFactory; - - @Before - public void setUp() throws Exception { - dbUtils.setAutoFlush(true); - - // we use custom threads because in layoutservice there is commit somewhere - // called, and because of that hibernate session injected by spring cannot - // commit at the end of the test case - dbUtils.createSessionForCurrentThread(); - - defaultMap = configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); - - projectBean = getProjectBean(); - userBean = getUserBean(); - } - - @After - public void tearDown() throws Exception { - configurationService.setConfigurationValue(ConfigurationElementType.DEFAULT_MAP, defaultMap); - - Project p = projectService.getProjectByProjectId(projectId, adminToken); - if (p != null) { - projectService.removeProject(p, null, false, adminToken); - } - // close session - dbUtils.closeSessionForCurrentThread(); - - // close session - dbUtils.closeSessionForCurrentThread(); - } - - @Test - public void testOnRemoveCheck() throws Exception { - try { - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - projectDao.commit(); - - configurationService.setConfigurationValue(ConfigurationElementType.DEFAULT_MAP, projectId); - - ProjectView row = projectService.getProjectViewByProjectId(projectId, adminToken); - - getUserBean().setAuthenticationToken(adminToken); - projectBean.setSelectedProject(row); - projectBean.removeSelectedProject(null); - - assertNotNull(projectService.getProjectViewByProjectId(projectId, adminToken)); - - configurationService.setConfigurationValue(ConfigurationElementType.DEFAULT_MAP, "test bla"); - - projectBean.removeSelectedProject(null); - - ProjectView pv = projectService.getProjectViewByProjectId(projectId, adminToken); - if (pv != null && pv.getIdObject() != null) { - assertEquals(ProjectStatus.REMOVING.toString(), pv.getStatus()); - } - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test(timeout = 15000) - public void testOnChangeCheck() throws Exception { - try { - Project project = new Project(); - project.setProjectId(projectId); - projectDao.add(project); - - configurationService.setConfigurationValue(ConfigurationElementType.DEFAULT_MAP, projectId); - - ProjectView row = projectService.getProjectViewByProjectId(projectId, adminToken); - - userBean.setAuthenticationToken(adminToken); - projectBean.setSelectedProject(row); - - ProjectView row2 = new ProjectView(row); - - row2.setProjectId("shdfsjkfhsd"); - - // this set should be rollback (we cannot change the name of default - // project) - projectBean.setSelectedProject(row2); - - assertEquals(row, projectBean.getSelectedProject()); - - row2 = projectViewFactory.create(null); - row2.setProjectId(projectId); - - // this set should be rollback (we cannot create a new project with the - // name that already exists in a system) - projectBean.setSelectedProject(row2); - - assertEquals(row, projectBean.getSelectedProject()); - - row2.setProjectId(projectId + "haha"); - - // this set shouldn't be rollback - projectBean.setSelectedProject(row2); - - assertEquals(row2, projectBean.getSelectedProject()); - - projectDao.delete(project); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testOnUploadCheck() throws Exception { - try { - File file = new File("testFiles/complex_model.zip"); - InputStream inputStream = new FileInputStream(file); - FileUploadEvent event = Mockito.mock(FileUploadEvent.class); - UploadedFile uploadedFile = Mockito.mock(UploadedFile.class); - Mockito.when(uploadedFile.getFileName()).thenReturn(file.getName()); - Mockito.when(uploadedFile.getContentType()).thenReturn("application/octet-stream"); - Mockito.when(uploadedFile.getInputstream()).thenReturn(inputStream); - Mockito.when(event.getFile()).thenReturn(uploadedFile); - - projectBean.handleFileUpload(event); - assertNotNull(projectBean.getMapFile()); - assertTrue(projectBean.getComplexModel().equalsIgnoreCase("true")); - assertEquals(5, projectBean.getModelZipEntries().size()); - ZipEntryFile zef = projectBean.getModelZipEntries().get(0); - assertTrue(zef instanceof ModelZipEntryFile); - assertFalse(((ModelZipEntryFile) zef).getName().contains("xml")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - /** - * Checks if bean implements {@link Serializable} properly. - * - * @throws Exception - */ - @Test - public void testSearialization() throws Exception { - try { - SerializationUtils.serialize(projectBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/ReferenceGenomeBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/ReferenceGenomeBeanTest.java deleted file mode 100644 index 3a5bebbae9883e768cae02d2c36d484f9911b549..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/ReferenceGenomeBeanTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package lcsb.mapviewer.bean; - -import static org.junit.Assert.assertNotNull; - -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; - -import lcsb.mapviewer.annotation.services.TaxonomyBackend; -import lcsb.mapviewer.persist.DbUtils; - -public class ReferenceGenomeBeanTest extends WebTestFunctions { - Logger logger = Logger.getLogger(ReferenceGenomeBeanTest.class); - - ReferenceGenomeBean referenceGenomeBean; - - @Autowired - DbUtils dbUtils; - - @Before - public void setUp() throws Exception { - referenceGenomeBean = super.getReferenceGenomeBean(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testSetOrganism() { - try { - referenceGenomeBean.setSelectedOrganism(TaxonomyBackend.HUMAN_TAXONOMY); - assertNotNull(referenceGenomeBean.getSelectedUrl()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetPrivilege() { - try { - Boolean result = referenceGenomeBean.getUserHasManageGenomesPrivilege(); - assertNotNull(result); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/SearchBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/SearchBeanTest.java deleted file mode 100644 index 7e77496e30603c2cad13084dfeedf0c47ed51159..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/SearchBeanTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.Serializable; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class SearchBeanTest extends WebTestFunctions { - - SearchBean searchBean; - - @Before - public void setUp() throws Exception { - searchBean = getSearchBean(); - } - - @After - public void tearDown() throws Exception { - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(searchBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/UserBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/UserBeanTest.java deleted file mode 100644 index cecf9f8facf6f145a4e2be75cacaeb0eed1c82ed..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/UserBeanTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package lcsb.mapviewer.bean; - -import static org.junit.Assert.assertFalse; - -import java.io.ByteArrayOutputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -import lcsb.mapviewer.model.user.User; - -import org.apache.commons.lang3.SerializationUtils; -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class UserBeanTest extends WebTestFunctions { - static Logger logger = Logger.getLogger(UserBeanTest.class); - - UserBean bean; - - @Before - public void setUp() throws Exception { - bean = new UserBean(); - bean.setUserService(userService); - bean.setConfigurationService(configurationService); - bean.setLogService(logService); - bean.init(); - createUser(); - } - - @After - public void tearDown() throws Exception { - userService.deleteUser(user); - } - - @Test - public void test() { - - bean.setLoggedUser(user); - User user = bean.getLoggedUser(); - bean.setLogin("Test"); - User user2 = bean.getLoggedUser(); - - assertFalse(user.equals(user2)); - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() throws Exception { - try { - - SerializationUtils.serialize(bean); - - ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); - ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream); - objectOutputStream.writeObject(bean); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testSearialization2() throws Exception { - try { - ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(); - ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteOutputStream); - objectOutputStream.writeObject(bean); - objectOutputStream.flush(); - objectOutputStream.close(); - - logger.debug(byteOutputStream.toByteArray().length); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/UsersBeanTest.java b/web/src/test/java/lcsb/mapviewer/bean/UsersBeanTest.java deleted file mode 100644 index 56f548d896bb1bca9877b5ca6514eb42f70028ab..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/UsersBeanTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.Serializable; - -import org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class UsersBeanTest extends WebTestFunctions { - UsersBean usersBean; - - @Before - public void setUp() throws Exception { - usersBean = getUsersBean(); - } - - @After - public void tearDown() throws Exception { - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(usersBean); - } 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 deleted file mode 100644 index fccf8ea97ff33d35499ff9af035184565b46f1f5..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/WebTestFunctions.java +++ /dev/null @@ -1,719 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.net.URLConnection; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.commons.io.FileUtils; -import org.apache.log4j.Logger; -import org.junit.After; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.test.annotation.Rollback; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.annotation.Transactional; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import lcsb.mapviewer.annotation.services.ChEMBLParser; -import lcsb.mapviewer.annotation.services.DrugbankHTMLParser; -import lcsb.mapviewer.annotation.services.ModelAnnotator; -import lcsb.mapviewer.annotation.services.annotators.BiocompendiumAnnotator; -import lcsb.mapviewer.common.Configuration; -import lcsb.mapviewer.common.exception.InvalidXmlSchemaException; -import lcsb.mapviewer.converter.ConverterParams; -import lcsb.mapviewer.converter.model.celldesigner.CellDesignerXmlParser; -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.model.user.User; -import lcsb.mapviewer.persist.DbUtils; -import lcsb.mapviewer.persist.dao.ConfigurationDao; -import lcsb.mapviewer.persist.dao.ProjectDao; -import lcsb.mapviewer.persist.dao.cache.CacheQueryDao; -import lcsb.mapviewer.persist.dao.graphics.PolylineDao; -import lcsb.mapviewer.persist.dao.log.LogDao; -import lcsb.mapviewer.persist.dao.map.CommentDao; -import lcsb.mapviewer.persist.dao.map.ModelDao; -import lcsb.mapviewer.persist.dao.map.ReactionDao; -import lcsb.mapviewer.persist.dao.map.species.ElementDao; -import lcsb.mapviewer.persist.dao.map.statistics.SearchHistoryDao; -import lcsb.mapviewer.persist.dao.user.PrivilegeDao; -import lcsb.mapviewer.persist.dao.user.UserDao; -import lcsb.mapviewer.services.interfaces.ICommentService; -import lcsb.mapviewer.services.interfaces.IConfigurationService; -import lcsb.mapviewer.services.interfaces.IDataMiningService; -import lcsb.mapviewer.services.interfaces.IExporterService; -import lcsb.mapviewer.services.interfaces.IExternalServicesService; -import lcsb.mapviewer.services.interfaces.ILayoutService; -import lcsb.mapviewer.services.interfaces.ILogService; -import lcsb.mapviewer.services.interfaces.IModelService; -import lcsb.mapviewer.services.interfaces.IProjectService; -import lcsb.mapviewer.services.interfaces.IReferenceGenomeService; -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", // -}) -@RunWith(SpringJUnit4ClassRunner.class) -public abstract class WebTestFunctions { - private Logger logger = Logger.getLogger(WebTestFunctions.class); - - @Autowired - protected ChEMBLParser chemblParser; - - @Autowired - protected DrugbankHTMLParser drugBankHTMLParser; - - @Autowired - protected ModelAnnotator modelAnnotator; - - @Autowired - protected BiocompendiumAnnotator restService; - - public double EPSILON = 1e-6; - - @Autowired - protected IConfigurationService configurationService; - - @Autowired - protected IModelService modelService; - - @Autowired - protected IExternalServicesService externalServicesService; - - @Autowired - protected ILayoutService layoutService; - - @Autowired - protected ILogService logService; - - @Autowired - protected IExporterService exportService; - - @Autowired - protected LogDao logDao; - - @Autowired - protected SearchHistoryDao searchHistoryDao; - - @Autowired - protected PasswordEncoder passwordEncoder; - - @Autowired - protected IUserService userService; - - @Autowired - protected ConfigurationDao configurationDao; - - @Autowired - protected IDataMiningService dataMiningService; - - @Autowired - protected ISearchService searchService; - - @Autowired - protected IDrugService drugService; - - @Autowired - protected IChemicalService chemicalService; - - @Autowired - protected IProjectService projectService; - - @Autowired - protected ProjectDao projectDao; - - @Autowired - protected CacheQueryDao cacheQueryDao; - - @Autowired - protected PolylineDao polylineDao; - - @Autowired - protected ModelDao modelDao; - - @Autowired - protected ICommentService commentService; - - @Autowired - protected UserDao userDao; - - @Autowired - protected PrivilegeDao privilegeDao; - - @Autowired - protected CommentDao commentDao; - - @Autowired - protected DbUtils dbUtils; - - @Autowired - protected ReactionDao reactionDao; - - @Autowired - protected ElementDao aliasDao; - - @Autowired - protected ModelViewFactory modelViewFactory; - - @Autowired - protected IReferenceGenomeService referenceGenomeService; - - protected User user; - - private ConfigurationBean configurationBean; - private LayoutBean layoutBean; - private MapBean mapBean; - private ProjectBean projectBean; - private UserBean userBean; - - private ExportBean exportBean; - - private FeedbackBean feedbackBean; - private MiriamBean miriamBean; - private MissingConnectionBean missingConnectionBean; - private SearchBean searchBean; - private UsersBean usersBean; - - private ReferenceGenomeBean referenceGenomeBean; - - protected CustomPrimefacesUtils primefacesUtils = new CustomPrimefacesUtils(); - - AuthenticationToken token; - - AuthenticationToken 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()); - - } - -}