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 692c2af511d270b38661eeca476e730ec688d347..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/ConfigurationBean.java +++ /dev/null @@ -1,510 +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.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 (lcsb.mapviewer.services.SecurityException e) { - throw new PropertyVetoException("You have no privilege to perform this operation", arg0); - } - if (!view.getStatus().equalsIgnoreCase("OK")) { - throw new PropertyVetoException( - "Project " + arg0.getNewValue() + " is invalid. Project status: " + view.getStatus(), arg0); - } - } - } - } - }; - addVetoablePropertyChangeListener(selectedMapVetoChanged); - - PropertyChangeListener xFrameChanged = new PropertyChangeListener() { - - @Override - public void propertyChange(PropertyChangeEvent arg0) { - if ((X_FRAME_PROPERTY).equals(arg0.getPropertyName())) { - Configuration.setxFrameDomain((String) arg0.getNewValue()); - } - } - }; - addPropertyChangeListener(xFrameChanged); - - // listener that checks if the new x-fram address is valid - VetoableChangeListener xFrameVetoChanged = new VetoableChangeListener() { - @Override - public void vetoableChange(final PropertyChangeEvent arg0) throws PropertyVetoException { - if ((X_FRAME_PROPERTY).equals(arg0.getPropertyName())) { - String domain = (String) arg0.getNewValue(); - if (!new UrlValidator().isValid(domain) && !(domain != null && domain.contains("localhost"))) { - throw new PropertyVetoException("Invalid address: " + domain, arg0); - } - } - } - }; - addVetoablePropertyChangeListener(xFrameVetoChanged); - - version = configurationService.getSystemVersion(getProjectDeployPath()); - - refreshValues(null); - - Configuration.setWebAppDir(new File(getPrimefacesUtils().getPath() + "../").getAbsolutePath() + "/"); - } - - /** - * Refresh values from the database. - * - * @param actionEvent - * event from thefrom the client - */ - public final void refreshValues(final ActionEvent actionEvent) { - values = configurationService.getAllValues(); - for (ConfigurationView view : values) { - valueMap.put(view.getType(), view.getValue()); - } - } - - /** - * Save values to the database. - * - * @param actionEvent - * event from thefrom the client - */ - public final void saveValues(final ActionEvent actionEvent) { - // first check if we have privileges - if (getUserHasConfigurationView()) { - setValues(values); - configurationService.updateConfiguration(values); - values = configurationService.getAllValues(); - } - } - - /** - * Checks if logged user can manage the configuration of the system. - * - * @return <code>true</code> if logged user can manage the configuration, - * <code>false</code> otherwise - */ - public final boolean getUserHasConfigurationView() { - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.CONFIGURATION_MANAGE); - return result; - } - - /** - * - * @return list of all configuration values - * @see #values - */ - public final List<ConfigurationView> getValues() { - if (getUserHasConfigurationView()) { - return values; - } else { - return new ArrayList<>(); - } - } - - /** - * Sets the new list of configurable parameters. - * - * @param values - * list of configurable parameters with new values - */ - public final void setValues(final List<ConfigurationView> values) { - // when we set new values we should: - // 1) check if they are correct (vchs listeners) - // 2) notify apropriate listeners - - // for the naming convention of parameters take a look at {@link #vchs} - - // remember the old values from the system (!! not from the bean !!) - List<ConfigurationView> old = configurationService.getAllValues(); - this.values = values; - for (ConfigurationView el : values) { - String newVal = el.getValue(); - String oldVal = null; - for (ConfigurationView oldEl : old) { - if (oldEl.getType().equals(el.getType())) { - oldVal = oldEl.getValue(); - } - } - try { - if (el.getType().equals(ConfigurationElementType.DEFAULT_MAP)) { - fireVetoableChange(DEFAULT_MODEL_PROPERTY, oldVal, newVal); - } - } catch (PropertyVetoException e) { // if there was a veto then rollback - // to system parameters - this.values = old; - logger.debug("Rollback because parameter " + el.getType().name() + " contains inproper value: " + newVal); - sendError(e.getMessage()); - return; - } - } - for (ConfigurationView el : values) { - String newVal = el.getValue(); - String oldVal = null; - for (ConfigurationView oldEl : old) { - if (oldEl.getType().equals(el.getType())) { - oldVal = oldEl.getValue(); - } - } - if (el.getType().equals(ConfigurationElementType.DEFAULT_MAP)) { - firePropertyChange(DEFAULT_MODEL_PROPERTY, oldVal, newVal); - } else if (el.getType().equals(ConfigurationElementType.X_FRAME_DOMAIN)) { - firePropertyChange(X_FRAME_PROPERTY, oldVal, newVal); - } - - } - } - - @Override - public void clear() { - setValues(new ArrayList<ConfigurationView>()); - } - - /** - * @return the userBean - * @see #userBean - */ - public UserBean getUserBean() { - return userBean; - } - - /** - * @param userBean - * the userBean to set - * @see #userBean - */ - public void setUserBean(UserBean userBean) { - this.userBean = userBean; - } - - /** - * @return the configurationService - * @see #configurationService - */ - public IConfigurationService getConfigurationService() { - return configurationService; - } - - /** - * @param configurationService - * the configurationService to set - * @see #configurationService - */ - public void setConfigurationService(IConfigurationService configurationService) { - this.configurationService = configurationService; - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - /** - * @return the projectService - * @see #projectService - */ - public IProjectService getProjectService() { - return projectService; - } - - /** - * @param projectService - * the projectService to set - * @see #projectService - */ - public void setProjectService(IProjectService projectService) { - this.projectService = projectService; - } - - /** - * @return the version - * @see #version - */ - public FrameworkVersion getVersion() { - return version; - } - - /** - * @param version - * the version to set - * @see #version - */ - public void setVersion(FrameworkVersion version) { - this.version = version; - } - - /** - * Returns {@link ConfigurationElementType#GOOGLE_ANALYTICS_IDENTIFIER google - * analytics identifier} used for tracking web-service usage. - * - * @return {@link ConfigurationElementType#GOOGLE_ANALYTICS_IDENTIFIER google - * analytics identifier} used for tracking web-service usage - */ - public String getGoogleAnalyticsIdentifier() { - return valueMap.get(ConfigurationElementType.GOOGLE_ANALYTICS_IDENTIFIER); - } - - /** - * Returns {@link ConfigurationElementType#LOGO_IMG logo image}. - * - * @return {@link ConfigurationElementType#LOGO_IMG logo image} - */ - public String getLogoImg() { - return valueMap.get(ConfigurationElementType.LOGO_IMG); - } - - /** - * Returns {@link ConfigurationElementType#LOGO_LINK logo link}. - * - * @return {@link ConfigurationElementType#LOGO_LINK logo link} - */ - public String getLogoLink() { - return valueMap.get(ConfigurationElementType.LOGO_LINK); - } - - /** - * Returns {@link ConfigurationElementType#LOGO_TEXT alt text for logo}. - * - * @return {@link ConfigurationElementType#LOGO_TEXT alt text for logo} - */ - public String getLogoText() { - return valueMap.get(ConfigurationElementType.LOGO_TEXT); - } - - /** - * Returns {@link ConfigurationElementType#LEGEND_FILE_1 legend file 1}. - * - * @return {@link ConfigurationElementType#LEGEND_FILE_1 legend file 1} - */ - public String getLegendFile1() { - return valueMap.get(ConfigurationElementType.LEGEND_FILE_1); - } - - /** - * Returns {@link ConfigurationElementType#LEGEND_FILE_2 legend file 2}. - * - * @return {@link ConfigurationElementType#LEGEND_FILE_2 legend file 2} - */ - public String getLegendFile2() { - return valueMap.get(ConfigurationElementType.LEGEND_FILE_2); - } - - /** - * Returns {@link ConfigurationElementType#LEGEND_FILE_3 legend file 3}. - * - * @return {@link ConfigurationElementType#LEGEND_FILE_3 legend file 3} - */ - public String getLegendFile3() { - return valueMap.get(ConfigurationElementType.LEGEND_FILE_3); - } - - /** - * Returns {@link ConfigurationElementType#LEGEND_FILE_4 legend file 4}. - * - * @return {@link ConfigurationElementType#LEGEND_FILE_4 legend file 4} - */ - public String getLegendFile4() { - return valueMap.get(ConfigurationElementType.LEGEND_FILE_4); - } - - /** - * Returns {@link ConfigurationElementType#USER_MANUAL_FILE user manual file}. - * - * @return {@link ConfigurationElementType#USER_MANUAL_FILE user manual file} - */ - public String getUserManual() { - return valueMap.get(ConfigurationElementType.USER_MANUAL_FILE); - } - - /** - * Returns {@link String} with estimated current memory usage (in MB). - * - * @return estimated current memory usage (in MB) - */ - public String getMemoryUsage() { - return NumberFormat.getInstance().format(configurationService.getMemoryUsage()) + " MB"; - } - - /** - * Returns {@link String} with max memory available to JVM (in MB). - * - * @return max memory available to JVM (in MB) - */ - public String getMaxMemory() { - return NumberFormat.getInstance().format(configurationService.getMaxMemory()) + " MB"; - } - - /** - * Returns {@link ConfigurationElementType#MIN_COLOR_VAL color} used for - * representing overlay element with negative values. - * - * @return {@link ConfigurationElementType#MIN_COLOR_VAL color} used for - * representing overlay element with negative values - */ - public String getMinColor() { - return valueMap.get(ConfigurationElementType.MIN_COLOR_VAL); - } - - /** - * Returns {@link ConfigurationElementType#MIN_COLOR_VAL color} used for - * representing overlay element with negative values. - * - * @return {@link ConfigurationElementType#MIN_COLOR_VAL color} used for - * representing overlay element with positive values - */ - public String getMaxColor() { - return valueMap.get(ConfigurationElementType.MAX_COLOR_VAL); - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/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 278b5f362fc4403159aaeba007b62b53ea736b26..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/GalaxyBean.java +++ /dev/null @@ -1,222 +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.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"); - - String token = userService.login(login, password); - Model model = (Model) modelService.getLastModelByProjectId(modelName, token); - User user = null; - if (token != null) { - user = userService.getUserByToken(token); - } - LayoutView layout = layoutService.getLayoutByName(model, identifier); - if (identifier == null) { - status = "ERROR. Identifier cannot be null"; - } else if (schema == null) { - status = "ERROR. Expression values schema cannot be null"; - } else if (user == null) { - status = "ERROR. Invalid credentials."; - } else if (modelName == null) { - status = "ERROR. Model cannot be null."; - } else if (model == null) { - status = "ERROR. " + modelName + " model doesn't exist."; - } else if (layout != null) { - status = "ERROR. Layout with given identifier (\"" + identifier + "\") already exists."; - } else { - createLayout(identifier, schema, model, user); - } - if (!status.equals("OK")) { - logger.warn("Problem in galaxy connector: " + status); - } - } catch (Exception e) { - logger.error(e, e); - status = "INTERNAL SERVER ERROR"; - } - } else { - logger.debug("Status already set..."); - } - return status; - } - - /** - * Creates layout from coloring data. - * - * @param identifier - * identifier of layout - * @param schema - * coloring schema (in string format) - * @param model - * model for which we create layout - * @param user - * user who will own the layout - */ - protected void createLayout(String identifier, String schema, Model model, User user) { - String directory = getProjectDeployPath() + "../map_images/" + model.getProject().getDirectory() + "/" - + model.getProject().getProjectId() + Math.random(); - - InputStream stream = new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8)); - // the following call will execute asynchronically - try { - CreateLayoutParams params = new CreateLayoutParams().name(identifier).// - directory(directory).// - model(model).// - colorInputStream(stream).// - user(user).// - async(true); - layoutService.createLayout(params); - status = "OK"; - - } catch (InvalidColorSchemaException e) { - status = "Problem with input file: " + e.getMessage(); - } catch (Exception e) { - logger.error(e, e); - status = "Internal server error. More details can be found in log file."; - } - } - - /** - * @param status - * the status to set - * @see #status - */ - public void setStatus(String status) { - this.status = status; - } - - /** - * @return the modelService - * @see #modelService - */ - public IModelService getModelService() { - return modelService; - } - - /** - * @param modelService - * the modelService to set - * @see #modelService - */ - public void setModelService(IModelService modelService) { - this.modelService = modelService; - } - - /** - * @return the layoutService - * @see #layoutService - */ - public ILayoutService getLayoutService() { - return layoutService; - } - - /** - * @param layoutService - * the layoutService to set - * @see #layoutService - */ - public void setLayoutService(ILayoutService layoutService) { - this.layoutService = layoutService; - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - @Override - public void init() { - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java b/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java deleted file mode 100644 index 89300005b0100ec6299c0e1aa6142cbbfa376fc5..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/LayoutBean.java +++ /dev/null @@ -1,814 +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 - * @throws SecurityException - */ - public void addAnonymousLayout(ProjectView project) throws SecurityException { - errorOccurred = false; - Model model = modelService.getLastModelByProjectId(project.getProjectId(), userBean.getAuthenticationToken()); - addLayout(model, null); - } - - /** - * This method adds new layout to the model given in parameter. - * - * - * @param model - * where the new layout should be added - * @param user - * who should be the owenr of new layout (if <code>null</code> the - * layout will be available to everybody) - */ - private void addLayout(Model model, User user) { - if (model == null) { - errorOccurred = true; - sendError("Unknown model."); - return; - } - try { - String directory = getProjectDeployPath() + "../map_images/" + model.getProject().getDirectory() + "/" - + model.getProject().getProjectId() + Math.random(); - - // the following call will execute asynchronically - CreateLayoutParams params = new CreateLayoutParams().name(layoutName).// - directory(directory).// - model(model).// - description(layoutDescription).// - colorInputStream(new FileInputStream(layoutFile)).// - layoutFileName(layoutFile.getName()).// - user(user).// - colorSchemaType(layoutType).// - async(true); - LayoutView view = layoutService.createLayout(params); - layoutName = ""; - layoutFile = null; - - ObjectAddedEvent event = new ObjectAddedEvent(view); - super.callListeners(event); - - sendInfo("File processed successfully. Generating layout."); - } catch (IOException e) { - errorOccurred = true; - logger.error("Problem with uploading layout", e); - sendError(e.getMessage()); - } catch (InvalidColorSchemaException e) { - errorOccurred = true; - logger.error("Problem with uploading layout", e); - sendError(e.getMessage()); - } catch (Exception e) { - logger.error("Problem with uploading layout", e); - sendError("Unknown problem with uploaded file..."); - } - } - - /** - * This method adds a new custom layout to currently selected map. - * - * @param actionEvent - * event from thefrom the client - */ - public void addLayout(final ActionEvent actionEvent) { - errorOccurred = false; - User user = userBean.getLoggedUser(); - Model model = getCurrentTopModel(); - - if (!getUserHasAddLayoutPrivilege()) { - errorOccurred = true; - sendError("You cannot add new layout"); - return; - } - addLayout(model, user); - } - - /** - * Removes layout selected by the client. - * - * @param actionEvent - * action event from client side - */ - public void removeLayout(final ActionEvent actionEvent) { - removeLayout(selectedLayout); - } - - /** - * Removes layout given in the parameter. - * - * @param layout - * layout that should be removed - */ - public void removeLayout(LayoutView layout) { - errorOccurred = false; - try { - User user = userBean.getLoggedUser(); - if (!layoutService.userCanRemoveLayout(layout, user)) { - errorOccurred = true; - sendError("You cannot remove this layout"); - return; - } - layoutService.removeLayout(layout, getProjectDeployPath()); - - ObjectRemovedEvent event = new ObjectRemovedEvent(layout); - super.callListeners(event); - } catch (Exception e) { - errorOccurred = true; - sendError("Problem with removing layout", e); - } - } - - /** - * Updates selectedLayout in the service layer. - * - * @param actionEvent - * action event from client side - */ - public void updateLayout(final ActionEvent actionEvent) { - errorOccurred = false; - if (!getUserHasRemoveLayoutPrivilege()) { - errorOccurred = true; - sendError("You cannot update this layout"); - return; - } - try { - layoutService.updateLayout(selectedLayout); - refreshCustomLayouts(actionEvent); - } catch (Exception e) { - errorOccurred = true; - sendError("Problem with updating layout", e); - } - } - - /** - * Updates layout in the service layer. - * - * @param layout - * layout for update - */ - public void updateLayout(final LayoutView layout) { - errorOccurred = false; - User user = userBean.getLoggedUser(); - if (!layoutService.userCanRemoveLayout(layout, user)) { - errorOccurred = true; - sendError("You cannot update this layout"); - return; - } - try { - layoutService.updateLayout(layout); - refreshCustomLayouts(null); - } catch (Exception e) { - errorOccurred = true; - sendError("Problem with updating layout", e); - } - } - - /** - * Returns the number of layouts that can be uploaded by the user. - * - * @return number of layouts that can still be uploaded by the user - */ - public int getAvailableCustomLayoutNumber() { - User user = userBean.getLoggedUser(); - return (int) layoutService.getAvailableCustomLayoutsNumber(user); - } - - @Override - public void clear() { - setCustomLayouts(null); - setSelectedLayout(null); - setLayoutFile(null); - setLayoutName(null); - setErrorOccurred(false); - setLayoutType(ColorSchemaType.GENERIC); - } - - /** - * @return the userBean - * @see #userBean - */ - public UserBean getUserBean() { - return userBean; - } - - /** - * @param userBean - * the userBean to set - * @see #userBean - */ - public void setUserBean(UserBean userBean) { - this.userBean = userBean; - } - - /** - * @return the layoutService - * @see #layoutService - */ - public ILayoutService getLayoutService() { - return layoutService; - } - - /** - * @param layoutService - * the layoutService to set - * @see #layoutService - */ - public void setLayoutService(ILayoutService layoutService) { - this.layoutService = layoutService; - } - - /** - * @return the mapBean - * @see #mapBean - */ - public MapBean getMapBean() { - return mapBean; - } - - /** - * @param mapBean - * the mapBean to set - * @see #mapBean - */ - public void setMapBean(MapBean mapBean) { - this.mapBean = mapBean; - } - - /** - * @return the selectedLayout - * @see #selectedLayout - */ - public LayoutView getSelectedLayout() { - return selectedLayout; - } - - /** - * @param selectedLayout - * the selectedLayout to set - * @see #selectedLayout - */ - public void setSelectedLayout(LayoutView selectedLayout) { - this.selectedLayout = selectedLayout; - } - - /** - * @return the customLayouts - * @see #customLayouts - */ - public List<LayoutView> getCustomLayouts() { - return customLayouts; - } - - /** - * @param customLayouts - * the customLayouts to set - * @see #customLayouts - */ - public void setCustomLayouts(List<LayoutView> customLayouts) { - this.customLayouts = customLayouts; - } - - /** - * @return the layoutFile - * @see #layoutFile - */ - public File getLayoutFile() { - return layoutFile; - } - - /** - * @param layoutFile - * the layoutFile to set - * @see #layoutFile - */ - public void setLayoutFile(File layoutFile) { - File oldFile = this.layoutFile; - this.layoutFile = layoutFile; - firePropertyChange(LAYOUT_FILE_PROPERTY, oldFile, layoutFile); - } - - /** - * @return the layoutName - * @see #layoutName - */ - public String getLayoutName() { - return layoutName; - } - - /** - * @param layoutName - * the layoutName to set - * @see #layoutName - */ - public void setLayoutName(String layoutName) { - this.layoutName = layoutName; - } - - /** - * @return the errorOccurred - * @see #errorOccurred - */ - public boolean isErrorOccurred() { - return errorOccurred; - } - - /** - * @param errorOccurred - * the errorOccurred to set - * @see #errorOccurred - */ - public void setErrorOccurred(boolean errorOccurred) { - this.errorOccurred = errorOccurred; - } - - /** - * @return the visualizedLayout - * @see #visualizedLayout - */ - public LayoutView getVisualizedLayout() { - return visualizedLayout; - } - - /** - * @param visualizedLayout - * the visualizedLayout to set - * @see #visualizedLayout - */ - public void setVisualizedLayout(LayoutView visualizedLayout) { - this.visualizedLayout = visualizedLayout; - } - - /** - * Updates information in {@link #visualizedLayout} object. - * - * @param actionEvent - * action event from client side - */ - public void getVisualizedLayoutDetails(final ActionEvent actionEvent) { - if (visualizedLayout.getName() != null && !visualizedLayout.getName().trim().equals("")) { - visualizedLayout = layoutService.getLayoutByName(getCurrentTopModel(), visualizedLayout.getName()); - if (visualizedLayout == null) { - visualizedLayout = new LayoutView(); - } else { - // we have new element to vizualize - ObjectAddedEvent event = new ObjectAddedEvent(visualizedLayout); - super.callListeners(event); - } - } - } - - /** - * @return the generalLayouts - * @see #generalLayouts - */ - public List<LayoutView> getGeneralLayouts() { - return generalLayouts; - } - - /** - * @param generalLayouts - * the generalLayouts to set - * @see #generalLayouts - */ - public void setGeneralLayouts(List<LayoutView> generalLayouts) { - this.generalLayouts = generalLayouts; - } - - /** - * Method that allows to donlwoad input data for given layout. - * - * @param layout - * layout for which input data will be downloaded - * - * @throws IOException - * thrown when there are some problems with sending file - * @throws SecurityException - */ - public void downloadInputData(LayoutView layout) throws IOException, SecurityException { - // get input data from database - byte[] data = layoutService.getInputDataForLayout(layout, userBean.getAuthenticationToken()); - String string = new String(data, StandardCharsets.UTF_8); - - sendFileAsResponse(string, "layout_" + layout.getIdObject() + ".txt", MimeType.TEXT); - } - - /** - * @return the modelService - * @see #modelService - */ - public IModelService getModelService() { - return modelService; - } - - /** - * @param modelService - * the modelService to set - * @see #modelService - */ - public void setModelService(IModelService modelService) { - this.modelService = modelService; - } - - /** - * @return the layoutDescription - * @see #layoutDescription - */ - public String getLayoutDescription() { - return layoutDescription; - } - - /** - * @param layoutDescription - * the layoutDescription to set - * @see #layoutDescription - */ - public void setLayoutDescription(String layoutDescription) { - this.layoutDescription = layoutDescription; - } - - /** - * This method sends list of aliases that should be visualized in a - * {@link lcsb.mapviewer.model.map.layout.Layout} to the browser. - * - * @throws IOException - * thrown when there is a problem with accessing information about - * layout - */ - public void retreiveActiveAliasesForLayout() throws IOException { - int layoutId = Integer.valueOf(getRequestParameter("layoutId").replace("cv", "")); - String string = "[]"; - try { - List<LightLayoutAliasView> list = layoutService.getAliasesForLayout(getCurrentTopModel(), layoutId, - userBean.getAuthenticationToken()); - LightLayoutAliasViewFactory factory = new LightLayoutAliasViewFactory(); - string = factory.createGson(list); - } catch (Exception e) { - sendError("Internal server error", e); - } - executeJavascript("ServerConnector.addAliasesForLayout('" + layoutId + "','" + string + "');"); - } - - /** - * This method sends full information about aliases that are visualized in a - * {@link lcsb.mapviewer.model.map.layout.Layout} to the browser and identified - * by list of identifiers. - * - * @throws IOException - * thrown when there is a problem with accessing information about - * layout - */ - public void retreiveFullAliasesForLayout() { - int layoutId = Integer.valueOf(getRequestParameter("layoutId").replace("cv", "")); - String string = "[]"; - try { - List<Pair<Integer, Integer>> identifiers = deserializeJsonIds(getRequestParameter("ids")); - List<FullLayoutAliasView> list = layoutService.getFullAliasesForLayoutByIds(getCurrentTopModel(), identifiers, - layoutId, userBean.getAuthenticationToken()); - string = new FullLayoutAliasViewFactory().createGson(list); - } catch (Exception e) { - sendError("Internal server error", e); - } - executeJavascript("ServerConnector.updateAliasesForLayout('" + layoutId + "','" + string + "');"); - } - - /** - * This method sends list of reactions that should be visualized in a - * {@link lcsb.mapviewer.model.map.layout.Layout} to the browser. - * - * @throws IOException - * thrown when there is a problem with accessing information about - * layout - */ - public void retreiveActiveReactionsForLayout() throws IOException { - int layoutId = Integer.valueOf(getRequestParameter("layoutId").replace("cv", "")); - String string = "[]"; - try { - List<LightLayoutReactionView> list = layoutService.getReactionsForLayout(getCurrentTopModel(), layoutId, - userBean.getAuthenticationToken()); - LightLayoutReactionViewFactory factory = new LightLayoutReactionViewFactory(); - string = factory.createGson(list); - } catch (Exception e) { - sendError("Internal server error", e); - } - executeJavascript("ServerConnector.addReactionsForLayout('" + layoutId + "','" + string + "');"); - } - - /** - * @return the layoutType - * @see #layoutType - */ - public ColorSchemaType getLayoutType() { - return layoutType; - } - - /** - * @param layoutType - * the layoutType to set - * @see #layoutType - */ - public void setLayoutType(ColorSchemaType layoutType) { - this.layoutType = layoutType; - } - - /** - * Returns list of available layout types. - * - * @return list of available layout types - */ - public ColorSchemaType[] getColorSchemaTypes() { - return ColorSchemaType.values(); - } - - /** - * Returns currently browsed map. - * - * @return currently browsed map - */ - private Model getCurrentTopModel() { - return mapBean.getCurrentTopModel(); - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/MapBean.java b/web/src/main/java/lcsb/mapviewer/bean/MapBean.java deleted file mode 100644 index bf2709f766b291eef1fb78ad4c7170f014474a41..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/MapBean.java +++ /dev/null @@ -1,1037 +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.SecurityException; -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) { - try { - setCurrentTopModel(getModelService().getLastModelByProjectId((String) arg0.getOldValue(), - userBean.getAuthenticationToken())); - } catch (SecurityException e1) { - logger.error(e1, e1); - } - logger.error(e, e); - } - } - } - - }; - addPropertyChangeListener(mapIdChangeListener); - - // when we change id we should propagate the change to model - VetoableChangeListener vetoMapIdChangeListener = new VetoableChangeListener() { - @Override - public void vetoableChange(PropertyChangeEvent arg0) throws PropertyVetoException { - if (!getProjectService().projectExists((String) arg0.getNewValue())) { - throw new PropertyVetoException("Project with id \"" + arg0.getNewValue() + "\" doesn't exist.", arg0); - } - } - - }; - addVetoablePropertyChangeListener(vetoMapIdChangeListener); - - // set id from request parameters (id is the url GET parameter) - setCurrentMapId(getRequestParameter("id")); - - } - - /** - * Refresh information about models. - */ - protected void updateModelView() { - - Model model = getCurrentTopModel(); - // configuration - ModelView topView = modelService.getModelView(model, userBean.getLoggedUser()); - - mapDataList = new ArrayList<>(); - - ClientMapData cmd = new ClientMapData(); - cmd.setMapConfig(topView); - cmd.setType("N/A"); - // coordinates converter - cmd.setcConverter(new CoordinationConverter(model)); - - mapDataList.add(cmd); - topModelMapData = cmd; - - for (ModelView view : topView.getSubmodels()) { - cmd = new ClientMapData(); - cmd.setMapConfig(view); - // coordinates converter - cmd.setcConverter(new CoordinationConverter(model.getSubmodelById(view.getIdObject()))); - cmd.setType(model.getSubmodelConnectionById(view.getIdObject()).getType().getCommonName()); - mapDataList.add(cmd); - } - } - - /** - * This method center map in the client using coordinates from client. - * - * @param actionEvent - * event from thefrom the client - */ - public void centerMap(final ActionEvent actionEvent) { - createSubmodelDialog(actionEvent); - - // we have plain coordinates (not lat lng) - String xCoord = getRequestParameter("xCoord"); - String yCoord = getRequestParameter("yCoord"); - String modelIdentifier = getRequestParameter("submodelId"); - if (modelIdentifier == null) { - sendError("submodelId param wasn't set"); - return; - } - Integer modelId = Integer.valueOf(modelIdentifier); - - ClientMapData selectedMapData = null; - for (ClientMapData mapData : getMapDataList()) { - if (mapData.getMapConfig().getIdObject().equals(modelId)) { - selectedMapData = mapData; - } - } - if (selectedMapData == null) { - sendError("Cannot find map with the identifier: " + modelId); - return; - } - - LatLng latLng; - if (xCoord != null && yCoord != null) { - double x = Double.parseDouble(xCoord); - double y = Double.parseDouble(yCoord); - latLng = selectedMapData.getcConverter().toLatLng(new Point2D.Double(x, y)); - } else { - String latCoord = getRequestParameter("latCoord"); - String lngCoord = getRequestParameter("lngCoord"); - double lat = Double.parseDouble(latCoord); - double lng = Double.parseDouble(lngCoord); - latLng = new LatLng(lat, lng); - } - centerMapInJavascript(latLng, selectedMapData); - } - - /** - * Method responsible for centering map in client using coordinates given as a - * parameter. - * - * @param mapData - * defines which map we want to center. If the value is not set then - * default one is selected - * - * @param latLng - * - coordinates - */ - private void centerMapInJavascript(final LatLng latLng, ClientMapData mapData) { - double lat = latLng.getLat(); - double lng = latLng.getLng(); - logger.debug("Center map in js (" + lat + "," + lng + ")"); - executeJavascript("customMap.setCenter(" + mapData.getMapConfig().getIdObject() + ", new google.maps.LatLng(" + lat - + "," + lng + "));"); - } - - /** - * Check if user can see the map. - * - * @return <i>true</i> if user can see the map,<br/> - * <i> false otherwise</i> - */ - public boolean getUserHasViewPrivilege() { - Project project = getCurrentProject(); - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, project); - if (!result) { - logger.debug("User doesn't have privilege"); - } - return result; - } - - /** - * This is artifitial method called by the client side to pass some parameters - * to the bean: - * <ul> - * <li>{@link #centerCoordinateX},</li> - * <li>{@link #centerCoordinateY},</li> - * <li>{@link #selectedLayout},</li> - * <li>{@link #zoomLevel}.</li> - * </ul> - */ - public void actualizeParams() { - - } - - /** - * Returns the index of layout that is currently visualized. - * - * @return index of layout that is currently visualized. - */ - public Integer getSelectedLayoutIdentifier() { - if (topModelMapData.getSelectedLayout() == null) { - return null; - } else { - String str = topModelMapData.getSelectedLayout().replaceAll("[^0-9]", ""); - Integer id = null; - try { - id = Integer.parseInt(str); - } catch (NumberFormatException e) { - logger.warn("Problem with layout identifier: " + topModelMapData.getSelectedLayout()); - } - return id; - } - } - - /** - * Returns level on which the map is currently browsed. It's not equal to the - * zoom level, becuse zoom level is shifted by - * {@link lcsb.mapviewer.common.Configuration.MIN_ZOOM_LEVEL} value. - * - * @param mapData - * defines on which map we are looking for zoom level. If the value is - * not set then default one is selected - * @return level on which the map is currently browsed - */ - public Integer getLevel(ClientMapData mapData) { - String zoomLevel = mapData.getZoomLevel(); - if (zoomLevel == null) { - return null; - } - Integer res = null; - try { - res = Integer.valueOf(zoomLevel) - Configuration.MIN_ZOOM_LEVEL; - } catch (NumberFormatException e) { - logger.warn("Problem with zoomLevel: " + zoomLevel); - } - return res; - } - - @Override - public void clear() { - throw new NotImplementedException(); - } - - /** - * @return the modelService - * @see #modelService - */ - public IModelService getModelService() { - return modelService; - } - - /** - * @param modelService - * the modelService to set - * @see #modelService - */ - public void setModelService(IModelService modelService) { - this.modelService = modelService; - } - - /** - * @return the userBean - * @see #userBean - */ - public UserBean getUserBean() { - return userBean; - } - - /** - * @param userBean - * the userBean to set - * @see #userBean - */ - public void setUserBean(UserBean userBean) { - this.userBean = userBean; - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - /** - * @return the mapDataList - * @see #mapDataList - */ - public List<ClientMapData> getMapDataList() { - return mapDataList; - } - - /** - * Creates dialog on client side for submodel. - * - * @param actionEvent - * event from the client - */ - public void createSubmodelDialog(final ActionEvent actionEvent) { - try { - String dialogGroup = "_gmapForm:submodelDialogGroup"; - String idParamName = "submodelId"; - String dialogIdPrefix = "submodelDialog"; - - UIComponent panelGroup = findComponent(dialogGroup); - if (panelGroup == null) { - sendError("Cannot find " + dialogGroup + " component."); - return; - } - String id = getRequestParameter(idParamName); - if (id == null) { - sendError(idParamName + " request param cannot be null."); - return; - } - if (id.equals(getCurrentTopModel().getId() + "")) { - logger.debug("TopModel doesn't require window"); - return; - } - id = dialogIdPrefix + id; - for (UIComponent child : panelGroup.getChildren()) { - if (child instanceof Dialog) { - if (child.getId().equals(id)) { - logger.debug("Dialog " + id + " found"); - return; - } - } - } - for (ModelSubmodelConnection model : getCurrentTopModel().getSubmodelConnections()) { - Integer modelId = model.getSubmodel().getId(); - id = dialogIdPrefix + modelId; - Dialog dialog = new Dialog(); - dialog.setId(id); - dialog.setWidgetVar(id); - dialog.setHeader("Submodel: " + model.getSubmodel().getName()); - dialog.setMinimizable(true); - panelGroup.getChildren().add(dialog); - } - - RequestContext requestContext = RequestContext.getCurrentInstance(); - requestContext.update(dialogGroup); - - } catch (Exception e) { - logger.error(e, e); - sendError(e.getMessage()); - } - } - - /** - * Returns map configuration in Gson format. - * - * @return map configuration in Gson format - */ - public String getGsonConfiguration() { - return new Gson().toJson(getMapDataList().get(0).getMapConfig()); - } - - /** - * @return the topModelMapData - * @see #topModelMapData - */ - public ClientMapData getTopModelMapData() { - if (topModelMapData == null) { - updateModelView(); - } - return topModelMapData; - } - - /** - * @param topModelMapData - * the topModelMapData to set - * @see #topModelMapData - */ - public void setTopModelMapData(ClientMapData topModelMapData) { - this.topModelMapData = topModelMapData; - } - - /** - * Returns {@link ClientMapData} for (sub)model identified by identifier. - * - * @param identifier - * identifier of the model - * @return {@link ClientMapData} - */ - public ClientMapData getMapDataByMapIdentifier(String identifier) { - Integer id = Integer.parseInt(identifier); - return getMapDataByMapIdentifier(id); - } - - /** - * Returns {@link ClientMapData} for (sub)model identified by identifier. - * - * @param identifier - * identifier of the model - * @return {@link ClientMapData} - */ - public ClientMapData getMapDataByMapIdentifier(Integer identifier) { - // in case we haven't initialized mapdata we need to do it here (it's a - // workaround...) - if (getMapDataList().size() == 0) { - updateModelView(); - } - for (ClientMapData md : getMapDataList()) { - if (md.getMapConfig().getIdObject().equals(identifier)) { - return md; - } - } - return null; - } - - /** - * @return the configurationService - * @see #configurationService - */ - public IConfigurationService getConfigurationService() { - return configurationService; - } - - /** - * @param configurationService - * the configurationService to set - * @see #configurationService - */ - public void setConfigurationService(IConfigurationService configurationService) { - this.configurationService = configurationService; - } - - /** - * Sets zoom level for submodel. Parameters are passed using http request - * mechainsm/ - */ - public void setModelZoomLevel() { - String mapId = getRequestParameter("mapId"); - String zoomLevel = getRequestParameter("zoomLevel"); - - Integer id = Integer.valueOf(mapId); - - for (ClientMapData cmd : getMapDataList()) { - if (cmd.getMapConfig().getIdObject().equals(id)) { - cmd.setZoomLevel(zoomLevel); - return; - } - } - sendError("Cannot find model with id: " + id); - - } - - /** - * Sends list of aliases (with given identifiers) to the browser. Identifiers - * are passed as a json string in request parameter <i>ids</i>. Each identifier - * is a pair containing information about {@link Model#getId() model id} and - * {@link lcsb.mapviewer.model.map.species.Element#id alias id}. Data is very - * light - contains only information about the location on the model. - * - */ - public void retreiveLightAliases() { - List<Pair<Integer, Integer>> identifiers = deserializeJsonIds(getRequestParameter("ids")); - List<LightAliasView> list = modelService.getLightAliasesByIds(getCurrentTopModel(), identifiers); - LightAliasViewFactory factory = new LightAliasViewFactory(); - String string = factory.createGson(list); - executeJavascript("ServerConnector.addAliases(" + string + ");"); - } - - /** - * Sends list of reactions (with given identifiers) to the browser. Identifiers - * are passed as a json string in request parameter <i>ids</i>. Each identifier - * is a pair containing information about {@link Model#getId() model id} and - * {@link lcsb.mapviewer.model.map.reaction.Reaction#id reaction id}. - * - */ - public void retreiveLightReactions() { - List<Pair<Integer, Integer>> identifiers = deserializeJsonIds(getRequestParameter("ids")); - List<LightReactionView> list = modelService.getLightReactionsByIds(getCurrentTopModel(), identifiers); - LightReactionViewFactory factory = new LightReactionViewFactory(); - String string = factory.createGson(list); - executeJavascript("ServerConnector.addReactions('" + string + "');"); - } - - /** - * @return the fullAliasViewFactory - * @see #fullAliasViewFactory - */ - public FullAliasViewFactory getFullAliasViewFactory() { - if (fullAliasViewFactory == null) { - fullAliasViewFactory = findBean(FullAliasViewFactory.class); - } - return fullAliasViewFactory; - } - - /** - * @param fullAliasViewFactory - * the fullAliasViewFactory to set - * @see #fullAliasViewFactory - */ - public void setFullAliasViewFactory(FullAliasViewFactory fullAliasViewFactory) { - this.fullAliasViewFactory = fullAliasViewFactory; - } - - /** - * @return the currentMapId - * @see #currentMapId - */ - public final String getCurrentMapId() { - // if user didn't provide id then use default one - if (currentMapId == null) { - String tmp = confService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); - if (tmp == null) { - logger.warn("Cannot find default map in the system."); - } - setCurrentMapId(tmp); - } - return currentMapId; - } - - /** - * @param currentMapId - * the currentMapId to set - * @see #currentMapId - */ - public final void setCurrentMapId(String currentMapId) { - try { - fireVetoableChange(CURRENT_MODEL_ID_PROPERTY, this.currentMapId, currentMapId); - String oldValue = this.currentMapId; - this.currentMapId = currentMapId; - firePropertyChange(CURRENT_MODEL_ID_PROPERTY, oldValue, currentMapId); - } catch (PropertyVetoException e) { - logger.warn("Cannot change property: " + CURRENT_MODEL_ID_PROPERTY + ". Form: \"" + this.currentMapId - + "\" into: \"" + currentMapId + "\""); - } - } - - /** - * Return {@link #currentMap currently browsed map}. - * - * @return currently browsed map - */ - protected final Model getCurrentTopModel() { - if (currentMap == null) { - try { - setCurrentTopModel( - this.getModelService().getLastModelByProjectId(getCurrentMapId(), userBean.getAuthenticationToken())); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return currentMap; - } - - /** - * @return the currentProject - * @see #currentProject - */ - public Project getCurrentProject() { - return getCurrentTopModel().getProject(); - } - - /** - * @param topModel - * the topModel to set - * @see #currentMap - */ - private void setCurrentTopModel(Model topModel) { - Model oldValue = this.currentMap; - this.currentMap = topModel; - firePropertyChange(CURRENT_MODEL_PROPERTY, oldValue, topModel); - } - - /** - * @return the currentProjectView - * @see #currentProjectView - */ - public ProjectView getCurrentProjectView() { - return currentProjectView; - } - - /** - * @param currentProjectView - * the currentProjectView to set - * @see #currentProjectView - */ - public void setCurrentProjectView(ProjectView currentProjectView) { - this.currentProjectView = currentProjectView; - } - - /** - * @return the projectService - * @see #projectService - */ - public IProjectService getProjectService() { - return projectService; - } - - /** - * @param projectService - * the projectService to set - * @see #projectService - */ - public void setProjectService(IProjectService projectService) { - this.projectService = projectService; - } - - /** - * @return the confService - * @see #confService - */ - public IConfigurationService getConfService() { - return confService; - } - - /** - * @param confService - * the confService to set - * @see #confService - */ - public void setConfService(IConfigurationService confService) { - this.confService = confService; - } - - /** - * Returns organism associated with currently viewed project. If organism is not - * set then {@link #DEFAULT_ORGANISM} is returned. - * - * @return organism associated with currently viewed project - */ - public MiriamData getOrganism() { - MiriamData organism = getCurrentProject().getOrganism(); - if (organism == null || organism.getResource().isEmpty()) { - organism = DEFAULT_ORGANISM; - } - return organism; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/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 6a6c30a73b45ce4dc5f82c14421deb226c664252..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/ProjectBean.java +++ /dev/null @@ -1,1523 +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; - try { - localProjectList = projectService.getAllProjectViews(userBean.getAuthenticationToken()); - for (ProjectView projectRow : localProjectList) { - projects.add(projectRow); - } - Collections.sort(projects); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - /** - * This method handle upload of a file. - * - * @param event - * event send by the client with a file reference - */ - public void handleFileUpload(final FileUploadEvent event) { - try { - logger.debug(event.getFile().getFileName() + " is uploaded."); - UploadedFile uploadedFile = event.getFile(); - String filename = FilenameUtils.getBaseName(uploadedFile.getFileName()); - String extension = FilenameUtils.getExtension(uploadedFile.getFileName()); - File file = File.createTempFile(filename + "-cd-", "." + extension); - file.delete(); - InputStream input = uploadedFile.getInputstream(); - Files.copy(input, file.toPath()); - input.close(); - - this.setMapFile(file); - } catch (Exception e) { - sendError("Problem with uploading...", e); - } - } - - /** - * Generates project based on the information provided by the client. - * - * @param file - * file with the model in CellDesigner format - * @throws SecurityException - */ - protected void generateProject(final File file) throws SecurityException { - // if project with this name already exists then add random suffix - String projectId = getNewProjectId(); - if (projectService.projectExists(getNewProjectId())) { - sendError("Project with identifier: \"" + getNewProjectId() + "\" already exists."); - return; - } - - // get proper paths: - // to directory with images - String imagePath = getProjectDeployPath() + "/../map_images/" + md5(projectId) + "/"; - String version = getNewMapVersion(); - - boolean autoResize = newMapAutoResize.equalsIgnoreCase("true"); - - CreateProjectParams params = new CreateProjectParams(); - - params.complex("true".equalsIgnoreCase(complexModel)); - params.projectId(projectId); - params.projectName(newProjectName); - params.projectDisease(newProjectDisease); - params.projectOrganism(newProjectOrganism); - params.version(version); - params.projectFile(file); - params.autoResize(autoResize); - params.images(true); - params.async(true); - params.notifyEmail(userBean.getLoggedUser().getEmail()); - params.projectDir(imagePath); - params.annotatorsMap(annotatorsTree); - params.addUser(userBean.getLogin(), null); - params.annotations("true".equalsIgnoreCase(annotateModel)); - params.analyzeAnnotations("true".equalsIgnoreCase(verifyAnnotationsModel)); - params.cacheModel("true".equalsIgnoreCase(cacheModel)); - params.validAnnotations(annotatorsTree); - params.requiredAnnotations(annotatorsTree); - params.authenticationToken(userBean.getAuthenticationToken()); - for (ZipEntryFile submodel : getZipEntries()) { - params.addZipEntry(submodel); - } - params.sbgnFormat("true".equalsIgnoreCase(sbgnFormat)); - params.semanticZoom("true".equalsIgnoreCase(semanticOverlay)); - params.networkLayoutAsDefault("true".equalsIgnoreCase(networkLayoutAsDefault)); - projectService.createProject(params); - projectService.updateClassAnnotatorTreeForUser(userBean.getLoggedUser(), annotatorsTree, - sbgnFormat.equalsIgnoreCase("true"), networkLayoutAsDefault.equalsIgnoreCase("true")); - - ObjectAddedEvent event = new ObjectAddedEvent( - projectService.getProjectByProjectId(projectId, userBean.getAuthenticationToken())); - callListeners(event); - } - - /** - * Returns list of all zip entries in the currently processed file. - * - * @return list of all zip entries in the currently processed file - */ - private Collection<ZipEntryFile> getZipEntries() { - List<ZipEntryFile> result = new ArrayList<ZipEntryFile>(); - result.addAll(modelZipEntries); - result.addAll(imageZipEntries); - result.addAll(layoutZipEntries); - result.addAll(dataMiningZipEntries); - return result; - } - - /** - * Method that computes md5 hash for a given {@link String}. - * - * @param data - * input string - * @return md5 hash for input string - */ - private String md5(String data) { - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - byte[] mdbytes = md.digest(data.getBytes()); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < mdbytes.length; i++) { - // CHECKSTYLE:OFF - // this magic formula transforms int into hex value - sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); - // CHECKSTYLE:ON - } - return sb.toString(); - } catch (NoSuchAlgorithmException e) { - logger.fatal("Problem with instance of MD5 encoder", e); - } - - return null; - } - - /** - * Returns project currently selected and edited by the client side. - * - * @return project view currently selected and edited by the client side - */ - public ProjectView getSelectedProject() { - if (selectedProject == null) { - selectedProject = projectService.createEmpty(); - } - return selectedProject; - } - - /** - * Set new currently selected and edited project. - * - * @param selectedProject - * view of the new currently selected and edited project - */ - public void setSelectedProject(final ProjectView selectedProject) { - ProjectView oldValue = this.selectedProject; - this.selectedProject = selectedProject; - try { - fireVetoableChange(SELECTED_PROJECT_PROPERTY, oldValue, selectedProject); - firePropertyChange(SELECTED_PROJECT_PROPERTY, oldValue, selectedProject); - logger.debug("Selected project was set to: " + this.selectedProject.getProjectId()); - } catch (PropertyVetoException e) { - this.selectedProject = oldValue; - sendError(e.getMessage(), e); - } - } - - /** - * Method which update a project. - * - * @param actionEvent - * event from thefrom the client - * @throws SecurityException - */ - public void updateSelectedProject(final ActionEvent actionEvent) throws SecurityException { - - // first we need small trick (maybe this should be improved) - - ProjectView newProject = selectedProject; - // get old version of the project from db - ProjectView oldProject = projectService.getProjectViewById(newProject.getIdObject(), - userBean.getAuthenticationToken()); - - // set old version - setSelectedProject(oldProject); - // now, change to the new one (property change listener will ensure that - // everything is fine) - setSelectedProject(newProject); - - // if everything is ok then update in db - if (selectedProject != null) { - projectService.updateProject(selectedProject); - } else { - logger.warn("Problem during updating project..."); - } - refreshProjectList(actionEvent); - - callListeners(new ObjectModifiedEvent(newProject)); - } - - /** - * Removes project selected by client. - * - * @param actionEvent - * client side action - */ - public void removeSelectedProject(final ActionEvent actionEvent) { - try { - logger.debug("Removing project: " + selectedProject); - String defaultMap = configurationService.getConfigurationValue(ConfigurationElementType.DEFAULT_MAP); - String projectId = selectedProject.getProjectId(); - - // find out what is the name of the project in db - ProjectView project = projectService.getProjectViewById(selectedProject.getIdObject(), - userBean.getAuthenticationToken()); - if (project != null) { - projectId = project.getProjectId(); - } - - logger.debug("Removing project: " + projectId); - - // if the project name is a default one then don't remove it - if (defaultMap.equals(projectId)) { - sendError("Cannot remove default map. To remove this map change the default map in configuration tab first."); - } else { - projectService.removeProject(selectedProject, getProjectDeployPath(), true, userBean.getAuthenticationToken()); - callListeners(new ObjectRemovedEvent(selectedProject)); - refreshProjectList(actionEvent); - } - } catch (Exception e) { - sendError("Internal server error", e); - } - } - - /** - * Checks if user can manage projects. - * - * @return <code>true</code> if user can amange projects, <code>false</code> - * otherwise - */ - public boolean getUserHasManagePrivileges() { - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.PROJECT_MANAGEMENT); - return result; - } - - /** - * Checks if user can add project. - * - * @return <code>true</code> if user can add projects, <code>false</code> - * otherwise - */ - public boolean getUserHasAddMapPrivileges() { - User user = userBean.getLoggedUser(); - boolean result = userService.userHasPrivilege(user, PrivilegeType.ADD_MAP); - return result; - } - - /** - * Gets project identifier for newly created project. - * - * @return name of the new project - */ - public String getNewProjectId() { - return newProjectId; - } - - /** - * Sets project identifier for the newly created project. - * - * @param newProjectId - * new name for the new project - */ - public void setNewProjectId(final String newProjectId) { - String oldValue = this.newProjectId; - this.newProjectId = newProjectId; - firePropertyChange(PROJECT_ID_PROPERTY, oldValue, newProjectId); - } - - /** - * @return {@link #newMapVersion} - */ - public String getNewMapVersion() { - return newMapVersion; - } - - /** - * Sets new value for {@link #newMapVersion}. Property change listeners will be - * thrown for "newMapVersion" property. - * - * @param newMapVersion - * {@link #newMapVersion} - */ - public void setNewMapVersion(final String newMapVersion) { - String oldValue = this.newMapVersion; - this.newMapVersion = newMapVersion; - firePropertyChange(MAP_VERSION_PROPERTY, oldValue, newMapVersion); - } - - /** - * - * @return {@link #mapFile} - */ - public File getMapFile() { - return mapFile; - } - - /** - * Sets new value for {@link #mapFile}. Property change listeners will be thrown - * for "mapFile" property. - * - * @param mapFile - * {@link #mapFile} - */ - public void setMapFile(final File mapFile) { - File oldValue = this.mapFile; - this.mapFile = mapFile; - firePropertyChange(MAP_FILE_PROPERTY, oldValue, mapFile); - } - - /** - * Method that creates a project. - */ - public void createProject() { - try { - if (getMapFile() == null) { - sendError("File cannot be null"); - } else { - generateProject(getMapFile()); - } - } catch (Exception e) { - sendError("Internal server error.", e); - } - } - - /** - * - * @return {@link #newMapAutoResize} - */ - public String getNewMapAutoResize() { - return newMapAutoResize; - } - - /** - * Sets new value for {@link #newMapAutoResize}. Property change listeners will - * be thrown for "newMapAutoResize" property. - * - * @param newMapAutoResize - * {@link #newMapAutoResize} - */ - public void setNewMapAutoResize(final String newMapAutoResize) { - String oldValue = this.newMapAutoResize; - this.newMapAutoResize = newMapAutoResize; - firePropertyChange(AUTO_RESIZE_MAP_PROPERTY, oldValue, newMapAutoResize); - } - - @Override - public void clear() { - throw new NotImplementedException(); - } - - /** - * @return the projectService - * @see #projectService - */ - public IProjectService getProjectService() { - return projectService; - } - - /** - * @param projectService - * the projectService to set - * @see #projectService - */ - public void setProjectService(IProjectService projectService) { - this.projectService = projectService; - } - - /** - * @return the projects - * @see #projects - */ - public List<ProjectView> getProjects() { - if (projects == null) { - projects = new ArrayList<>(); - refreshProjectList(null); - } - return projects; - } - - /** - * @param projects - * the projects to set - * @see #projects - */ - public void setProjects(List<ProjectView> projects) { - this.projects = projects; - } - - /** - * @return the userBean - * @see #userBean - */ - public UserBean getUserBean() { - return userBean; - } - - /** - * @param userBean - * the userBean to set - * @see #userBean - */ - public void setUserBean(UserBean userBean) { - this.userBean = userBean; - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - /** - * @return the modelService - * @see #modelService - */ - public IModelService getModelService() { - return modelService; - } - - /** - * @param modelService - * the modelService to set - * @see #modelService - */ - public void setModelService(IModelService modelService) { - this.modelService = modelService; - } - - /** - * @return the configurationService - * @see #configurationService - */ - public IConfigurationService getConfigurationService() { - return configurationService; - } - - /** - * @param configurationService - * the configurationService to set - * @see #configurationService - */ - public void setConfigurationService(IConfigurationService configurationService) { - this.configurationService = configurationService; - } - - /** - * @return the annotateModel - * @see #annotateModel - */ - public String getAnnotateModel() { - return annotateModel; - } - - /** - * @param annotateModel - * the annotateModel to set - * @see #annotateModel - */ - public void setAnnotateModel(String annotateModel) { - this.annotateModel = annotateModel; - } - - /** - * @return the cacheModel - * @see #cacheModel - */ - public String getCacheModel() { - return cacheModel; - } - - /** - * @param cacheModel - * the cacheModel to set - * @see #cacheModel - */ - public void setCacheModel(String cacheModel) { - this.cacheModel = cacheModel; - } - - /** - * @return the verifyAnnotationsModel - * @see #verifyAnnotationsModel - */ - public String getVerifyAnnotationsModel() { - return verifyAnnotationsModel; - } - - /** - * @param verifyAnnotationsModel - * the verifyAnnotationsModel to set - * @see #verifyAnnotationsModel - */ - public void setVerifyAnnotationsModel(String verifyAnnotationsModel) { - this.verifyAnnotationsModel = verifyAnnotationsModel; - } - - /** - * Method that exports selected project warnings. - * - * @throws IOException - * thrown when there are some problems with sending file - */ - public void downloadWarnings() throws IOException { - // and send it as response - sendFileAsResponse(StringUtils.join(selectedProject.getWarnings(), "\n"), "warnings.txt", MimeType.TEXT); - } - - /** - * @return the complexModel - * @see #complexModel - */ - public String getComplexModel() { - return complexModel; - } - - /** - * @param complexModel - * the complexModel to set - * @see #complexModel - */ - public void setComplexModel(String complexModel) { - this.complexModel = complexModel; - } - - /** - * Returns list of all available submodel types. - * - * @return list of all available submodel types - */ - public SubmodelType[] getSubmodelTypes() { - return SubmodelType.values(); - } - - /** - * Returns list of all possible {@link InputFileType}. - * - * @return array with all possible values of {@link InputFileType} enum - */ - public InputFileType[] getFileTypes() { - return InputFileType.values(); - } - - /** - * @return the annotatorsTree - * @see #annotatorsTree - */ - public TreeNode getAnnotatorsTree() { - return annotatorsTree; - } - - /** - * @param annotatorsTree - * the annotatorsTree to set - * @see #annotatorsTree - */ - public void setAnnotatorsTree(TreeNode annotatorsTree) { - this.annotatorsTree = annotatorsTree; - } - - /** - * @return the annotators - * @see #annotators - */ - public DualListModel<String> getAnnotators() { - return annotators; - } - - /** - * @param annotators - * the annotators to set - * @see #annotators - */ - public void setAnnotators(DualListModel<String> annotators) { - this.annotators = annotators; - } - - /** - * @return the selectedAnnotatorTreeNodeData - * @see #selectedAnnotatorTreeNodeData - */ - public AnnotatedObjectTreeRow getSelectedAnnotatorTreeNodeData() { - return selectedAnnotatorTreeNodeData; - } - - /** - * @param selectedAnnotatorTreeNodeData - * the selectedAnnotatorTreeNodeData to set - * @see #selectedAnnotatorTreeNodeData - */ - public void setSelectedAnnotatorTreeNodeData(AnnotatedObjectTreeRow selectedAnnotatorTreeNodeData) { - AnnotatedObjectTreeRow oldValue = this.selectedAnnotatorTreeNodeData; - this.selectedAnnotatorTreeNodeData = selectedAnnotatorTreeNodeData; - - firePropertyChange(SELECTED_ANNOTATOR_TREE_NODE_DATA_PROPERTY, oldValue, selectedAnnotatorTreeNodeData); - } - - /** - * Method called when list of annotators in {@link #annotators} changed. - * - * @param event - * primefaces event - */ - public void onTransfer(TransferEvent event) { - updateAnnotatorTreeNodeData(); - } - - /** - * This method updates data in {@link #selectedAnnotatorTreeNodeData}. - */ - private void updateAnnotatorTreeNodeData() { - this.selectedAnnotatorTreeNodeData.setValidAnnotators(annotators.getSource()); - this.selectedAnnotatorTreeNodeData.setUsedAnnotators(annotators.getTarget()); - this.selectedAnnotatorTreeNodeData.setMissingValidAnnotations(validMiriam.getSource()); - this.selectedAnnotatorTreeNodeData.setValidAnnotations(validMiriam.getTarget()); - this.selectedAnnotatorTreeNodeData.setMissingRequiredAnnotations(requiredMiriam.getSource()); - this.selectedAnnotatorTreeNodeData.setRequiredAnnotations(requiredMiriam.getTarget()); - } - - /** - * Method called when list of annotators in {@link #annotators} changed order. - */ - public void onReorder() { - updateAnnotatorTreeNodeData(); - } - - /** - * @return the validMiriam - * @see #validMiriam - */ - public DualListModel<MiriamType> getValidMiriam() { - return validMiriam; - } - - /** - * @param validMiriam - * the validMiriam to set - * @see #validMiriam - */ - public void setValidMiriam(DualListModel<MiriamType> validMiriam) { - this.validMiriam = validMiriam; - } - - /** - * @return the requiredMiriam - * @see #requiredMiriam - */ - public DualListModel<MiriamType> getRequiredMiriam() { - return requiredMiriam; - } - - /** - * @param requiredMiriam - * the requiredMiriam to set - * @see #requiredMiriam - */ - public void setRequiredMiriam(DualListModel<MiriamType> requiredMiriam) { - this.requiredMiriam = requiredMiriam; - } - - /** - * @return the dataMiningTypes - * @see #dataMiningTypes - */ - public List<DataMiningType> getDataMiningTypes() { - return dataMiningTypes; - } - - /** - * @param dataMiningTypes - * the dataMiningTypes to set - * @see #dataMiningTypes - */ - public void setDataMiningTypes(List<DataMiningType> dataMiningTypes) { - this.dataMiningTypes = dataMiningTypes; - } - - /** - * @return the layoutBean - * @see #layoutBean - */ - public LayoutBean getLayoutBean() { - return layoutBean; - } - - /** - * @param layoutBean - * the layoutBean to set - * @see #layoutBean - */ - public void setLayoutBean(LayoutBean layoutBean) { - this.layoutBean = layoutBean; - } - - /** - * Clears list with information about zip entries in currently processed zip - * file. - */ - private void clearZipEntriesData() { - dataMiningZipEntries.clear(); - imageZipEntries.clear(); - layoutZipEntries.clear(); - modelZipEntries.clear(); - - } - - /** - * @return the dataMiningZipEntries - * @see #dataMiningZipEntries - */ - public List<DataMiningZipEntryFile> getDataMiningZipEntries() { - return dataMiningZipEntries; - } - - /** - * @param dataMiningZipEntries - * the dataMiningZipEntries to set - * @see #dataMiningZipEntries - */ - public void setDataMiningZipEntries(List<DataMiningZipEntryFile> dataMiningZipEntries) { - this.dataMiningZipEntries = dataMiningZipEntries; - } - - /** - * @return the modelZipEntries - * @see #modelZipEntries - */ - public List<ModelZipEntryFile> getModelZipEntries() { - return modelZipEntries; - } - - /** - * @param modelZipEntries - * the modelZipEntries to set - * @see #modelZipEntries - */ - public void setModelZipEntries(List<ModelZipEntryFile> modelZipEntries) { - this.modelZipEntries = modelZipEntries; - } - - /** - * @return the layoutZipEntries - * @see #layoutZipEntries - */ - public List<LayoutZipEntryFile> getLayoutZipEntries() { - return layoutZipEntries; - } - - /** - * @param layoutZipEntries - * the layoutZipEntries to set - * @see #layoutZipEntries - */ - public void setLayoutZipEntries(List<LayoutZipEntryFile> layoutZipEntries) { - this.layoutZipEntries = layoutZipEntries; - } - - /** - * @return the imageZipEntries - * @see #imageZipEntries - */ - public List<ImageZipEntryFile> getImageZipEntries() { - return imageZipEntries; - } - - /** - * @param imageZipEntries - * the imageZipEntries to set - * @see #imageZipEntries - */ - public void setImageZipEntries(List<ImageZipEntryFile> imageZipEntries) { - this.imageZipEntries = imageZipEntries; - } - - /** - * @return the newProjectName - * @see #newProjectName - */ - public String getNewProjectName() { - return newProjectName; - } - - /** - * @param newProjectName - * the newProjectName to set - * @see #newProjectName - */ - public void setNewProjectName(String newProjectName) { - this.newProjectName = newProjectName; - } - - /** - * @return the sbgnFormat - * @see #sbgnFormat - */ - public String getSbgnFormat() { - return sbgnFormat; - } - - /** - * @param sbgnFormat - * the sbgnFormat to set - * @see #sbgnFormat - */ - public void setSbgnFormat(String sbgnFormat) { - this.sbgnFormat = sbgnFormat; - } - - /** - * @return the networkLayoutAsDefault - * @see #networkLayoutAsDefault - */ - public String getNetworkLayoutAsDefault() { - return networkLayoutAsDefault; - } - - /** - * @param networkLayoutAsDefault - * the networkLayoutAsDefault to set - * @see #networkLayoutAsDefault - */ - public void setNetworkLayoutAsDefault(String networkLayoutAsDefault) { - this.networkLayoutAsDefault = networkLayoutAsDefault; - } - - /** - * @return new project disease. - */ - public String getNewProjectDisease() { - return newProjectDisease; - } - - /** - * @param newProjectDisease - * sets the disease - */ - public void setNewProjectDisease(String newProjectDisease) { - this.newProjectDisease = newProjectDisease; - } - - /** - * Method that trigger download of a file in jsf. The file is the source file - * used to create project given in the parameter. - * - * @param projectView - * view of the {@link Project} for which we are looking for an original - * source file - * @throws IOException - * thrown when there is a problem with sending file - * @throws SecurityException - */ - public void downloadInputData(ProjectView projectView) throws IOException, SecurityException { - // get input data from database - byte[] data = projectService.getInputDataForProject(projectView); - Project project = projectService.getProjectByProjectId(projectView.getProjectId(), - userBean.getAuthenticationToken()); - String string = new String(data, StandardCharsets.UTF_8); - - String fileName = project.getInputData().getOriginalFileName(); - MimeType respMimeType = null; - if (fileName.endsWith("xml")) { - respMimeType = MimeType.XML; - } else if (fileName.endsWith("zip")) { - respMimeType = MimeType.ZIP; - } else if (fileName.endsWith("sbgn")) { - respMimeType = MimeType.XML; - } else { - logger.warn("Cannot determine mime type of file: " + fileName); - respMimeType = MimeType.TEXT; - } - sendFileAsResponse(string, fileName, respMimeType); - } - - /** - * @return the newProjectOrganism - * @see #newProjectOrganism - */ - public String getNewProjectOrganism() { - return newProjectOrganism; - } - - /** - * @param newProjectOrganism - * the newProjectOrganism to set - * @see #newProjectOrganism - */ - public void setNewProjectOrganism(String newProjectOrganism) { - this.newProjectOrganism = newProjectOrganism; - } - - /** - * @return the semanticOverlay - * @see #semanticOverlay - */ - public String getSemanticOverlay() { - return semanticOverlay; - } - - /** - * @param semanticOverlay - * the semanticOverlay to set - * @see #semanticOverlay - */ - public void setSemanticOverlay(String semanticOverlay) { - this.semanticOverlay = semanticOverlay; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/bean/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 ad57da482f7c29d33617020b9ad8c47d93131ad0..0000000000000000000000000000000000000000 --- a/web/src/main/java/lcsb/mapviewer/bean/UserBean.java +++ /dev/null @@ -1,605 +0,0 @@ -package lcsb.mapviewer.bean; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.IOException; -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.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 String authenticationToken; - - /** - * Password of currently logged user. - */ - private String password = ""; - - /** - * Email address that should be used when requesting an account. - */ - private String requestAccountEmail = ""; - - /** - * Currently logged user. The user is transient because it contains information - * from db and to serialize it properly we should provide apropriate converter. - */ - private User loggedUser = null; - - /** - * Object to use to edit user's profile. - */ - private UserView editUser = null; - - /** - * Service used to access information about users. - * - * @see IUserService - */ - @ManagedProperty(value = "#{UserService}") - private transient IUserService userService; - - /** - * Service used to access logs. - * - * @see ILogService - */ - @ManagedProperty(value = "#{LogService}") - private transient ILogService logService; - - /** - * Service used to access configuration parameters. - * - * @see IConfigurationService - */ - @ManagedProperty(value = "#{ConfigurationService}") - private transient IConfigurationService configurationService; - - /** - * Default constructor. - */ - public UserBean() { - super(); - // we have to clear default list of property change listeners (we don't - // want - // to put passwords in the log file ;-)) - for (PropertyChangeListener listener : getPropertyChangeListeners()) { - removePropertyChangeListener(listener); - } - - // and now add custom logger property listener - PropertyChangeListener propertyChangeLogger = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (PASSWORD_PROPERTY.equals(arg0.getPropertyName())) { - logger.debug("Property changed: " + arg0.getPropertyName() + ". Old: *** New: ***"); - } else { - logger.debug("Property changed: " + arg0.getPropertyName() + ". Old: " + arg0.getOldValue() + " New: " - + arg0.getNewValue()); - } - } - - }; - addPropertyChangeListener(propertyChangeLogger); - } - - @Override - public void init() { - PropertyChangeListener loginPasswordChanged = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (LOGIN_PROPERTY.equals(arg0.getPropertyName()) || PASSWORD_PROPERTY.equals(arg0.getPropertyName())) { - authenticationToken = getUserService().login(login, password); - if (authenticationToken != null) { - setLoggedUser(getUserService().getUserByLogin(login)); - } else { - authenticationToken = getUserService().login(Configuration.ANONYMOUS_LOGIN, ""); - setLoggedUser(getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN)); - } - } - } - }; - addPropertyChangeListener(loginPasswordChanged); - - PropertyChangeListener loggedUserChanged = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (LOGGED_USER_PROPERTY.equals(arg0.getPropertyName())) { - getLogService().setLoggedUser(getLoggedUser()); - } - } - }; - addPropertyChangeListener(loggedUserChanged); - - PropertyChangeListener logServiceLoggedUserChanged = new PropertyChangeListener() { - @Override - public void propertyChange(final PropertyChangeEvent arg0) { - if (LOGGED_USER_PROPERTY.equals(arg0.getPropertyName())) { - if (!getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN).equals(arg0.getOldValue())) { - LogParams params = new LogParams().type(LogType.USER_LOGOUT).object(arg0.getOldValue()); - getLogService().log(params); - } - - if (!getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN).equals(arg0.getNewValue())) { - LogParams params = new LogParams().type(LogType.USER_LOGIN).object(arg0.getNewValue()); - getLogService().log(params); - } - } - } - }; - addPropertyChangeListener(logServiceLoggedUserChanged); - - setLoggedUser(getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN)); - setRequestAccountEmail( - getConfigurationService().getConfigurationValue(ConfigurationElementType.REQUEST_ACCOUNT_EMAIL)); - - } - - /** - * - * @return {@link #login} - */ - public String getLogin() { - return login; - } - - /** - * Sets new login value. Property change listeners for "login" property will be - * thrown after setting this value. - * - * @param login - * new {@link #login} value - */ - public void setLogin(final String login) { - String oldLogin = this.login; - this.login = login; - firePropertyChange(LOGIN_PROPERTY, oldLogin, login); - } - - /** - * Perform spring login operation. - * - * @throws IOException - * thrown when underlaying layer throws this exception - * @throws ServletException - * thrown when underlaying layer will throw this exception - */ - public void doLogin() throws IOException, ServletException { - doLogin(null); - } - - /** - * Perform spring login operation. - * - * @param id - * name of the map which should be used after authentication - * - * @throws IOException - * thrown when underlaying layer throws this exception - * @throws ServletException - * thrown when underlaying layer will throw this exception - */ - public void doLogin(String id) throws IOException, ServletException { - FacesContext context = FacesContext.getCurrentInstance(); - ExternalContext externalContext = context.getExternalContext(); - - ServletRequest request = (ServletRequest) externalContext.getRequest(); - Map<?, ?> map = request.getParameterMap(); - for (Object obj : map.keySet()) { - try { - String[] arr = (String[]) map.get(obj); - if (obj.equals("username")) { - setLogin(arr[0]); - } - if (obj.equals("password")) { - setPassword(arr[0]); - } - } catch (ClassCastException e) { - logger.error("WTF", e); - } - } - - // now perform spring authentication - String requestDispatcher = Configuration.SPRING_SECURITY_ACTION; - logger.debug(id); - if (id != null) { - requestDispatcher += "?id=" + id; - } - logger.debug(requestDispatcher); - - RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest()) - .getRequestDispatcher(requestDispatcher); - - dispatcher.forward((ServletRequest) externalContext.getRequest(), (ServletResponse) externalContext.getResponse()); - - context.responseComplete(); - } - - /** - * Performs spring login as anonymous. - * - * @throws IOException - * thrown when underlaying layer throws this exception - * @throws ServletException - * thrown when underlaying layer will throw this exception - */ - public void anonymousLogin() throws IOException, ServletException { - setLogin(Configuration.ANONYMOUS_LOGIN); - setPassword(""); - FacesContext context = FacesContext.getCurrentInstance(); - ExternalContext externalContext = context.getExternalContext(); - ServletRequest request = (ServletRequest) externalContext.getRequest(); - Map<?, ?> map = request.getParameterMap(); - for (Object obj : map.keySet()) { - try { - String[] arr = (String[]) map.get(obj); - if (obj.equals("username")) { - arr[0] = Configuration.ANONYMOUS_LOGIN; - } - if (obj.equals("password")) { - arr[0] = ""; - } - } catch (ClassCastException e) { - logger.error("WTF", e); - } - } - - RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest()) - .getRequestDispatcher(Configuration.SPRING_SECURITY_ACTION); - - dispatcher.forward((ServletRequest) externalContext.getRequest(), (ServletResponse) externalContext.getResponse()); - - context.responseComplete(); - } - - /** - * Perform spring logout operation. - * - * @param actionEvent - * event from thefrom the client - */ - public void doLogout(final ActionEvent actionEvent) { - try { - FacesContext context = FacesContext.getCurrentInstance(); - ExternalContext externalContext = context.getExternalContext(); - - RequestDispatcher dispatcher = ((ServletRequest) externalContext.getRequest()) - .getRequestDispatcher(Configuration.SPRING_SECURITY_LOGOUT); - - dispatcher.forward((ServletRequest) externalContext.getRequest(), - (ServletResponse) externalContext.getResponse()); - - context.responseComplete(); - } catch (Exception e) { - logger.error(e.getMessage(), e); - - } - } - - /** - * - * @return {@link #password} - */ - public String getPassword() { - return password; - } - - /** - * Sets new password value. Property change listeners for "password" property - * will be thrown after setting this value. - * - * @param password - * new {@link #password} value - */ - public void setPassword(final String password) { - String oldPassword = this.password; - this.password = password; - firePropertyChange(PASSWORD_PROPERTY, oldPassword, password); - } - - /** - * - * @return {@link #loggedUser} - */ - public User getLoggedUser() { - if (loggedUser == null) { - loggedUser = getUserService().getUserByLogin(Configuration.ANONYMOUS_LOGIN); - } - return loggedUser; - // return userService.getUserById(loggedUser.getIdObject()); - } - - /** - * Sets new loggedUser value. Property change listeners for "loggedUser" - * property will be thrown after setting this value. - * - * @param user - * new {@link #loggedUser} value - */ - public void setLoggedUser(final User user) { - User oldUser = this.loggedUser; - // loggedUser = getUserService().getUserView(user); - loggedUser = user; - firePropertyChange(LOGGED_USER_PROPERTY, oldUser, loggedUser); - } - - /** - * Check if user has privileges to manage the users. - * - * @return <i>true</i> if user has privileges to manage the users,<br/> - * <i>false</i> otherwise - */ - public boolean getUserHasManagePrivileges() { - User user = getLoggedUser(); - if (user == null) { - return false; - } - boolean result = getUserService().userHasPrivilege(user, PrivilegeType.USER_MANAGEMENT); - return result; - } - - @Override - public void clear() { - throw new NotImplementedException(); - } - - /** - * @return the userService - * @see #userService - */ - public IUserService getUserService() { - if (userService == null) { - userService = findBean(IUserService.class); - } - return userService; - } - - /** - * @param userService - * the userService to set - * @see #userService - */ - public void setUserService(IUserService userService) { - this.userService = userService; - } - - /** - * @return the configurationService - * @see #configurationService - */ - public IConfigurationService getConfigurationService() { - if (configurationService == null) { - configurationService = findBean(IConfigurationService.class); - } - return configurationService; - } - - /** - * @param configurationService - * the configurationService to set - * @see #configurationService - */ - public void setConfigurationService(IConfigurationService configurationService) { - this.configurationService = configurationService; - } - - /** - * @return the requestAccountEmail - * @see #requestAccountEmail - */ - public String getRequestAccountEmail() { - return requestAccountEmail; - } - - /** - * @param requestAccountEmail - * the requestAccountEmail to set - * @see #requestAccountEmail - */ - public void setRequestAccountEmail(String requestAccountEmail) { - this.requestAccountEmail = requestAccountEmail; - } - - /** - * @return the logService - * @see #logService - */ - public ILogService getLogService() { - if (logService == null) { - logService = findBean(ILogService.class); - } - return logService; - } - - /** - * @param logService - * the logService to set - * @see #logService - */ - public void setLogService(ILogService logService) { - this.logService = logService; - } - - /** - * Refresh edit user. - */ - public void refreshEditUser() { - if (!loggedUser.getLogin().equals(Configuration.ANONYMOUS_LOGIN)) { - this.setEditUser(getUserService().getUserRow(loggedUser)); - RequestContext.getCurrentInstance().reset(":tabView:userForm2:panel"); - } - } - - /** - * @param ctx - * context - * @param component - * ui component - * @param value - * the new value - * @throws ValidatorException - * if validation fails - */ - public void checkOldPassword(FacesContext ctx, UIComponent component, Object value) throws ValidatorException { - UIInput passwordComp = (UIInput) component.getAttributes().get("passwordComp"); - if (passwordComp != null) { - String password = null; - password = (String) passwordComp.getValue(); - if (password != null && !password.isEmpty()) { - String oldPassword = (String) value; - if (oldPassword == null || oldPassword.isEmpty() - || !this.getUserService().encodePassword(oldPassword).equals(editUser.getCryptedPassword())) { - ((UIInput) component).setValid(false); - FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, - "Typed old password does not match stored one.", null); - throw new ValidatorException(message); - } - } - } - } - - /** - * @param ctx - * context - * @param component - * ui component - * @param value - * the new value - * @throws ValidatorException - * if validation fails - */ - public void checkNewPassword(FacesContext ctx, UIComponent component, Object value) throws ValidatorException { - UIInput passwordComp = (UIInput) component.getAttributes().get("passwordComp"); - if (passwordComp != null) { - String password = null; - password = (String) passwordComp.getValue(); - if (password != null && !password.isEmpty()) { - String oldPassword = (String) value; - if (oldPassword == null || oldPassword.isEmpty() - || !this.getUserService().encodePassword(oldPassword).equals(editUser.getCryptedPassword())) { - ((UIInput) component).setValid(false); - FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, - "Typed old password does not match stored one.", null); - throw new ValidatorException(message); - } - } - } - } - - /** - * Update selected user. - */ - public void updateUser() { - getUserService().updateUser(editUser); - setLoggedUser(getUserService().getUserByLogin(login)); - ObjectModifiedEvent event = new ObjectModifiedEvent(editUser); - callListeners(event); - } - - /** - * @return editable instance of the object. - */ - public UserView getEditUser() { - return editUser; - } - - /** - * @param editUser - * instance to be edited. - */ - public void setEditUser(UserView editUser) { - this.editUser = editUser; - } - - /** - * @return the authenticationToken - * @see #authenticationToken - */ - public String getAuthenticationToken() { - if (authenticationToken == null) { - authenticationToken = getUserService().login(Configuration.ANONYMOUS_LOGIN, ""); - } - return authenticationToken; - } - - /** - * @param authenticationToken - * the authenticationToken to set - * @see #authenticationToken - */ - public void setAuthenticationToken(String authenticationToken) { - this.authenticationToken = authenticationToken; - } - -} diff --git a/web/src/main/java/lcsb/mapviewer/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/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/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/web.xml b/web/src/main/webapp/WEB-INF/web.xml index 9753c6e538f5d961575b59e3c5bed7823d2aba2c..e5bdde9887143378115fb88f8aa02e458522cba8 100644 --- a/web/src/main/webapp/WEB-INF/web.xml +++ b/web/src/main/webapp/WEB-INF/web.xml @@ -187,6 +187,7 @@ <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> 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 21b132558e623e4bf1a8e8468fa9fdb3ad4aeee9..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 org.apache.commons.lang3.SerializationUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import lcsb.mapviewer.model.map.model.Model; -import lcsb.mapviewer.services.SecurityException; - -public class GalaxyBeanTest extends WebTestFunctions { - - GalaxyBean galaxyBean; - - @Before - public void setUp() throws Exception { - galaxyBean = new GalaxyBean(); - galaxyBean.setLayoutService(layoutService); - } - - @After - public void tearDown() throws Exception { - } - - @Test - @Ignore - public void test() throws SecurityException { - galaxyBean.createLayout("CC75308E16F6AA9C", "NAME\tVALUE\nSNCA\t1\nPINK1\t-1\n", - (Model) modelService.getLastModelByProjectId("pdmap", adminToken), userService.getUserByLogin("galaxy")); - } - - /** - * Checks if bean implements {@link Serializable} properly. - */ - @Test - public void testSearialization() { - try { - SerializationUtils.serialize(galaxyBean); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - -} diff --git a/web/src/test/java/lcsb/mapviewer/bean/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 af6b07728d1bdf9579c96fd73c5bb37ed04109a4..0000000000000000000000000000000000000000 --- a/web/src/test/java/lcsb/mapviewer/bean/WebTestFunctions.java +++ /dev/null @@ -1,718 +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.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(); - - String token; - - String adminToken; - - @Before - public void generalSetUp() { - dbUtils.setAutoFlush(false); - createConfigurationBean(); - createLayoutBean(); - createMapBean(); - createProjectBean(); - createUserBean(); - createExportBean(); - createFeedbackBean(); - createMiriamBean(); - createMissingConnectionBean(); - createSearchBean(); - createUsersBean(); - createReferenceGenomeBean(); - - configurationBean.internalInit(); - layoutBean.internalInit(); - mapBean.internalInit(); - projectBean.internalInit(); - userBean.internalInit(); - - exportBean.internalInit(); - - feedbackBean.internalInit(); - miriamBean.internalInit(); - missingConnectionBean.internalInit(); - searchBean.internalInit(); - usersBean.internalInit(); - - referenceGenomeBean.internalInit(); - - token = userService.login(Configuration.ANONYMOUS_LOGIN, null); - - // assume that we have admin account with all the privileges - adminToken = userService.login("admin", "admin"); - - } - - @After - public void generatTearDown() throws IOException { - File f = new File("map_images"); - if (f.exists()) { - logger.info("Removing output test directory: " + f.getAbsolutePath()); - FileUtils.deleteDirectory(f); - } - - } - - protected String readFile(String file) throws IOException { - StringBuilder stringBuilder = new StringBuilder(); - BufferedReader reader = new BufferedReader(new FileReader(file)); - try { - String line = null; - String ls = System.getProperty("line.separator"); - - while ((line = reader.readLine()) != null) { - stringBuilder.append(line); - stringBuilder.append(ls); - } - } finally { - reader.close(); - } - - return stringBuilder.toString(); - } - - protected Node getNodeFromXmlString(String text) throws InvalidXmlSchemaException { - InputSource is = new InputSource(); - is.setCharacterStream(new StringReader(text)); - return getXmlDocumentFromInputSource(is).getChildNodes().item(0); - } - - protected Document getXmlDocumentFromFile(String fileName) throws InvalidXmlSchemaException, IOException { - File file = new File(fileName); - InputStream inputStream = new FileInputStream(file); - Reader reader = null; - try { - reader = new InputStreamReader(inputStream, "UTF-8"); - InputSource is = new InputSource(reader); - - Document result = getXmlDocumentFromInputSource(is); - inputStream.close(); - return result; - } catch (UnsupportedEncodingException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; - } - - protected Document getXmlDocumentFromInputSource(InputSource stream) throws InvalidXmlSchemaException { - DocumentBuilder db; - try { - db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - } catch (ParserConfigurationException e) { - throw new InvalidXmlSchemaException("Problem with xml parser"); - } - Document doc = null; - try { - doc = db.parse(stream); - } catch (SAXException e) { - logger.error(e); - } catch (IOException e) { - logger.error(e); - } - return doc; - } - - /** - * This method remove model with all connections from db (used only when the db - * must be handled manually) - * - * @param id - */ - protected void removeModelById(int id) { - modelDao.delete(modelDao.getById(id)); - } - - protected void createUser() { - user = userDao.getUserByLogin("john.doe"); - if (user == null) { - user = new User(); - user.setName("John"); - user.setSurname("Doe"); - user.setEmail("john.doe@uni.lu"); - user.setLogin("john.doe"); - user.setCryptedPassword(passwordEncoder.encode("passwd")); - userDao.add(user); - } - } - - private static Map<String, Model> models = new HashMap<String, Model>(); - - protected Model getModelForFile(String fileName, boolean fromCache) throws Exception { - if (!fromCache) { - logger.debug("File without cache: " + fileName); - return new CellDesignerXmlParser().createModel(new ConverterParams().filename(fileName)); - } - Model result = WebTestFunctions.models.get(fileName); - if (result == null) { - logger.debug("File to cache: " + fileName); - - CellDesignerXmlParser parser = new CellDesignerXmlParser(); - result = parser.createModel(new ConverterParams().filename(fileName).sizeAutoAdjust(false)); - WebTestFunctions.models.put(fileName, result); - } - return result; - } - - protected String createTmpFileName() { - try { - File f = File.createTempFile("prefix", ".txt"); - String filename = f.getName(); - f.delete(); - return filename; - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - - protected String nodeToString(Node node) { - return nodeToString(node, false); - } - - protected String nodeToString(Node node, boolean includeHeadNode) { - if (node == null) - return null; - StringWriter sw = new StringWriter(); - try { - Transformer t = TransformerFactory.newInstance().newTransformer(); - t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); - t.setOutputProperty(OutputKeys.INDENT, "yes"); - t.setOutputProperty(OutputKeys.METHOD, "xml"); - - NodeList list = node.getChildNodes(); - for (int i = 0; i < list.getLength(); i++) { - Node element = list.item(i); - t.transform(new DOMSource(element), new StreamResult(sw)); - } - } catch (TransformerException te) { - logger.debug("nodeToString Transformer Exception"); - } - if (includeHeadNode) { - return "<" + node.getNodeName() + ">" + sw.toString() + "</" + node.getNodeName() + ">"; - } - return sw.toString(); - } - - protected boolean equalFiles(String fileA, String fileB) throws IOException { - int BLOCK_SIZE = 65536; - FileInputStream inputStreamA = new FileInputStream(fileA); - FileInputStream inputStreamB = new FileInputStream(fileB); - // vary BLOCK_SIZE to suit yourself. - // it should probably a factor or multiple of the size of a disk - // sector/cluster. - // Note that your max heap size may need to be adjused - // if you have a very big block size or lots of these comparators. - - // assume inputStreamA and inputStreamB are streams from your two files. - byte[] streamABlock = new byte[BLOCK_SIZE]; - byte[] streamBBlock = new byte[BLOCK_SIZE]; - boolean match = true; - int bytesReadA = 0; - int bytesReadB = 0; - do { - bytesReadA = inputStreamA.read(streamABlock); - bytesReadB = inputStreamB.read(streamBBlock); - match = ((bytesReadA == bytesReadB) && Arrays.equals(streamABlock, streamBBlock)); - } while (match && (bytesReadA > -1)); - inputStreamA.close(); - inputStreamB.close(); - return match; - } - - public PrivilegeDao getPrivilegeDao() { - return privilegeDao; - } - - public void setPrivilegeDao(PrivilegeDao privilegeDao) { - this.privilegeDao = privilegeDao; - } - - public File createTempDirectory() throws IOException { - final File temp; - - temp = File.createTempFile("temp", Long.toString(System.nanoTime())); - - if (!(temp.delete())) { - throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); - } - - if (!(temp.mkdir())) { - throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); - } - - return (temp); - } - - protected String getWebpage(String accessUrl) throws IOException { - String inputLine; - StringBuilder tmp = new StringBuilder(); - URL url = new URL(accessUrl); - URLConnection urlConn = url.openConnection(); - BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); - - while ((inputLine = in.readLine()) != null) { - tmp.append(inputLine); - } - in.close(); - return tmp.toString(); - } - - protected UserBean getUserBean() { - if (userBean == null) { - createUserBean(); - } - return userBean; - } - - protected LayoutBean getLayoutBean() { - if (layoutBean == null) { - createLayoutBean(); - } - return layoutBean; - } - - private void createUserBean() { - if (userBean != null) { - return; - } - userBean = new UserBean(); - userBean.setPrimefacesUtils(primefacesUtils); - - userBean.setUserService(userService); - userBean.setConfigurationService(configurationService); - userBean.setLogService(logService); - - } - - private void createLayoutBean() { - if (layoutBean != null) { - return; - } - layoutBean = new LayoutBean(); - layoutBean.setPrimefacesUtils(primefacesUtils); - - layoutBean.setLayoutService(layoutService); - layoutBean.setModelService(modelService); - layoutBean.setUserBean(getUserBean()); - layoutBean.setMapBean(getMapBean()); - - } - - protected MapBean getMapBean() { - if (mapBean == null) { - createMapBean(); - } - return mapBean; - } - - private void createMapBean() { - if (mapBean != null) { - return; - } - mapBean = new MapBean(); - mapBean.setPrimefacesUtils(primefacesUtils); - - mapBean.setConfService(configurationService); - mapBean.setModelService(modelService); - mapBean.setProjectService(projectService); - mapBean.setConfigurationService(configurationService); - mapBean.setModelService(modelService); - mapBean.setUserService(userService); - mapBean.setUserBean(getUserBean()); - } - - protected ProjectBean getProjectBean() { - if (projectBean == null) { - createProjectBean(); - } - return projectBean; - } - - private void createProjectBean() { - if (projectBean != null) { - return; - } - projectBean = new ProjectBean(); - projectBean.setPrimefacesUtils(primefacesUtils); - - projectBean.setConfigurationService(configurationService); - projectBean.setModelService(modelService); - projectBean.setProjectService(projectService); - projectBean.setUserService(userService); - - projectBean.setLayoutBean(getLayoutBean()); - projectBean.setUserBean(getUserBean()); - } - - protected ExportBean getExportBean() { - if (exportBean == null) { - createExportBean(); - } - return exportBean; - } - - private void createExportBean() { - if (exportBean != null) { - return; - } - exportBean = new ExportBean(); - exportBean.setPrimefacesUtils(primefacesUtils); - - exportBean.setExporterService(exportService); - exportBean.setMapBean(getMapBean()); - } - - protected ConfigurationBean getConfigurationBean() { - if (configurationBean == null) { - createConfigurationBean(); - } - return configurationBean; - } - - private void createConfigurationBean() { - if (configurationBean != null) { - return; - } - configurationBean = new ConfigurationBean(); - configurationBean.setPrimefacesUtils(primefacesUtils); - - configurationBean.setConfigurationService(configurationService); - configurationBean.setUserService(userService); - configurationBean.setProjectService(projectService); - - configurationBean.setUserBean(getUserBean()); - } - - protected FeedbackBean getFeedbackBean() { - if (feedbackBean == null) { - createFeedbackBean(); - } - return feedbackBean; - } - - protected MiriamBean getMiriamBean() { - if (miriamBean == null) { - createMiriamBean(); - } - return miriamBean; - } - - protected MissingConnectionBean getMissingConnectionBean() { - if (missingConnectionBean == null) { - createMissingConnectionBean(); - } - return missingConnectionBean; - } - - protected SearchBean getSearchBean() { - if (searchBean == null) { - createSearchBean(); - } - return searchBean; - } - - protected UsersBean getUsersBean() { - if (usersBean == null) { - createUsersBean(); - } - return usersBean; - } - - private void createFeedbackBean() { - if (feedbackBean != null) { - return; - } - feedbackBean = new FeedbackBean(); - feedbackBean.setPrimefacesUtils(primefacesUtils); - - feedbackBean.setCommentService(commentService); - feedbackBean.setUserService(userService); - feedbackBean.setUserBean(userBean); - - feedbackBean.setUserBean(getUserBean()); - feedbackBean.setMapBean(getMapBean()); - - } - - private void createMiriamBean() { - if (miriamBean != null) { - return; - } - miriamBean = new MiriamBean(); - miriamBean.setPrimefacesUtils(primefacesUtils); - - } - - private void createMissingConnectionBean() { - if (missingConnectionBean != null) { - return; - } - missingConnectionBean = new MissingConnectionBean(); - missingConnectionBean.setPrimefacesUtils(primefacesUtils); - } - - private void createSearchBean() { - if (searchBean != null) { - return; - } - searchBean = new SearchBean(); - searchBean.setPrimefacesUtils(primefacesUtils); - - searchBean.setConfigurationService(configurationService); - searchBean.setUserService(userService); - - searchBean.setUserBean(getUserBean()); - searchBean.setMapBean(getMapBean()); - } - - private void createUsersBean() { - if (usersBean != null) { - return; - } - usersBean = new UsersBean(); - usersBean.setPrimefacesUtils(primefacesUtils); - - usersBean.setUserService(userService); - - usersBean.setUserBean(getUserBean()); - usersBean.setProjectBean(getProjectBean()); - } - - public ReferenceGenomeBean getReferenceGenomeBean() { - if (referenceGenomeBean == null) { - createReferenceGenomeBean(); - } - return referenceGenomeBean; - } - - private void createReferenceGenomeBean() { - if (referenceGenomeBean != null) { - return; - } - referenceGenomeBean = new ReferenceGenomeBean(); - referenceGenomeBean.setPrimefacesUtils(primefacesUtils); - - referenceGenomeBean.setReferenceGenomeService(referenceGenomeService); - referenceGenomeBean.setUserBean(getUserBean()); - referenceGenomeBean.setUserService(userService); - referenceGenomeBean.setMapBean(getMapBean()); - - } - -}