diff --git a/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java b/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java index 7834e459adcb97b7931bec5b4f88ec8daeff6083..3336c875464041bf7aea4c6d65e5f0004d1d9b84 100644 --- a/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java +++ b/service/src/main/java/lcsb/mapviewer/services/impl/UserService.java @@ -16,6 +16,7 @@ import org.springframework.transaction.annotation.Transactional; import lcsb.mapviewer.commands.ColorExtractor; import lcsb.mapviewer.common.Configuration; import lcsb.mapviewer.common.ObjectUtils; +import lcsb.mapviewer.common.comparator.IntegerComparator; import lcsb.mapviewer.common.exception.InvalidArgumentException; import lcsb.mapviewer.common.geometry.ColorParser; import lcsb.mapviewer.model.Project; @@ -281,14 +282,16 @@ public class UserService implements IUserService { @Override public void dropPrivilegesForObjectType(PrivilegeType type, int id) { + IntegerComparator integerComparator = new IntegerComparator(); // this will be slow when number of user will increase (we fetch all // users and drop privileges one by one) List<User> users = userDao.getAll(); for (User user : users) { List<BasicPrivilege> toRemove = new ArrayList<BasicPrivilege>(); for (BasicPrivilege privilege : user.getPrivileges()) { - if (privilege.getType().equals(type) && privilege instanceof ObjectPrivilege - && ((ObjectPrivilege) privilege).getIdObject() == id) { + if (privilege.getType().equals(type) && + privilege instanceof ObjectPrivilege && + integerComparator.compare(((ObjectPrivilege) privilege).getIdObject() ,id)==0) { toRemove.add(privilege); } } diff --git a/service/src/main/java/lcsb/mapviewer/services/view/UserView.java b/service/src/main/java/lcsb/mapviewer/services/view/UserView.java index 65f4cc15ff67a0d4a9214e2a02aa5596d1a94857..7569de2fc50c3e4538f5e60c828862ddf378e6d2 100644 --- a/service/src/main/java/lcsb/mapviewer/services/view/UserView.java +++ b/service/src/main/java/lcsb/mapviewer/services/view/UserView.java @@ -24,572 +24,576 @@ import org.primefaces.model.SelectableDataModel; */ public class UserView extends AbstractView<User> implements Comparable<UserView>, Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default class logger. - */ - private static Logger logger = Logger.getLogger(UserView.class); - - /** - * This data model is extension of faces {@link ListDataModel} and - * implements {@link SelectableDataModel} from primefaces library. It allows - * client to create a table (in xhtml) that allows to select element on it - * and call select event associated with the row. The model operates on - * {@link UserProjectPrivilegeView} that describe set of privileges to - * single project. - * - * @author Piotr Gawron - * - */ - public class ProjectDataModel extends ListDataModel<UserProjectPrivilegeView> - implements SelectableDataModel<UserProjectPrivilegeView>, Serializable { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Default constructor. - */ - public ProjectDataModel() { - } - - /** - * Constructor that initialize the data. - * - * @param data - * data used in the model - */ - public ProjectDataModel(List<UserProjectPrivilegeView> data) { - super(data); - } - - @Override - public Object getRowKey(UserProjectPrivilegeView object) { - return object.toString(); - } - - @SuppressWarnings("unchecked") - @Override - public UserProjectPrivilegeView getRowData(String rowKey) { - List<UserProjectPrivilegeView> privileges = (List<UserProjectPrivilegeView>) getWrappedData(); - - for (UserProjectPrivilegeView privilege : privileges) { - if ((privilege.toString()).equals(rowKey)) { - return privilege; - } - } - return null; - } - - } - - /** - * Class representing prvileges to the specific project. - * - * @author Piotr Gawron - * - */ - public class UserProjectPrivilegeView extends AbstractView<Project> implements Serializable { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * {@link Project#projectId Project identifier}. - */ - private String projectId; - - /** - * List of privileges to the project. - */ - private List<PrivilegeView> projectPrivileges = new ArrayList<PrivilegeView>(); - - /** - * List of layouts with privileges. - */ - private List<UserLayoutPrivilege> layoutPrivileges = new ArrayList<UserLayoutPrivilege>(); - - /** - * Constructor that creates view for the project. - * - * @param project - * originasl project - */ - public UserProjectPrivilegeView(Project project) { - super(project); - this.projectId = project.getProjectId(); - } - - /** - * Default constructor. - */ - public UserProjectPrivilegeView() { - super(null); - } - - /** - * @return the projectId - * @see #projectId - */ - public String getProjectId() { - return projectId; - } - - /** - * @param projectId - * the projectId to set - * @see #projectId - */ - public void setProjectId(String projectId) { - this.projectId = projectId; - } - - /** - * @return the projectPrivileges - * @see #projectPrivileges - */ - public List<PrivilegeView> getProjectPrivileges() { - return projectPrivileges; - } - - /** - * @param projectPrivileges - * the projectPrivileges to set - * @see #projectPrivileges - */ - public void setProjectPrivileges(List<PrivilegeView> projectPrivileges) { - this.projectPrivileges = projectPrivileges; - } - - /** - * @return the layoutPrivileges - * @see #layoutPrivileges - */ - public List<UserLayoutPrivilege> getLayoutPrivileges() { - return layoutPrivileges; - } - - /** - * @param layoutPrivileges - * the layoutPrivileges to set - * @see #layoutPrivileges - */ - public void setLayoutPrivileges(List<UserLayoutPrivilege> layoutPrivileges) { - this.layoutPrivileges = layoutPrivileges; - } - - /** - * Returns view of the {@link Privilege} for a given - * {@link PrivilegeType}. - * - * @param pt - * ttype of privilege - * @return view of the {@link Privilege} for a given - * {@link PrivilegeType} - */ - public PrivilegeView getProjectPrivilegeByPrivilegeType(PrivilegeType pt) { - for (PrivilegeView pv : projectPrivileges) { - if (pv.getType() == pt) { - return pv; - } - } - logger.warn("Cannot find " + pt + " for projectID: " + this.getIdObject() + " (" + this.getProjectId() - + "). UserId: " + UserView.this.getIdObject() + " (" + UserView.this.getLogin() + ")"); - return null; - } - - } - - /** - * Class representing prvileges to the specific - * {@link lcsb.mapviewer.db.model.map.layout.Layout Layout}. - * - * @author Piotr Gawron - * - */ - public class UserLayoutPrivilege extends AbstractView<Layout> { - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * Name of the layout. - */ - private String layoutName; - - /** - * List of privileges for the layout. - */ - private List<PrivilegeView> layoutPrivileges = new ArrayList<PrivilegeView>(); - - /** - * Default constructor. - * - * @param layout - * object for which the privilege set is created - */ - protected UserLayoutPrivilege(Layout layout) { - super(layout); - } - - /** - * Default constructor. Should be used only for deserialization. - */ - protected UserLayoutPrivilege() { - } - - /** - * @return the layoutName - * @see #layoutName - */ - public String getLayoutName() { - return layoutName; - } - - /** - * @param layoutName - * the layoutName to set - * @see #layoutName - */ - public void setLayoutName(String layoutName) { - this.layoutName = layoutName; - } - - /** - * @return the layoutPrivileges - * @see #layoutPrivileges - */ - public List<PrivilegeView> getLayoutPrivileges() { - return layoutPrivileges; - } - - /** - * @param layoutPrivileges - * the layoutPrivileges to set - * @see #layoutPrivileges - */ - public void setLayoutPrivileges(List<PrivilegeView> layoutPrivileges) { - this.layoutPrivileges = layoutPrivileges; - } - - } - - /** - * Use login. - */ - private String login; - - /** - * User password (can be set only by the client side, when view is created - * password should be set to empty, simple precaution not to reveal - * passwords). - */ - private String password; - - /** - * User password 2. - */ - private String password2; - - /** - * Old password. - */ - private String oldPassword; - - /** - * Old Encrypted password. - */ - private String cryptedPassword; - - /** - * Name of the user. - */ - private String name; - - /** - * Family name of the user. - */ - private String surname; - - /** - * User email address. - */ - private String email; - - /** - * List of general privielges. - */ - private List<PrivilegeView> basicPrivileges = new ArrayList<PrivilegeView>(); - /** - * List of privileges divided by the projects. - */ - - private List<UserProjectPrivilegeView> projectPrivileges = new ArrayList<UserProjectPrivilegeView>(); - /** - * Data model used for managing project privileges. - */ - private ProjectDataModel pdm = null; - - /** - * Constructor that create user view from the user data. - * - * @param user - * orignal user - */ - protected UserView(User user) { - super(user); - this.login = user.getLogin(); - this.password = ""; - this.password2 = ""; - this.oldPassword = ""; - this.cryptedPassword = user.getCryptedPassword(); - this.name = user.getName(); - this.surname = user.getSurname(); - this.email = user.getEmail(); - } - - /** - * Default constructor. - */ - protected UserView() { - super(null); - } - - /** - * Returns object with privileges for the given project. - * - * @param projectId - * identrifier of the project - * @return object with privileges for the given project - */ - public UserProjectPrivilegeView getProjectPrivilegeByProjectId(int projectId) { - for (UserProjectPrivilegeView projectPrivilege : getProjectPrivileges()) { - if (projectPrivilege.getIdObject() == projectId) { - return projectPrivilege; - } - } - if (projectId != 0) { - logger.warn("Cannot find project privileges for projectID: " + projectId + ". User: " + getIdObject() + " (" - + getLogin() + ")."); - } - return null; - } - - /** - * - * @return {@link #pdm} - */ - public ProjectDataModel getPdm() { - if (pdm == null) { - pdm = new ProjectDataModel(projectPrivileges); - } - return pdm; - } - - /** - * - * @param pdm - * new {@link #pdm} object - */ - public void setPdm(ProjectDataModel pdm) { - this.pdm = pdm; - } - - /** - * Return object with privileges for layout given in the parameter. - * - * @param layoutId - * identifier of the layout - * @return object with privileges for layout - */ - public UserLayoutPrivilege getLayoutPrivilegeByLayoutId(int layoutId) { - for (UserProjectPrivilegeView projectPrivilege : getProjectPrivileges()) { - for (UserLayoutPrivilege layoutPrivilege : projectPrivilege.getLayoutPrivileges()) { - if (layoutPrivilege.getIdObject() == layoutId) { - return layoutPrivilege; - } - } - } - logger.warn("Cannot find project privileges for layoutID: " + layoutId); - return null; - } - - @Override - public int compareTo(UserView o) { - IntegerComparator comparator = new IntegerComparator(); - if (o == null) { - comparator.compare(getIdObject(), null); - } - return comparator.compare(getIdObject(), o.getIdObject()); - - } - - /** - * @return the login - * @see #login - */ - public String getLogin() { - return login; - } - - /** - * @param login - * the login to set - * @see #login - */ - public void setLogin(String login) { - this.login = login; - } - - /** - * @return the password - * @see #password - */ - public String getPassword() { - return password; - } - - /** - * @param password - * the password to set - * @see #password - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return the name - * @see #name - */ - public String getName() { - return name; - } - - /** - * @param name - * the name to set - * @see #name - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return the surname - * @see #surname - */ - public String getSurname() { - return surname; - } - - /** - * @param surname - * the surname to set - * @see #surname - */ - public void setSurname(String surname) { - this.surname = surname; - } - - /** - * @return the email - * @see #email - */ - public String getEmail() { - return email; - } - - /** - * @param email - * the email to set - * @see #email - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return the basicPrivileges - * @see #basicPrivileges - */ - public List<PrivilegeView> getBasicPrivileges() { - return basicPrivileges; - } - - /** - * @param basicPrivileges - * the basicPrivileges to set - * @see #basicPrivileges - */ - public void setBasicPrivileges(List<PrivilegeView> basicPrivileges) { - this.basicPrivileges = basicPrivileges; - } - - /** - * @return the projectPrivileges - * @see #projectPrivileges - */ - public List<UserProjectPrivilegeView> getProjectPrivileges() { - return projectPrivileges; - } - - /** - * @param projectPrivileges - * the projectPrivileges to set - * @see #projectPrivileges - */ - public void setProjectPrivileges(List<UserProjectPrivilegeView> projectPrivileges) { - this.projectPrivileges = projectPrivileges; - } - - /** - * @return old password as typed by the user. - */ - public String getOldPassword() { - return oldPassword; - } - - /** - * @param oldPassword the field for the user to put in the old password, - */ - public void setOldPassword(String oldPassword) { - this.oldPassword = oldPassword; - } - - /** - * @return password crypted and stored in DB. - */ - public String getCryptedPassword() { - return cryptedPassword; - } - - /** - * @param cryptedPassword crypted password stored in DB - */ - public void setCryptedPassword(String cryptedPassword) { - this.cryptedPassword = cryptedPassword; - } - - /** - * @return password2. - */ - public String getPassword2() { - return password2; - } - - /** - * @param password2 to verify that the password match. - */ - public void setPassword2(String password2) { - this.password2 = password2; - } + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default class logger. + */ + private static Logger logger = Logger.getLogger(UserView.class); + + /** + * This data model is extension of faces {@link ListDataModel} and implements + * {@link SelectableDataModel} from primefaces library. It allows client to + * create a table (in xhtml) that allows to select element on it and call select + * event associated with the row. The model operates on + * {@link UserProjectPrivilegeView} that describe set of privileges to single + * project. + * + * @author Piotr Gawron + * + */ + public class ProjectDataModel extends ListDataModel<UserProjectPrivilegeView> + implements SelectableDataModel<UserProjectPrivilegeView>, Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Default constructor. + */ + public ProjectDataModel() { + } + + /** + * Constructor that initialize the data. + * + * @param data + * data used in the model + */ + public ProjectDataModel(List<UserProjectPrivilegeView> data) { + super(data); + } + + @Override + public Object getRowKey(UserProjectPrivilegeView object) { + return object.toString(); + } + + @SuppressWarnings("unchecked") + @Override + public UserProjectPrivilegeView getRowData(String rowKey) { + List<UserProjectPrivilegeView> privileges = (List<UserProjectPrivilegeView>) getWrappedData(); + + for (UserProjectPrivilegeView privilege : privileges) { + if ((privilege.toString()).equals(rowKey)) { + return privilege; + } + } + return null; + } + + } + + /** + * Class representing prvileges to the specific project. + * + * @author Piotr Gawron + * + */ + public class UserProjectPrivilegeView extends AbstractView<Project> implements Serializable { + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * {@link Project#projectId Project identifier}. + */ + private String projectId; + + /** + * List of privileges to the project. + */ + private List<PrivilegeView> projectPrivileges = new ArrayList<PrivilegeView>(); + + /** + * List of layouts with privileges. + */ + private List<UserLayoutPrivilege> layoutPrivileges = new ArrayList<UserLayoutPrivilege>(); + + /** + * Constructor that creates view for the project. + * + * @param project + * originasl project + */ + public UserProjectPrivilegeView(Project project) { + super(project); + this.projectId = project.getProjectId(); + } + + /** + * Default constructor. + */ + public UserProjectPrivilegeView() { + super(null); + } + + /** + * @return the projectId + * @see #projectId + */ + public String getProjectId() { + return projectId; + } + + /** + * @param projectId + * the projectId to set + * @see #projectId + */ + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + /** + * @return the projectPrivileges + * @see #projectPrivileges + */ + public List<PrivilegeView> getProjectPrivileges() { + return projectPrivileges; + } + + /** + * @param projectPrivileges + * the projectPrivileges to set + * @see #projectPrivileges + */ + public void setProjectPrivileges(List<PrivilegeView> projectPrivileges) { + this.projectPrivileges = projectPrivileges; + } + + /** + * @return the layoutPrivileges + * @see #layoutPrivileges + */ + public List<UserLayoutPrivilege> getLayoutPrivileges() { + return layoutPrivileges; + } + + /** + * @param layoutPrivileges + * the layoutPrivileges to set + * @see #layoutPrivileges + */ + public void setLayoutPrivileges(List<UserLayoutPrivilege> layoutPrivileges) { + this.layoutPrivileges = layoutPrivileges; + } + + /** + * Returns view of the {@link Privilege} for a given {@link PrivilegeType}. + * + * @param pt + * ttype of privilege + * @return view of the {@link Privilege} for a given {@link PrivilegeType} + */ + public PrivilegeView getProjectPrivilegeByPrivilegeType(PrivilegeType pt) { + for (PrivilegeView pv : projectPrivileges) { + if (pv.getType() == pt) { + return pv; + } + } + logger.warn("Cannot find " + pt + " for projectID: " + this.getIdObject() + " (" + this.getProjectId() + + "). UserId: " + UserView.this.getIdObject() + " (" + UserView.this.getLogin() + ")"); + return null; + } + + } + + /** + * Class representing prvileges to the specific + * {@link lcsb.mapviewer.db.model.map.layout.Layout Layout}. + * + * @author Piotr Gawron + * + */ + public class UserLayoutPrivilege extends AbstractView<Layout> { + /** + * + */ + private static final long serialVersionUID = 1L; + + /** + * Name of the layout. + */ + private String layoutName; + + /** + * List of privileges for the layout. + */ + private List<PrivilegeView> layoutPrivileges = new ArrayList<PrivilegeView>(); + + /** + * Default constructor. + * + * @param layout + * object for which the privilege set is created + */ + protected UserLayoutPrivilege(Layout layout) { + super(layout); + } + + /** + * Default constructor. Should be used only for deserialization. + */ + protected UserLayoutPrivilege() { + } + + /** + * @return the layoutName + * @see #layoutName + */ + public String getLayoutName() { + return layoutName; + } + + /** + * @param layoutName + * the layoutName to set + * @see #layoutName + */ + public void setLayoutName(String layoutName) { + this.layoutName = layoutName; + } + + /** + * @return the layoutPrivileges + * @see #layoutPrivileges + */ + public List<PrivilegeView> getLayoutPrivileges() { + return layoutPrivileges; + } + + /** + * @param layoutPrivileges + * the layoutPrivileges to set + * @see #layoutPrivileges + */ + public void setLayoutPrivileges(List<PrivilegeView> layoutPrivileges) { + this.layoutPrivileges = layoutPrivileges; + } + + } + + /** + * Use login. + */ + private String login; + + /** + * User password (can be set only by the client side, when view is created + * password should be set to empty, simple precaution not to reveal passwords). + */ + private String password; + + /** + * User password 2. + */ + private String password2; + + /** + * Old password. + */ + private String oldPassword; + + /** + * Old Encrypted password. + */ + private String cryptedPassword; + + /** + * Name of the user. + */ + private String name; + + /** + * Family name of the user. + */ + private String surname; + + /** + * User email address. + */ + private String email; + + /** + * List of general privielges. + */ + private List<PrivilegeView> basicPrivileges = new ArrayList<PrivilegeView>(); + /** + * List of privileges divided by the projects. + */ + + private List<UserProjectPrivilegeView> projectPrivileges = new ArrayList<UserProjectPrivilegeView>(); + /** + * Data model used for managing project privileges. + */ + private ProjectDataModel pdm = null; + + /** + * Constructor that create user view from the user data. + * + * @param user + * orignal user + */ + protected UserView(User user) { + super(user); + this.login = user.getLogin(); + this.password = ""; + this.password2 = ""; + this.oldPassword = ""; + this.cryptedPassword = user.getCryptedPassword(); + this.name = user.getName(); + this.surname = user.getSurname(); + this.email = user.getEmail(); + } + + /** + * Default constructor. + */ + protected UserView() { + super(null); + } + + /** + * Returns object with privileges for the given project. + * + * @param projectId + * identifier of the project + * @return object with privileges for the given project + */ + public UserProjectPrivilegeView getProjectPrivilegeByProjectId(Integer projectId) { + IntegerComparator comparator = new IntegerComparator(); + for (UserProjectPrivilegeView projectPrivilege : getProjectPrivileges()) { + if (comparator.compare(projectPrivilege.getIdObject(), projectId) == 0) { + return projectPrivilege; + } + } + if (projectId == null) { + logger.warn("Cannot find default project privileges. User: " + getIdObject() + " (" + getLogin() + ")."); + + } else if (projectId != 0) { + logger.warn("Cannot find project privileges for projectID: " + projectId + ". User: " + getIdObject() + " (" + + getLogin() + ")."); + } + return null; + } + + /** + * + * @return {@link #pdm} + */ + public ProjectDataModel getPdm() { + if (pdm == null) { + pdm = new ProjectDataModel(projectPrivileges); + } + return pdm; + } + + /** + * + * @param pdm + * new {@link #pdm} object + */ + public void setPdm(ProjectDataModel pdm) { + this.pdm = pdm; + } + + /** + * Return object with privileges for layout given in the parameter. + * + * @param layoutId + * identifier of the layout + * @return object with privileges for layout + */ + public UserLayoutPrivilege getLayoutPrivilegeByLayoutId(int layoutId) { + for (UserProjectPrivilegeView projectPrivilege : getProjectPrivileges()) { + for (UserLayoutPrivilege layoutPrivilege : projectPrivilege.getLayoutPrivileges()) { + if (layoutPrivilege.getIdObject() == layoutId) { + return layoutPrivilege; + } + } + } + logger.warn("Cannot find project privileges for layoutID: " + layoutId); + return null; + } + + @Override + public int compareTo(UserView o) { + IntegerComparator comparator = new IntegerComparator(); + if (o == null) { + comparator.compare(getIdObject(), null); + } + return comparator.compare(getIdObject(), o.getIdObject()); + + } + + /** + * @return the login + * @see #login + */ + public String getLogin() { + return login; + } + + /** + * @param login + * the login to set + * @see #login + */ + public void setLogin(String login) { + this.login = login; + } + + /** + * @return the password + * @see #password + */ + public String getPassword() { + return password; + } + + /** + * @param password + * the password to set + * @see #password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return the name + * @see #name + */ + public String getName() { + return name; + } + + /** + * @param name + * the name to set + * @see #name + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the surname + * @see #surname + */ + public String getSurname() { + return surname; + } + + /** + * @param surname + * the surname to set + * @see #surname + */ + public void setSurname(String surname) { + this.surname = surname; + } + + /** + * @return the email + * @see #email + */ + public String getEmail() { + return email; + } + + /** + * @param email + * the email to set + * @see #email + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * @return the basicPrivileges + * @see #basicPrivileges + */ + public List<PrivilegeView> getBasicPrivileges() { + return basicPrivileges; + } + + /** + * @param basicPrivileges + * the basicPrivileges to set + * @see #basicPrivileges + */ + public void setBasicPrivileges(List<PrivilegeView> basicPrivileges) { + this.basicPrivileges = basicPrivileges; + } + + /** + * @return the projectPrivileges + * @see #projectPrivileges + */ + public List<UserProjectPrivilegeView> getProjectPrivileges() { + return projectPrivileges; + } + + /** + * @param projectPrivileges + * the projectPrivileges to set + * @see #projectPrivileges + */ + public void setProjectPrivileges(List<UserProjectPrivilegeView> projectPrivileges) { + this.projectPrivileges = projectPrivileges; + } + + /** + * @return old password as typed by the user. + */ + public String getOldPassword() { + return oldPassword; + } + + /** + * @param oldPassword + * the field for the user to put in the old password, + */ + public void setOldPassword(String oldPassword) { + this.oldPassword = oldPassword; + } + + /** + * @return password crypted and stored in DB. + */ + public String getCryptedPassword() { + return cryptedPassword; + } + + /** + * @param cryptedPassword + * crypted password stored in DB + */ + public void setCryptedPassword(String cryptedPassword) { + this.cryptedPassword = cryptedPassword; + } + + /** + * @return password2. + */ + public String getPassword2() { + return password2; + } + + /** + * @param password2 + * to verify that the password match. + */ + public void setPassword2(String password2) { + this.password2 = password2; + } } diff --git a/service/src/main/java/lcsb/mapviewer/services/view/UserViewFactory.java b/service/src/main/java/lcsb/mapviewer/services/view/UserViewFactory.java index 7270a6114a79e8548d15d52dfd67356c5227e043..c5c9561a93d986f28dc5dd167b01df6f9c67b18a 100644 --- a/service/src/main/java/lcsb/mapviewer/services/view/UserViewFactory.java +++ b/service/src/main/java/lcsb/mapviewer/services/view/UserViewFactory.java @@ -31,208 +31,209 @@ import com.google.gson.Gson; * */ public class UserViewFactory extends AbstractViewFactory<User, UserView> { - - /** - * Default class logger. - */ - @SuppressWarnings("unused") - private static Logger logger = Logger.getLogger(UserViewFactory.class); - - /** - * Data access object for projects. - */ - @Autowired - private ProjectDao projectDao; - - /** - * Factory object for {@link PrivilegeView} elements. - */ - @Autowired - private PrivilegeViewFactory privilegeViewFactory; - - @Override - public UserView create(User user) { - return create(user, projectDao.getAll()); - } - - /** - * Creates {@link UserView} obejct for given user and given list of projects. - * - * @param user - * object for which {@link UserView} element will be created - * @param projects - * list of project for which privileges will be created as - * {@link PrivilegeView} elements in the result - * @return {@link UserView} obejct for given user - */ - public UserView create(User user, List<Project> projects) { - UserView result = null; - if (user == null) { - result = new UserView(); - for (Project project : projects) { - result.getProjectPrivileges().add(result.new UserProjectPrivilegeView(project)); - } - for (PrivilegeType type : getBasicTypes()) { - result.getBasicPrivileges().add(privilegeViewFactory.create(type)); - } - for (UserProjectPrivilegeView projectPrivilege : result.getProjectPrivileges()) { - for (PrivilegeType type : getObjectTypes()) { - if (type.getPrivilegeObjectType().equals(Project.class)) { - projectPrivilege.getProjectPrivileges().add(privilegeViewFactory.create(type)); - } - } - } - } else { - result = new UserView(user); - - for (Project project : projects) { - result.getProjectPrivileges().add(result.new UserProjectPrivilegeView(project)); - } - - setPrivilegeStatusFromDb(user, result); - - createUnknownPrivileges(result); - } - - Collections.sort(result.getBasicPrivileges()); - for (UserProjectPrivilegeView row1 : result.getProjectPrivileges()) { - Collections.sort(row1.getProjectPrivileges()); - } - - return result; - } - - /** - * Creates privileges for user that doesn't exists in database. - * - * @param row - * user for which we want to add missing privileges - */ - private void createUnknownPrivileges(UserView row) { - Set<PrivilegeType> knownPrivileges = new HashSet<PrivilegeType>(); - for (PrivilegeView privilege : row.getBasicPrivileges()) { - knownPrivileges.add(privilege.getType()); - } - - for (PrivilegeType type : getBasicTypes()) { - if (!knownPrivileges.contains(type)) { - row.getBasicPrivileges().add(privilegeViewFactory.create(type)); - } - } - for (UserProjectPrivilegeView projectPrivilege : row.getProjectPrivileges()) { - knownPrivileges.clear(); - for (PrivilegeView privilege : projectPrivilege.getProjectPrivileges()) { - knownPrivileges.add(privilege.getType()); - } - for (PrivilegeType type : getObjectTypes()) { - if (type.getPrivilegeObjectType().equals(Project.class)) { - if (!knownPrivileges.contains(type)) { - projectPrivilege.getProjectPrivileges().add(privilegeViewFactory.create(type)); - } - } - } - } - } - - /** - * Method that assignes privileges from original user object into view - * representation userView. - * - * @param user - * original object retrieved from database - * @param userView - * representation of the user passed later on to higher layer - */ - private void setPrivilegeStatusFromDb(User user, UserView userView) { - for (BasicPrivilege privilege : user.getPrivileges()) { - if (privilege.getClass().equals(BasicPrivilege.class)) { - userView.getBasicPrivileges().add(privilegeViewFactory.create(privilege)); - } else if (privilege.getClass().equals(ObjectPrivilege.class)) { - if (privilege.getType().getPrivilegeObjectType().equals(Project.class)) { - int projectId = ((ObjectPrivilege) privilege).getIdObject(); - UserProjectPrivilegeView projectPrivilege = userView.getProjectPrivilegeByProjectId(projectId); - if (projectPrivilege != null) { - projectPrivilege.getProjectPrivileges().add(privilegeViewFactory.create(privilege)); - } - } else if (privilege.getType().getPrivilegeObjectType().equals(Layout.class)) { - int layoutId = ((ObjectPrivilege) privilege).getIdObject(); - UserLayoutPrivilege layoutPrivilege = userView.getLayoutPrivilegeByLayoutId(layoutId); - if (layoutPrivilege != null) { - layoutPrivilege.getLayoutPrivileges().add(privilegeViewFactory.create(privilege)); - } - } else { - throw new InvalidPrivilegeException("Unknown class for object privilege: " + privilege.getType().getPrivilegeObjectType()); - } - } else { - throw new InvalidPrivilegeException("Unknown privilege type: " + privilege.getType()); - } - } - } - - /** - * Returns list of basic privilege types (privileges that doesn't refer to - * another object). - * - * @return list of basic privilege types - */ - public List<PrivilegeType> getBasicTypes() { - if (basicTypes == null) { - fillTypeList(); - } - return basicTypes; - } - - /** - * List of type privileges that refers to {@link BasicPrivilege} class. - */ - private List<PrivilegeType> basicTypes = null; - /** - * List of type privileges that refers to {@link ObjectPrivilege} class. - */ - private List<PrivilegeType> objectTypes = null; - - /** - * Returns list of object privilege types (privileges that refer to another - * object). - * - * @return list of object privilege types - */ - public List<PrivilegeType> getObjectTypes() { - if (objectTypes == null) { - fillTypeList(); - } - return objectTypes; - } - - /** - * This method initializes {@link #basicTypes} and {@link #objectTypes} lists. - */ - private void fillTypeList() { - basicTypes = new ArrayList<PrivilegeType>(); - objectTypes = new ArrayList<PrivilegeType>(); - - PrivilegeType[] types = PrivilegeType.values(); - - for (PrivilegeType privilegeType : types) { - if (privilegeType.getPrivilegeClassType().equals(BasicPrivilege.class)) { - basicTypes.add(privilegeType); - } else if (privilegeType.getPrivilegeClassType().equals(ObjectPrivilege.class)) { - objectTypes.add(privilegeType); - } else { - throw new InvalidPrivilegeException("Unknown privilege type: " + privilegeType.getPrivilegeClassType()); - } - } - - } - - @Override - public String createGson(UserView object) { - return new Gson().toJson(object); - } - - @Override - public User viewToObject(UserView view) { - throw new NotImplementedException(); - } + + /** + * Default class logger. + */ + @SuppressWarnings("unused") + private static Logger logger = Logger.getLogger(UserViewFactory.class); + + /** + * Data access object for projects. + */ + @Autowired + private ProjectDao projectDao; + + /** + * Factory object for {@link PrivilegeView} elements. + */ + @Autowired + private PrivilegeViewFactory privilegeViewFactory; + + @Override + public UserView create(User user) { + return create(user, projectDao.getAll()); + } + + /** + * Creates {@link UserView} obejct for given user and given list of projects. + * + * @param user + * object for which {@link UserView} element will be created + * @param projects + * list of project for which privileges will be created as + * {@link PrivilegeView} elements in the result + * @return {@link UserView} obejct for given user + */ + public UserView create(User user, List<Project> projects) { + UserView result = null; + if (user == null) { + result = new UserView(); + for (Project project : projects) { + result.getProjectPrivileges().add(result.new UserProjectPrivilegeView(project)); + } + for (PrivilegeType type : getBasicTypes()) { + result.getBasicPrivileges().add(privilegeViewFactory.create(type)); + } + for (UserProjectPrivilegeView projectPrivilege : result.getProjectPrivileges()) { + for (PrivilegeType type : getObjectTypes()) { + if (type.getPrivilegeObjectType().equals(Project.class)) { + projectPrivilege.getProjectPrivileges().add(privilegeViewFactory.create(type)); + } + } + } + } else { + result = new UserView(user); + + for (Project project : projects) { + result.getProjectPrivileges().add(result.new UserProjectPrivilegeView(project)); + } + + setPrivilegeStatusFromDb(user, result); + + createUnknownPrivileges(result); + } + + Collections.sort(result.getBasicPrivileges()); + for (UserProjectPrivilegeView row1 : result.getProjectPrivileges()) { + Collections.sort(row1.getProjectPrivileges()); + } + + return result; + } + + /** + * Creates privileges for user that doesn't exists in database. + * + * @param row + * user for which we want to add missing privileges + */ + private void createUnknownPrivileges(UserView row) { + Set<PrivilegeType> knownPrivileges = new HashSet<PrivilegeType>(); + for (PrivilegeView privilege : row.getBasicPrivileges()) { + knownPrivileges.add(privilege.getType()); + } + + for (PrivilegeType type : getBasicTypes()) { + if (!knownPrivileges.contains(type)) { + row.getBasicPrivileges().add(privilegeViewFactory.create(type)); + } + } + for (UserProjectPrivilegeView projectPrivilege : row.getProjectPrivileges()) { + knownPrivileges.clear(); + for (PrivilegeView privilege : projectPrivilege.getProjectPrivileges()) { + knownPrivileges.add(privilege.getType()); + } + for (PrivilegeType type : getObjectTypes()) { + if (type.getPrivilegeObjectType().equals(Project.class)) { + if (!knownPrivileges.contains(type)) { + projectPrivilege.getProjectPrivileges().add(privilegeViewFactory.create(type)); + } + } + } + } + } + + /** + * Method that assigns privileges from original user object into view + * representation userView. + * + * @param user + * original object retrieved from database + * @param userView + * representation of the user passed later on to higher layer + */ + private void setPrivilegeStatusFromDb(User user, UserView userView) { + for (BasicPrivilege privilege : user.getPrivileges()) { + if (privilege.getClass().equals(BasicPrivilege.class)) { + userView.getBasicPrivileges().add(privilegeViewFactory.create(privilege)); + } else if (privilege.getClass().equals(ObjectPrivilege.class)) { + if (privilege.getType().getPrivilegeObjectType().equals(Project.class)) { + Integer projectId = ((ObjectPrivilege) privilege).getIdObject(); + UserProjectPrivilegeView projectPrivilege = userView.getProjectPrivilegeByProjectId(projectId); + if (projectPrivilege != null) { + projectPrivilege.getProjectPrivileges().add(privilegeViewFactory.create(privilege)); + } + } else if (privilege.getType().getPrivilegeObjectType().equals(Layout.class)) { + int layoutId = ((ObjectPrivilege) privilege).getIdObject(); + UserLayoutPrivilege layoutPrivilege = userView.getLayoutPrivilegeByLayoutId(layoutId); + if (layoutPrivilege != null) { + layoutPrivilege.getLayoutPrivileges().add(privilegeViewFactory.create(privilege)); + } + } else { + throw new InvalidPrivilegeException( + "Unknown class for object privilege: " + privilege.getType().getPrivilegeObjectType()); + } + } else { + throw new InvalidPrivilegeException("Unknown privilege type: " + privilege.getType()); + } + } + } + + /** + * Returns list of basic privilege types (privileges that doesn't refer to + * another object). + * + * @return list of basic privilege types + */ + public List<PrivilegeType> getBasicTypes() { + if (basicTypes == null) { + fillTypeList(); + } + return basicTypes; + } + + /** + * List of type privileges that refers to {@link BasicPrivilege} class. + */ + private List<PrivilegeType> basicTypes = null; + /** + * List of type privileges that refers to {@link ObjectPrivilege} class. + */ + private List<PrivilegeType> objectTypes = null; + + /** + * Returns list of object privilege types (privileges that refer to another + * object). + * + * @return list of object privilege types + */ + public List<PrivilegeType> getObjectTypes() { + if (objectTypes == null) { + fillTypeList(); + } + return objectTypes; + } + + /** + * This method initializes {@link #basicTypes} and {@link #objectTypes} lists. + */ + private void fillTypeList() { + basicTypes = new ArrayList<PrivilegeType>(); + objectTypes = new ArrayList<PrivilegeType>(); + + PrivilegeType[] types = PrivilegeType.values(); + + for (PrivilegeType privilegeType : types) { + if (privilegeType.getPrivilegeClassType().equals(BasicPrivilege.class)) { + basicTypes.add(privilegeType); + } else if (privilegeType.getPrivilegeClassType().equals(ObjectPrivilege.class)) { + objectTypes.add(privilegeType); + } else { + throw new InvalidPrivilegeException("Unknown privilege type: " + privilegeType.getPrivilegeClassType()); + } + } + + } + + @Override + public String createGson(UserView object) { + return new Gson().toJson(object); + } + + @Override + public User viewToObject(UserView view) { + throw new NotImplementedException(); + } } diff --git a/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java b/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java index be7a28143ec317cd966efc6bbf931ad7c175a5d5..b7eaa4225800da8e01abf213f9944b4b7d6705b5 100644 --- a/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java +++ b/service/src/test/java/lcsb/mapviewer/services/ServiceTestFunctions.java @@ -84,347 +84,347 @@ import lcsb.mapviewer.services.search.db.drug.IDrugService; @Transactional(value = "txManager") @Rollback(false) @ContextConfiguration(locations = { "/applicationContext-annotation.xml", // - "/applicationContext-persist.xml", // - "/applicationContext-service.xml", // - "/dataSource.xml", // + "/applicationContext-persist.xml", // + "/applicationContext-service.xml", // + "/dataSource.xml", // }) @RunWith(SpringJUnit4ClassRunner.class) public abstract class ServiceTestFunctions { - private Logger logger = Logger.getLogger(ServiceTestFunctions.class); + private Logger logger = Logger.getLogger(ServiceTestFunctions.class); - @Autowired - protected ChEMBLParser chemblParser; + @Autowired + protected ChEMBLParser chemblParser; - @Autowired - protected DrugbankHTMLParser drugBankHTMLParser; + @Autowired + protected DrugbankHTMLParser drugBankHTMLParser; - @Autowired - protected ModelAnnotator modelAnnotator; + @Autowired + protected ModelAnnotator modelAnnotator; - @Autowired - protected BiocompendiumAnnotator restService; + @Autowired + protected BiocompendiumAnnotator restService; - public double EPSILON = 1e-6; + public double EPSILON = 1e-6; - @Autowired - protected IConfigurationService configurationService; + @Autowired + protected IConfigurationService configurationService; - @Autowired - protected IModelService modelService; + @Autowired + protected IModelService modelService; - @Autowired - protected IExternalServicesService externalServicesService; + @Autowired + protected IExternalServicesService externalServicesService; - @Autowired - protected ILayoutService layoutService; + @Autowired + protected ILayoutService layoutService; - @Autowired - protected ILogService logService; + @Autowired + protected ILogService logService; - @Autowired - protected LogDao logDao; + @Autowired + protected LogDao logDao; - @Autowired - protected SearchHistoryDao searchHistoryDao; + @Autowired + protected SearchHistoryDao searchHistoryDao; - @Autowired - protected PasswordEncoder passwordEncoder; + @Autowired + protected PasswordEncoder passwordEncoder; - @Autowired - protected IUserService userService; + @Autowired + protected IUserService userService; - @Autowired - protected ConfigurationDao configurationDao; + @Autowired + protected ConfigurationDao configurationDao; - @Autowired - protected IDataMiningService dataMiningService; + @Autowired + protected IDataMiningService dataMiningService; - @Autowired - protected ISearchService searchService; + @Autowired + protected ISearchService searchService; - @Autowired - protected IDrugService drugService; + @Autowired + protected IDrugService drugService; - @Autowired - protected IChemicalService chemicalService; + @Autowired + protected IChemicalService chemicalService; - @Autowired - protected IProjectService projectService; + @Autowired + protected IProjectService projectService; - @Autowired - protected ProjectDao projectDao; + @Autowired + protected ProjectDao projectDao; - @Autowired - protected CacheQueryDao cacheQueryDao; + @Autowired + protected CacheQueryDao cacheQueryDao; - @Autowired - protected PolylineDao polylineDao; + @Autowired + protected PolylineDao polylineDao; - @Autowired - protected ModelDao modelDao; + @Autowired + protected ModelDao modelDao; - @Autowired - protected ICommentService commentService; + @Autowired + protected ICommentService commentService; - @Autowired - protected UserDao userDao; + @Autowired + protected UserDao userDao; - @Autowired - protected PrivilegeDao privilegeDao; - - @Autowired - protected CommentDao commentDao; - - @Autowired - protected DbUtils dbUtils; - - @Autowired - protected ReactionDao reactionDao; - - @Autowired - protected ElementDao aliasDao; - - protected User user; - protected User user2 = null; - - private EventStorageLoggerAppender appender; - - @Before - public final void _setUp() throws Exception { - Logger.getRootLogger().removeAppender(appender); - appender = new EventStorageLoggerAppender(); - Logger.getRootLogger().addAppender(appender); - dbUtils.setAutoFlush(false); - } - - @After - public final void _tearDown() throws Exception { - Logger.getRootLogger().removeAppender(appender); - } - - protected List<LoggingEvent> getWarnings() { - return appender.getWarnings(); - } - - 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) { - logger.debug("remove user"); - userDao.delete(user); - userDao.flush(); - } - 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); - } - - protected void createUser2() { - user2 = userDao.getUserByLogin("john.doe.bis"); - if (user2 != null) { - userDao.delete(user2); - } - user2 = new User(); - user2.setName("John"); - user2.setSurname("Doe BIS"); - user2.setEmail("john.doe@uni.lux"); - user2.setLogin("john.doe.bis"); - user2.setCryptedPassword(passwordEncoder.encode("passwd")); - userDao.add(user2); - } - - 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 = ServiceTestFunctions.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)); - ServiceTestFunctions.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(); - } + @Autowired + protected PrivilegeDao privilegeDao; + + @Autowired + protected CommentDao commentDao; + + @Autowired + protected DbUtils dbUtils; + + @Autowired + protected ReactionDao reactionDao; + + @Autowired + protected ElementDao aliasDao; + + protected User user; + protected User user2 = null; + + private EventStorageLoggerAppender appender; + + @Before + public final void _setUp() throws Exception { + Logger.getRootLogger().removeAppender(appender); + appender = new EventStorageLoggerAppender(); + Logger.getRootLogger().addAppender(appender); + dbUtils.setAutoFlush(false); + } + + @After + public final void _tearDown() throws Exception { + Logger.getRootLogger().removeAppender(appender); + } + + protected List<LoggingEvent> getWarnings() { + return appender.getWarnings(); + } + + 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) { + logger.debug("remove user"); + userDao.delete(user); + userDao.flush(); + } + 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); + } + + protected void createUser2() { + user2 = userDao.getUserByLogin("john.doe.bis"); + if (user2 != null) { + userDao.delete(user2); + } + user2 = new User(); + user2.setName("John"); + user2.setSurname("Doe BIS"); + user2.setEmail("john.doe@uni.lux"); + user2.setLogin("john.doe.bis"); + user2.setCryptedPassword(passwordEncoder.encode("passwd")); + userDao.add(user2); + } + + 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 = ServiceTestFunctions.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)); + ServiceTestFunctions.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(); + } } diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java index ca85d27c3a208e4abbd7c949575e776baaa96e46..b148ea934ac3db927b3bda976b58e251028fcb78 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/LayoutServiceTest.java @@ -95,6 +95,12 @@ public class LayoutServiceTest extends ServiceTestFunctions { projectService.addProject(project); + if (userDao.getUserByLogin("john.doe")!=null) { + userService.deleteUser(userDao.getUserByLogin("john.doe")); + } + if (userDao.getUserByLogin("john.doe.bis")!=null) { + userService.deleteUser(userDao.getUserByLogin("john.doe.bis")); + } createUser(); createUser2(); diff --git a/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java b/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java index 251681625148ae5dfde939f8838961be897b604f..967910ca147a63948c9d52f637f1840d2c1e12de 100644 --- a/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java +++ b/service/src/test/java/lcsb/mapviewer/services/impl/UserServiceTest.java @@ -31,422 +31,422 @@ import org.springframework.test.annotation.Rollback; @Rollback(true) public class UserServiceTest extends ServiceTestFunctions { - static Logger logger = Logger.getLogger(UserServiceTest.class); - - @Autowired - UserViewFactory userViewFactory; - - @Before - public void setUp() throws Exception { - createUser(); - logService.setLoggedUser(user); - } - - @After - public void tearDown() throws Exception { - userDao.delete(user); - } - - @Test - public void testLogin() { - try { - assertNull(userService.login("john.doe", "incorrect password")); - assertNotNull(userService.login("john.doe", "passwd")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testLoginWithNull() { - try { - assertNull(userService.login("john.doe", null)); - assertNull(userService.login(null, "passwd")); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUserHasPrivilegeUserPrivilegeType1() { - try { - assertFalse(userService.userHasPrivilege(user, PrivilegeType.ADD_MAP)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testUserHasPrivilegeUserPrivilegeType3() { - try { - userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT); - fail("An exception should occure. VIEW_MAP must be connected with object"); - } catch (Exception e) { - - } - } - - @Test - public void testUserHasPrivilegeUserPrivilegeType2() { - try { - BasicPrivilege privilege = new BasicPrivilege(); - privilege.setLevel(1); - privilege.setType(PrivilegeType.ADD_MAP); - userService.setUserPrivilege(user, privilege); - assertTrue(userService.userHasPrivilege(user, PrivilegeType.ADD_MAP)); - - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } - - @Test - public void testUserHasPrivilegeUserPrivilegeTypeObject() { - try { - Project project = new Project(); - projectDao.add(project); - - assertFalse(userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, project)); - try { - userService.userHasPrivilege(user, PrivilegeType.ADD_MAP, project); - fail("An exception should occure. ADD_MAP must not be connected with object"); - } catch (Exception e) { - - } - - try { - userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, user); - fail("An exception should occure. VIEW_MAP must be connected with Model type"); - } catch (Exception e) { - - } - - ObjectPrivilege privilege = new ObjectPrivilege(); - privilege.setLevel(1); - privilege.setType(PrivilegeType.VIEW_PROJECT); - privilege.setIdObject(project.getId()); - userService.setUserPrivilege(user, privilege); - - assertTrue(userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, project)); - - privilege = new ObjectPrivilege(project, 0, PrivilegeType.VIEW_PROJECT, user); - userService.setUserPrivilege(user, privilege); - - assertFalse(userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, project)); - - projectDao.delete(project); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } - - @Test - public void testUserHasPrivilegeUserPrivilegeTypeObject2() { - try { - userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, null); - fail("Exception should occur"); - } catch (InvalidArgumentException e) { - } - } - - @Test - public void testAddUser() throws Exception { - try { - long logCount = logDao.getCount(); - User user2 = new User(); - user2.setLogin("login"); - userService.addUser(user2); - assertNotNull(user2.getId()); - long logCount2 = logDao.getCount(); - assertEquals("Log entry is missing for add user event", logCount + 1, logCount2); - userDao.evict(user2); - User user3 = userService.getUserById(user2.getId()); - assertNotNull(user3); - userService.deleteUser(user3); - user3 = userService.getUserById(user2.getId()); - assertNull(user3); - - long logCount3 = logDao.getCount(); - assertEquals("Log entry is missing for remove user event", logCount2 + 1, logCount3); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testGetAllUserList() throws Exception { - try { - User user2 = new User(); - user2.setLogin("login"); - userService.addUser(user2); - - Project project = new Project(); - projectDao.add(project); - - ObjectPrivilege privilege = new ObjectPrivilege(); - privilege.setLevel(1); - privilege.setType(PrivilegeType.VIEW_PROJECT); - privilege.setIdObject(project.getId()); - userService.setUserPrivilege(user2, privilege); - - List<UserView> list = userService.getAllUserRows(); - UserView currentUser = null; - for (UserView userRow : list) { - if (userRow.getIdObject() == user2.getId()) { - currentUser = userRow; - } - } - assertNotNull(currentUser); - assertEquals(user2.getLogin(), currentUser.getLogin()); - - PrivilegeType types[] = PrivilegeType.values(); - - List<BasicPrivilege> basicTypes = new ArrayList<BasicPrivilege>(); - List<ObjectPrivilege> projectObjectTypes = new ArrayList<ObjectPrivilege>(); - for (PrivilegeType privilegeType : types) { - if (privilegeType.getPrivilegeClassType().equals(BasicPrivilege.class)) { - basicTypes.add(privilegeType.getPrivilegeClassType().newInstance()); - } else if (privilegeType.getPrivilegeClassType().equals(ObjectPrivilege.class)) { - if (privilegeType.getPrivilegeObjectType().equals(Project.class)) { - projectObjectTypes.add((ObjectPrivilege) privilegeType.getPrivilegeClassType().newInstance()); - } - } - } - - assertEquals(basicTypes.size(), currentUser.getBasicPrivileges().size()); - - long projectCount = projectDao.getCount(); - - assertEquals(projectCount, currentUser.getProjectPrivileges().size()); - - UserProjectPrivilegeView currentProject = null; - for (UserProjectPrivilegeView projectPrivilege : currentUser.getProjectPrivileges()) { - assertEquals(projectObjectTypes.size(), projectPrivilege.getProjectPrivileges().size()); - if (projectPrivilege.getIdObject() == project.getId()) { - currentProject = projectPrivilege; - } - } - assertNotNull(currentProject); - PrivilegeView currentPrivilege = null; - for (PrivilegeView row : currentProject.getProjectPrivileges()) { - if (row.getType() == PrivilegeType.VIEW_PROJECT) { - currentPrivilege = row; - } - } - assertNotNull(currentPrivilege); - assertTrue(currentPrivilege.getSelected()); - - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - /** - * Test update of a user that doesn't exist in db - */ - @Test - public void testUpdateUserRow() { - try { - Project project = new Project(); - projectDao.add(project); - - UserView userRow = userService.createEmptyUserRow(); - - for (PrivilegeView pRow : userRow.getBasicPrivileges()) { - if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { - pRow.setSelected(true); - } - } - - for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { - if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { - pRow.setSelected(true); - } - } - - userService.updateUser(userRow); - - assertNotNull(userRow.getIdObject()); - assertTrue(userRow.getIdObject() != 0); - - User user2 = userDao.getById(userRow.getIdObject()); - - assertTrue(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.PROJECT_MANAGEMENT)); - assertTrue(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - - for (PrivilegeView pRow : userRow.getBasicPrivileges()) { - if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { - pRow.setSelected(false); - } - } - - for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { - if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { - pRow.setSelected(false); - } - } - - userService.updateUser(userRow); - - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } - - /** - * Test update of a user that exist in the db - * - * @throws Exception - */ - @Test - public void testUpdateUserRow2() throws Exception { - String cryptedPassword = "passwd"; - - try { - Project project = new Project(); - projectDao.add(project); - - User user2 = new User(); - user2.setLogin("login"); - user2.setCryptedPassword(cryptedPassword); - userService.addUser(user2); - - List<UserView> rows = userService.getAllUserRows(); - UserView userRow = null; - for (UserView userRow2 : rows) { - if (userRow2.getIdObject() == user2.getId()) - userRow = userRow2; - } - - assertNotNull(userRow); - - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - - for (PrivilegeView pRow : userRow.getBasicPrivileges()) { - if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { - pRow.setSelected(true); - } - } - - for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { - if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { - pRow.setSelected(true); - } - } - - userRow.setPassword(""); - - userService.updateUser(userRow); - - User user3 = userDao.getById(user2.getId()); - - // check if password didn't change - assertEquals(cryptedPassword, user3.getCryptedPassword()); - - assertTrue(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertTrue(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - - for (PrivilegeView pRow : userRow.getBasicPrivileges()) { - if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { - pRow.setSelected(false); - } - } - - for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { - if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { - pRow.setSelected(false); - } - } - - userRow.setPassword("new passwd"); - userService.updateUser(userRow); - - user3 = userDao.getById(user2.getId()); - - // check if password changed - assertFalse(cryptedPassword.equals(user3.getCryptedPassword())); - - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); - assertFalse(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } - - @Test - public void testRemoveUserRow() throws Exception { - try { - UserView userRow = userService.createEmptyUserRow(); - userService.deleteUser(userRow); - - User user2 = new User(); - user2.setLogin("login"); - userService.addUser(user2); - - List<UserView> rows = userService.getAllUserRows(); - userRow = null; - for (UserView userRow2 : rows) { - if (userRow2.getIdObject() == user2.getId()) - userRow = userRow2; - } - - assertNotNull(userRow); - - userService.deleteUser(userRow); - - rows = userService.getAllUserRows(); - - userRow = null; - for (UserView userRow2 : rows) { - if (userRow2.getIdObject() == user2.getId()) - userRow = userRow2; - } - - assertNull(userRow); - } catch (Exception e) { - e.printStackTrace(); - throw e; - } - } + static Logger logger = Logger.getLogger(UserServiceTest.class); + + @Autowired + UserViewFactory userViewFactory; + + @Before + public void setUp() throws Exception { + createUser(); + logService.setLoggedUser(user); + } + + @After + public void tearDown() throws Exception { + userDao.delete(user); + } + + @Test + public void testLogin() { + try { + assertNull(userService.login("john.doe", "incorrect password")); + assertNotNull(userService.login("john.doe", "passwd")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testLoginWithNull() { + try { + assertNull(userService.login("john.doe", null)); + assertNull(userService.login(null, "passwd")); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testUserHasPrivilegeUserPrivilegeType1() { + try { + assertFalse(userService.userHasPrivilege(user, PrivilegeType.ADD_MAP)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testUserHasPrivilegeUserPrivilegeType3() { + try { + userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT); + fail("An exception should occure. VIEW_MAP must be connected with object"); + } catch (Exception e) { + + } + } + + @Test + public void testUserHasPrivilegeUserPrivilegeType2() { + try { + BasicPrivilege privilege = new BasicPrivilege(); + privilege.setLevel(1); + privilege.setType(PrivilegeType.ADD_MAP); + userService.setUserPrivilege(user, privilege); + assertTrue(userService.userHasPrivilege(user, PrivilegeType.ADD_MAP)); + + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception"); + } + } + + @Test + public void testUserHasPrivilegeUserPrivilegeTypeObject() { + try { + Project project = new Project(); + projectDao.add(project); + + assertFalse(userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, project)); + try { + userService.userHasPrivilege(user, PrivilegeType.ADD_MAP, project); + fail("An exception should occure. ADD_MAP must not be connected with object"); + } catch (Exception e) { + + } + + try { + userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, user); + fail("An exception should occure. VIEW_MAP must be connected with Model type"); + } catch (Exception e) { + + } + + ObjectPrivilege privilege = new ObjectPrivilege(); + privilege.setLevel(1); + privilege.setType(PrivilegeType.VIEW_PROJECT); + privilege.setIdObject(project.getId()); + userService.setUserPrivilege(user, privilege); + + assertTrue(userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, project)); + + privilege = new ObjectPrivilege(project, 0, PrivilegeType.VIEW_PROJECT, user); + userService.setUserPrivilege(user, privilege); + + assertFalse(userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, project)); + + projectDao.delete(project); + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception"); + } + } + + @Test + public void testUserHasPrivilegeUserPrivilegeTypeObject2() { + try { + userService.userHasPrivilege(user, PrivilegeType.VIEW_PROJECT, null); + fail("Exception should occur"); + } catch (InvalidArgumentException e) { + } + } + + @Test + public void testAddUser() throws Exception { + try { + long logCount = logDao.getCount(); + User user2 = new User(); + user2.setLogin("login"); + userService.addUser(user2); + assertNotNull(user2.getId()); + long logCount2 = logDao.getCount(); + assertEquals("Log entry is missing for add user event", logCount + 1, logCount2); + userDao.evict(user2); + User user3 = userService.getUserById(user2.getId()); + assertNotNull(user3); + userService.deleteUser(user3); + user3 = userService.getUserById(user2.getId()); + assertNull(user3); + + long logCount3 = logDao.getCount(); + assertEquals("Log entry is missing for remove user event", logCount2 + 1, logCount3); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testGetAllUserList() throws Exception { + try { + User user2 = new User(); + user2.setLogin("login"); + userService.addUser(user2); + + Project project = new Project(); + projectDao.add(project); + + ObjectPrivilege privilege = new ObjectPrivilege(); + privilege.setLevel(1); + privilege.setType(PrivilegeType.VIEW_PROJECT); + privilege.setIdObject(project.getId()); + userService.setUserPrivilege(user2, privilege); + + List<UserView> list = userService.getAllUserRows(); + UserView currentUser = null; + for (UserView userRow : list) { + if (userRow.getIdObject() == user2.getId()) { + currentUser = userRow; + } + } + assertNotNull(currentUser); + assertEquals(user2.getLogin(), currentUser.getLogin()); + + PrivilegeType types[] = PrivilegeType.values(); + + List<BasicPrivilege> basicTypes = new ArrayList<BasicPrivilege>(); + List<ObjectPrivilege> projectObjectTypes = new ArrayList<ObjectPrivilege>(); + for (PrivilegeType privilegeType : types) { + if (privilegeType.getPrivilegeClassType().equals(BasicPrivilege.class)) { + basicTypes.add(privilegeType.getPrivilegeClassType().newInstance()); + } else if (privilegeType.getPrivilegeClassType().equals(ObjectPrivilege.class)) { + if (privilegeType.getPrivilegeObjectType().equals(Project.class)) { + projectObjectTypes.add((ObjectPrivilege) privilegeType.getPrivilegeClassType().newInstance()); + } + } + } + + assertEquals(basicTypes.size(), currentUser.getBasicPrivileges().size()); + + long projectCount = projectDao.getCount(); + + assertEquals(projectCount, currentUser.getProjectPrivileges().size()); + + UserProjectPrivilegeView currentProject = null; + for (UserProjectPrivilegeView projectPrivilege : currentUser.getProjectPrivileges()) { + assertEquals(projectObjectTypes.size(), projectPrivilege.getProjectPrivileges().size()); + if (projectPrivilege.getIdObject() == project.getId()) { + currentProject = projectPrivilege; + } + } + assertNotNull(currentProject); + PrivilegeView currentPrivilege = null; + for (PrivilegeView row : currentProject.getProjectPrivileges()) { + if (row.getType() == PrivilegeType.VIEW_PROJECT) { + currentPrivilege = row; + } + } + assertNotNull(currentPrivilege); + assertTrue(currentPrivilege.getSelected()); + + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + /** + * Test update of a user that doesn't exist in db + */ + @Test + public void testUpdateUserRow() { + try { + Project project = new Project(); + projectDao.add(project); + + UserView userRow = userService.createEmptyUserRow(); + + for (PrivilegeView pRow : userRow.getBasicPrivileges()) { + if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { + pRow.setSelected(true); + } + } + + for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { + if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { + pRow.setSelected(true); + } + } + + userService.updateUser(userRow); + + assertNotNull(userRow.getIdObject()); + assertTrue(userRow.getIdObject() != 0); + + User user2 = userDao.getById(userRow.getIdObject()); + + assertTrue(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); + assertFalse(userService.userHasPrivilege(user2, PrivilegeType.PROJECT_MANAGEMENT)); + assertTrue(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); + + for (PrivilegeView pRow : userRow.getBasicPrivileges()) { + if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { + pRow.setSelected(false); + } + } + + for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { + if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { + pRow.setSelected(false); + } + } + + userService.updateUser(userRow); + + assertFalse(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); + assertFalse(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + /** + * Test update of a user that exist in the db + * + * @throws Exception + */ + @Test + public void testUpdateUserRow2() throws Exception { + String cryptedPassword = "passwd"; + + try { + Project project = new Project(); + projectDao.add(project); + + User user2 = new User(); + user2.setLogin("login"); + user2.setCryptedPassword(cryptedPassword); + userService.addUser(user2); + + List<UserView> rows = userService.getAllUserRows(); + UserView userRow = null; + for (UserView userRow2 : rows) { + if (userRow2.getIdObject() == user2.getId()) + userRow = userRow2; + } + + assertNotNull(userRow); + + assertFalse(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); + assertFalse(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); + + for (PrivilegeView pRow : userRow.getBasicPrivileges()) { + if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { + pRow.setSelected(true); + } + } + + for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { + if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { + pRow.setSelected(true); + } + } + + userRow.setPassword(""); + + userService.updateUser(userRow); + + User user3 = userDao.getById(user2.getId()); + + // check if password didn't change + assertEquals(cryptedPassword, user3.getCryptedPassword()); + + assertTrue(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); + assertTrue(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); + + for (PrivilegeView pRow : userRow.getBasicPrivileges()) { + if (pRow.getType().equals(PrivilegeType.ADD_MAP)) { + pRow.setSelected(false); + } + } + + for (PrivilegeView pRow : userRow.getProjectPrivilegeByProjectId(project.getId()).getProjectPrivileges()) { + if (pRow.getType().equals(PrivilegeType.VIEW_PROJECT)) { + pRow.setSelected(false); + } + } + + userRow.setPassword("new passwd"); + userService.updateUser(userRow); + + user3 = userDao.getById(user2.getId()); + + // check if password changed + assertFalse(cryptedPassword.equals(user3.getCryptedPassword())); + + assertFalse(userService.userHasPrivilege(user2, PrivilegeType.ADD_MAP)); + assertFalse(userService.userHasPrivilege(user2, PrivilegeType.VIEW_PROJECT, project)); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } + + @Test + public void testRemoveUserRow() throws Exception { + try { + UserView userRow = userService.createEmptyUserRow(); + userService.deleteUser(userRow); + + User user2 = new User(); + user2.setLogin("login"); + userService.addUser(user2); + + List<UserView> rows = userService.getAllUserRows(); + userRow = null; + for (UserView userRow2 : rows) { + if (userRow2.getIdObject() == user2.getId()) + userRow = userRow2; + } + + assertNotNull(userRow); + + userService.deleteUser(userRow); + + rows = userService.getAllUserRows(); + + userRow = null; + for (UserView userRow2 : rows) { + if (userRow2.getIdObject() == user2.getId()) + userRow = userRow2; + } + + assertNull(userRow); + } catch (Exception e) { + e.printStackTrace(); + throw e; + } + } - @Test - public void testCreateEmptyUserRow() { - try { - Project project = new Project(); - projectDao.add(project); + @Test + public void testCreateEmptyUserRow() { + try { + Project project = new Project(); + projectDao.add(project); - UserView row = userService.createEmptyUserRow(); + UserView row = userService.createEmptyUserRow(); - assertNotNull(row); - - long projectCount = projectDao.getCount(); + assertNotNull(row); + + long projectCount = projectDao.getCount(); - assertEquals(projectCount, row.getProjectPrivileges().size()); - assertNotNull(row.getProjectPrivilegeByProjectId(project.getId())); + assertEquals(projectCount, row.getProjectPrivileges().size()); + assertNotNull(row.getProjectPrivilegeByProjectId(project.getId())); - for (UserProjectPrivilegeView upRow : row.getProjectPrivileges()) { - assertTrue(userViewFactory.getObjectTypes().size() >= upRow.getProjectPrivileges().size()); - } - assertEquals(userViewFactory.getBasicTypes().size(), row.getBasicPrivileges().size()); + for (UserProjectPrivilegeView upRow : row.getProjectPrivileges()) { + assertTrue(userViewFactory.getObjectTypes().size() >= upRow.getProjectPrivileges().size()); + } + assertEquals(userViewFactory.getBasicTypes().size(), row.getBasicPrivileges().size()); - } catch (Exception e) { - e.printStackTrace(); - fail("Unknown exception"); - } - } + } catch (Exception e) { + e.printStackTrace(); + fail("Unknown exception"); + } + } }