Skip to content
Snippets Groups Projects
Commit 8304918f authored by Piotr Gawron's avatar Piotr Gawron
Browse files

first rest methods

* login and rest token managament implemented
* getting of project info via rest added
parent 67bc0bc4
No related branches found
No related tags found
1 merge request!5Frontend refactor
Showing
with 982 additions and 68 deletions
......@@ -14,6 +14,9 @@
<springframework.version>4.2.0.RELEASE</springframework.version>
<springframework.security.version>4.0.2.RELEASE</springframework.security.version>
<springframework.security.oauth.version>2.0.12.RELEASE</springframework.security.oauth.version>
<springframework.webflow.version>2.4.2.RELEASE</springframework.webflow.version>
<xercesImp.version>2.11.0</xercesImp.version>
......@@ -31,7 +34,6 @@
<jersey.version>1.18.1</jersey.version>
<rs-jax.version>1.1.1</rs-jax.version>
<log4j.version>1.2.17</log4j.version>
......
......@@ -12,6 +12,7 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" path="src/main/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
......
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="MapViewer-rest-api">
<wb-resource deploy-path="/" source-path="/src/main/java"/>
<wb-resource deploy-path="/" source-path="/src/main/resources"/>
</wb-module>
</project-modules>
......@@ -20,6 +20,12 @@
<version>1.0</version>
</dependency>
<dependency>
<groupId>lcsb.mapviewer</groupId>
<artifactId>service</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
......@@ -36,5 +42,12 @@
<artifactId>jersey-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-faces</artifactId>
<version>${springframework.webflow.version}</version>
</dependency>
</dependencies>
</project>
package lcsb.mapviewer.api;
import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
public abstract class BaseController {
Logger logger = Logger.getLogger(BaseController.class);
@ExceptionHandler({ Exception.class })
public ResponseEntity<Object> handleException(Exception e, WebRequest request) {
logger.error(e, e);
if (e instanceof SecurityException) {
return new ResponseEntity<Object>("{\"error\" : \"Access denied.\",\"reason\":\"" + e.getMessage() + "\"}", new HttpHeaders(), HttpStatus.FORBIDDEN);
} else {
return new ResponseEntity<Object>(
"{\"error\" : \"Internal server error.\",\"reason\":\"" + e.getMessage() + "\"}", new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
package lcsb.mapviewer.api;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import lcsb.mapviewer.model.Project;
/**
* RESTfull API servlet for operations on {@link Project} objects.
*
* @author Piotr Gawron
*
*/
@Path("/project")
public class ProjectApiServlet {
/**
* Returns list of projects.
*
* @return {@link Response} object with list of projects
*/
@GET
@Path("/list")
public Response getMsg() {
String output = "Hello";
return Response.status(Response.Status.OK).entity(output).build();
}
}
package lcsb.mapviewer.api.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import lcsb.mapviewer.api.BaseController;
import lcsb.mapviewer.common.Configuration;
import lcsb.mapviewer.services.interfaces.IUserService;
import lcsb.mapviewer.services.view.AuthenticationToken;
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {
Logger logger = Logger.getLogger(UserController.class);
@Autowired
private IUserService userService;
@RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
public AuthenticationToken greeting(@RequestParam(value = "login", defaultValue = Configuration.ANONYMOUS_LOGIN) String login,
@RequestParam(value = "password", required = false) String password) {
AuthenticationToken token = userService.login(login, password);
return token;
}
/**
* @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;
}
}
\ No newline at end of file
package lcsb.mapviewer.api.project;
import java.awt.geom.Point2D;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import org.primefaces.model.map.LatLng;
import lcsb.mapviewer.common.Configuration;
import lcsb.mapviewer.model.map.layout.Layout;
import lcsb.mapviewer.model.map.model.Model;
import lcsb.mapviewer.model.map.model.ModelData;
import lcsb.mapviewer.model.map.model.ModelSubmodelConnection;
import lcsb.mapviewer.services.utils.gmap.CoordinationConverter;
import lcsb.mapviewer.services.view.LayoutView;
import lcsb.mapviewer.services.view.LayoutViewFactory;
public class ModelMetaData implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Version of the model.
*/
private String version;
/**
* Name of the model.
*/
private String name;
/**
* Size in pixels of the single square tile (small image used for graphical
* representation).
*/
private Integer tileSize;
private Integer width;
private Integer height;
/**
* Minimum zoom level that should be allowed by the Google Maps API.
*/
private Integer minZoom;
/**
* Maximum zoom level that should be allowed by the Google Maps API.
*/
private Integer maxZoom;
private List<LayoutView> layouts = new ArrayList<>();
/**
* List of submodels in the model.
*/
private List<ModelMetaData> submodels = new ArrayList<>();
/**
* Where is the center of the map in latituted, longiude format.
*/
private LatLng centerLatLng;
/**
* Top-Left corner of the map (0,0) as a latLng coordinates.
*/
private LatLng topLeftLatLng;
/**
* Bottom-Right corner of the map (width,height) as a latLng coordinates.
*/
private LatLng bottomRightLatLng;
/**
* Default constructor.
*/
public ModelMetaData(Model model) {
this(model.getModelData());
}
public ModelMetaData(ModelData model) {
this.setName(model.getName());
this.setMinZoom(Configuration.MIN_ZOOM_LEVEL);
this.setMaxZoom(this.getMinZoom() + model.getZoomLevels());
this.setTileSize(model.getTileSize());
this.setWidth((int) (double) model.getWidth());
this.setHeight((int) (double) model.getHeight());
int size = Math.max(width, height);
CoordinationConverter cConverter = new CoordinationConverter(model);
this.setCenterLatLng(cConverter.toLatLng(new Point2D.Double(size / 2, size / 2)));
this.setBottomRightLatLng(cConverter.toLatLng(new Point2D.Double(model.getWidth(), model.getHeight())));
this.setTopLeftLatLng(cConverter.toLatLng(new Point2D.Double(0, 0)));
List<ModelMetaData> submodels = new ArrayList<>();
for (ModelSubmodelConnection connection : model.getSubmodels()) {
submodels.add(new ModelMetaData(connection.getSubmodel().getModel()));
}
LayoutViewFactory factory = new LayoutViewFactory();
for (Layout layout : model.getLayouts()) {
if (layout.isPublicLayout()) {
layouts.add(factory.create(layout));
}
}
this.setSubmodels(submodels);
}
protected ModelMetaData() {
}
/**
* @return the version
* @see #version
*/
public String getVersion() {
return version;
}
/**
* @param version
* the version to set
* @see #version
*/
public void setVersion(String version) {
this.version = version;
}
/**
* @return the tileSize
* @see #tileSize
*/
public Integer getTileSize() {
return tileSize;
}
/**
* @param tileSize
* the tileSize to set
* @see #tileSize
*/
public void setTileSize(Integer tileSize) {
this.tileSize = tileSize;
}
/**
* @return the minZoom
* @see #minZoom
*/
public Integer getMinZoom() {
return minZoom;
}
/**
* @param minZoom
* the minZoom to set
* @see #minZoom
*/
public void setMinZoom(Integer minZoom) {
this.minZoom = minZoom;
}
/**
* @return the maxZoom
* @see #maxZoom
*/
public Integer getMaxZoom() {
return maxZoom;
}
/**
* @param maxZoom
* the maxZoom to set
* @see #maxZoom
*/
public void setMaxZoom(Integer maxZoom) {
this.maxZoom = maxZoom;
}
/**
* @return the centerLatLng
* @see #centerLatLng
*/
public LatLng getCenterLatLng() {
return centerLatLng;
}
/**
* @param centerLatLng
* the centerLatLng to set
* @see #centerLatLng
*/
public void setCenterLatLng(LatLng centerLatLng) {
this.centerLatLng = centerLatLng;
}
/**
* @return the name
* @see #name
*/
public String getName() {
return name;
}
/**
* @param name
* the name to set
* @see #name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the topLeftLatLng
* @see #topLeftLatLng
*/
public LatLng getTopLeftLatLng() {
return topLeftLatLng;
}
/**
* @param topLeftLatLng
* the topLeftLatLng to set
* @see #topLeftLatLng
*/
public void setTopLeftLatLng(LatLng topLeftLatLng) {
this.topLeftLatLng = topLeftLatLng;
}
/**
* @return the bottomRightLatLng
* @see #bottomRightLatLng
*/
public LatLng getBottomRightLatLng() {
return bottomRightLatLng;
}
/**
* @param bottomRightLatLng
* the bottomRightLatLng to set
* @see #bottomRightLatLng
*/
public void setBottomRightLatLng(LatLng bottomRightLatLng) {
this.bottomRightLatLng = bottomRightLatLng;
}
/**
* @return the width
* @see #width
*/
public Integer getWidth() {
return width;
}
/**
* @param width
* the width to set
* @see #width
*/
public void setWidth(Integer width) {
this.width = width;
}
/**
* @return the height
* @see #height
*/
public Integer getHeight() {
return height;
}
/**
* @param height
* the height to set
* @see #height
*/
public void setHeight(Integer height) {
this.height = height;
}
/**
* @return the submodels
* @see #submodels
*/
public List<ModelMetaData> getSubmodels() {
return submodels;
}
/**
* @param submodels
* the submodels to set
* @see #submodels
*/
public void setSubmodels(List<ModelMetaData> submodels) {
this.submodels = submodels;
}
/**
* @return the layouts
* @see #layouts
*/
public List<LayoutView> getLayouts() {
return layouts;
}
/**
* @param layouts the layouts to set
* @see #layouts
*/
public void setLayouts(List<LayoutView> layouts) {
this.layouts = layouts;
}
}
package lcsb.mapviewer.api.project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import lcsb.mapviewer.api.BaseController;
import lcsb.mapviewer.services.SecurityException;
@RestController
@RequestMapping("/project")
public class ProjectController extends BaseController {
@Autowired
private ProjectRestImpl projectController;
@RequestMapping(value = "/getMetaData", method = { RequestMethod.GET, RequestMethod.POST }, produces = { MediaType.APPLICATION_JSON_VALUE })
public ProjectMetaData getMetaData(@RequestParam(value = "projectId") String projectId, @RequestParam(value = "token") String token)
throws SecurityException {
return projectController.getMetaData(projectId, token);
}
}
\ No newline at end of file
package lcsb.mapviewer.api.project;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import lcsb.mapviewer.model.Project;
import lcsb.mapviewer.model.map.OverviewImage;
import lcsb.mapviewer.model.map.OverviewImageLink;
import lcsb.mapviewer.model.map.OverviewLink;
import lcsb.mapviewer.model.map.model.ModelData;
import lcsb.mapviewer.services.view.OverviewImageView;
import lcsb.mapviewer.services.view.OverviewImageViewFactory;
public class ProjectMetaData implements Serializable {
private static Logger logger = Logger.getLogger(ProjectMetaData.class);
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Version of the project.
*/
private String version;
/**
* Name of the project.
*/
private String name;
/**
* {@link lcsb.mapviewer.model.Project#projectId Project identifier}.
*/
private String projectId;
/**
* Description of the model.
*/
private String description;
private ModelMetaData map;
/**
* List of overview images attached to this model.
*/
private List<OverviewImageView> overviewImageViews;
/**
* Top level overview image.
*/
private OverviewImageView topOverviewImage;
/**
* Default constructor. Should be used only for deserialization.
*/
protected ProjectMetaData() {
}
public ProjectMetaData(Project project) {
OverviewImageViewFactory factory = new OverviewImageViewFactory();
ModelData model = null;
if (project.getModels().size() > 0) {
model = project.getModels().iterator().next();
}
this.setName(project.getName());
this.setProjectId(project.getProjectId());
if (model != null) {
this.setOverviewImageViews(factory.createList(model.getOverviewImages()));
this.setVersion(model.getMapVersion());
this.setDescription(model.getNotes());
Set<OverviewImage> set = new HashSet<OverviewImage>();
set.addAll(model.getOverviewImages());
for (OverviewImage image : model.getOverviewImages()) {
for (OverviewLink ol : image.getLinks()) {
if (ol instanceof OverviewImageLink) {
set.remove(((OverviewImageLink) ol).getLinkedOverviewImage());
}
}
}
if (set.size() > 0) {
this.setTopOverviewImage(factory.create(set.iterator().next()));
} else if (model.getOverviewImages().size() > 0) {
logger.warn("Cannot determine top level image. Taking first one. " + model.getOverviewImages().get(0).getFilename());
this.setTopOverviewImage(factory.create(model.getOverviewImages().get(0)));
}
this.setMap(new ModelMetaData(model));
}
}
/**
* @return the version
* @see #version
*/
public String getVersion() {
return version;
}
/**
* @param version
* the version to set
* @see #version
*/
public void setVersion(String version) {
this.version = version;
}
/**
* @return the description
* @see #description
*/
public String getDescription() {
return description;
}
/**
* @param description
* the description to set
* @see #description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the 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 overviewImageViews
* @see #overviewImageViews
*/
public List<OverviewImageView> getOverviewImageViews() {
return overviewImageViews;
}
/**
* @param overviewImageViews
* the overviewImageViews to set
* @see #overviewImageViews
*/
public void setOverviewImageViews(List<OverviewImageView> overviewImageViews) {
this.overviewImageViews = overviewImageViews;
}
/**
* @return the topOverviewImage
* @see #topOverviewImage
*/
public OverviewImageView getTopOverviewImage() {
return topOverviewImage;
}
/**
* @param topOverviewImage
* the topOverviewImage to set
* @see #topOverviewImage
*/
public void setTopOverviewImage(OverviewImageView topOverviewImage) {
this.topOverviewImage = topOverviewImage;
}
/**
* @return the projectId
* @see #projectId
*/
public String getProjectId() {
return projectId;
}
/**
* @param projectId
* the projectName to set
* @see #projectId
*/
public void setProjectId(String projectId) {
this.projectId = projectId;
}
/**
* @return the map
* @see #map
*/
public ModelMetaData getMap() {
return map;
}
/**
* @param map
* the map to set
* @see #map
*/
public void setMap(ModelMetaData map) {
this.map = map;
}
}
package lcsb.mapviewer.api.project;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import lcsb.mapviewer.model.Project;
import lcsb.mapviewer.services.SecurityException;
import lcsb.mapviewer.services.interfaces.IProjectService;
import lcsb.mapviewer.services.interfaces.IUserService;
@Transactional(value = "txManager")
public class ProjectRestImpl {
@Autowired
private IUserService userService;
@Autowired
private IProjectService projectService;
public ProjectMetaData getMetaData(@RequestParam(value = "projectId") String projectId, @RequestParam(value = "token") String token)
throws SecurityException {
Project project = projectService.getProjectByProjectId(projectId, userService.getToken(token));
ProjectMetaData result = new ProjectMetaData(project);
return result;
}
/**
* @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;
}
}
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="ProjectRestImpl" class="lcsb.mapviewer.api.project.ProjectRestImpl"/>
</beans>
\ No newline at end of file
package lcsb.mapviewer.api.project;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.Gson;
import lcsb.mapviewer.model.map.model.Model;
import lcsb.mapviewer.model.map.model.ModelFullIndexed;
public class ModelMetaDataTest {
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
try {
Model model = new ModelFullIndexed(null);
model.setWidth(10);
model.setHeight(10);
model.setTileSize(128);
ModelMetaData data = new ModelMetaData(model);
String json = new Gson().toJson(data);
assertNotNull(json);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
package lcsb.mapviewer.api.project;
import static org.junit.Assert.assertNotNull;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.Gson;
import lcsb.mapviewer.model.Project;
public class ProjectMetaDataTest {
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testToGson() {
try {
Project project = new Project();
ProjectMetaData data = new ProjectMetaData(project);
Gson gson = new Gson();
assertNotNull(gson.toJson(data));
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
package lcsb.mapviewer.services;
public class AuthenticationTokenExpireException extends SecurityException {
public AuthenticationTokenExpireException(String message) {
super(message);
}
}
package lcsb.mapviewer.services;
public class InvalidTokenException extends SecurityException {
public InvalidTokenException(String message) {
super(message);
}
}
package lcsb.mapviewer.services;
public class SecurityException extends Exception {
public SecurityException(String message) {
super(message);
}
}
package lcsb.mapviewer.services;
public class UserAccessException extends SecurityException {
public UserAccessException(String message) {
super(message);
}
}
......@@ -84,6 +84,7 @@ import lcsb.mapviewer.persist.dao.ProjectDao;
import lcsb.mapviewer.persist.dao.map.CommentDao;
import lcsb.mapviewer.persist.dao.map.ModelDao;
import lcsb.mapviewer.persist.dao.user.UserDao;
import lcsb.mapviewer.services.UserAccessException;
import lcsb.mapviewer.services.interfaces.ICommentService;
import lcsb.mapviewer.services.interfaces.IConfigurationService;
import lcsb.mapviewer.services.interfaces.IDataMiningService;
......@@ -100,6 +101,7 @@ import lcsb.mapviewer.services.utils.CreateProjectParams;
import lcsb.mapviewer.services.utils.EmailSender;
import lcsb.mapviewer.services.utils.InvalidDataMiningInputFile;
import lcsb.mapviewer.services.utils.data.BuildInLayout;
import lcsb.mapviewer.services.view.AuthenticationToken;
import lcsb.mapviewer.services.view.ProjectView;
import lcsb.mapviewer.services.view.ProjectViewFactory;
......@@ -258,8 +260,11 @@ public class ProjectService implements IProjectService {
private MapGenerator generator = new MapGenerator();
@Override
public Project getProjectByProjectId(String name) {
public Project getProjectByProjectId(String name, AuthenticationToken token) throws UserAccessException {
Project result = projectDao.getProjectByProjectId(name);
if (!userService.userHasPrivilege(token, PrivilegeType.VIEW_PROJECT, result)) {
throw new UserAccessException("User cannot access project");
}
return result;
}
......@@ -333,9 +338,9 @@ public class ProjectService implements IProjectService {
}
@Override
public void removeProject(ProjectView selectedProject, String homeDir, boolean async) {
public void removeProject(ProjectView selectedProject, String homeDir, boolean async, AuthenticationToken token) throws UserAccessException {
Project project = projectDao.getById(selectedProject.getIdObject());
removeProject(project, homeDir, async);
removeProject(project, homeDir, async, token);
}
/**
......@@ -354,13 +359,17 @@ public class ProjectService implements IProjectService {
}
@Override
public ProjectView getProjectViewByProjectId(String name) {
Project project = getProjectByProjectId(name);
public ProjectView getProjectViewByProjectId(String name, AuthenticationToken token) throws UserAccessException {
Project project = getProjectByProjectId(name, token);
return projectViewFactory.create(project);
}
@Override
public void removeProject(final Project p, final String dir, final boolean async) {
public void removeProject(final Project p, final String dir, final boolean async, AuthenticationToken token) throws UserAccessException {
if (!userService.userHasPrivilege(userService.getUserByToken(token), PrivilegeType.PROJECT_MANAGEMENT)) {
throw new UserAccessException("User cannot remove project");
}
final String homeDir;
if (dir != null) {
if (p.getDirectory() != null) {
......@@ -433,7 +442,7 @@ public class ProjectService implements IProjectService {
} catch (HibernateException e) {
logger.error("Problem with database", e);
handleHibernateExceptionRemovingReporting(project, e);
handleHibernateExceptionRemovingReporting(project, e, token);
} finally {
if (async) {
// close the transaction for this thread
......@@ -473,7 +482,7 @@ public class ProjectService implements IProjectService {
* @param exception
* hibernate exception that caused problems
*/
protected void handleHibernateExceptionRemovingReporting(Project originalProject, HibernateException exception) {
protected void handleHibernateExceptionRemovingReporting(Project originalProject, HibernateException exception, AuthenticationToken token) {
// we need to open separate thread because current one thrown db exception
// and transaction is corrupetd and will be rolledback
Thread reportInSeparateThread = new Thread(new Runnable() {
......@@ -481,14 +490,20 @@ public class ProjectService implements IProjectService {
@Override
public void run() {
dbUtils.createSessionForCurrentThread();
// we need to get the project from db, because session where
// originalProject was retrieved is broken
Project project = getProjectByProjectId(originalProject.getProjectId());
String errorMessage = "Severe problem with removing object. Underlaying eror:\n" + exception.getMessage()
+ "\nMore information can be found in log file.";
project.setErrors(errorMessage + "\n" + project.getErrors());
project.setStatus(ProjectStatus.FAIL);
dbUtils.closeSessionForCurrentThread();
try {
// we need to get the project from db, because session where
// originalProject was retrieved is broken
Project project = getProjectByProjectId(originalProject.getProjectId(), token);
String errorMessage = "Severe problem with removing object. Underlaying eror:\n" + exception.getMessage()
+ "\nMore information can be found in log file.";
project.setErrors(errorMessage + "\n" + project.getErrors());
project.setStatus(ProjectStatus.FAIL);
projectDao.update(project);
} catch (UserAccessException e) {
logger.error(e, e);
} finally {
dbUtils.closeSessionForCurrentThread();
}
}
});
......@@ -502,8 +517,12 @@ public class ProjectService implements IProjectService {
}
@Override
public ProjectView getProjectViewById(Integer id) {
return projectViewFactory.create(projectDao.getById(id));
public ProjectView getProjectViewById(Integer id, AuthenticationToken token) throws UserAccessException {
Project project = projectDao.getById(id);
if (!userService.userHasPrivilege(token, PrivilegeType.VIEW_PROJECT, project)) {
throw new UserAccessException("User cannot access project");
}
return projectViewFactory.create(project);
}
/**
......@@ -1399,12 +1418,19 @@ public class ProjectService implements IProjectService {
public void run() {
dbUtils.createSessionForCurrentThread();
Project project = getProjectByProjectId(params.getProjectId());
String errorMessage = "Problem with uploading to database. You might violated some unhandled constraints or you run out of memory. Underlaying eror:\n"
+ e.getMessage() + "\nMore information can be found in log file.";
project.setErrors(errorMessage);
project.setStatus(ProjectStatus.FAIL);
dbUtils.closeSessionForCurrentThread();
try {
Project project = getProjectByProjectId(params.getProjectId(), params.getAuthenticationToken());
String errorMessage = "Problem with uploading to database. "
+ "You might violated some unhandled constraints or you run out of memory. Underlaying eror:\n" + e.getMessage()
+ "\nMore information can be found in log file.";
project.setErrors(errorMessage);
project.setStatus(ProjectStatus.FAIL);
projectDao.update(project);
} catch (Exception e) {
logger.error(e, e);
} finally {
dbUtils.closeSessionForCurrentThread();
}
}
});
......
......@@ -2,8 +2,11 @@ package lcsb.mapviewer.services.impl;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -11,6 +14,7 @@ import org.springframework.security.crypto.password.PasswordEncoder;
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.exception.InvalidArgumentException;
import lcsb.mapviewer.common.geometry.ColorParser;
......@@ -24,10 +28,14 @@ import lcsb.mapviewer.model.user.User;
import lcsb.mapviewer.persist.dao.ProjectDao;
import lcsb.mapviewer.persist.dao.user.PrivilegeDao;
import lcsb.mapviewer.persist.dao.user.UserDao;
import lcsb.mapviewer.services.AuthenticationTokenExpireException;
import lcsb.mapviewer.services.InvalidTokenException;
import lcsb.mapviewer.services.SecurityException;
import lcsb.mapviewer.services.interfaces.IConfigurationService;
import lcsb.mapviewer.services.interfaces.ILogService;
import lcsb.mapviewer.services.interfaces.ILogService.LogParams;
import lcsb.mapviewer.services.interfaces.IUserService;
import lcsb.mapviewer.services.view.AuthenticationToken;
import lcsb.mapviewer.services.view.PrivilegeView;
import lcsb.mapviewer.services.view.UserView;
import lcsb.mapviewer.services.view.UserView.UserProjectPrivilegeView;
......@@ -41,56 +49,93 @@ import lcsb.mapviewer.services.view.UserViewFactory;
*/
@Transactional(value = "txManager")
public class UserService implements IUserService {
private static Map<String, AuthenticationToken> authenticationTokens = new HashMap<>();
private static Map<AuthenticationToken, User> authenticatedUsers = new HashMap<>();
/**
* Default class logger.
*/
private static Logger logger = Logger.getLogger(UserService.class);
private static Logger logger = Logger.getLogger(UserService.class);
/**
* Data access object for users.
*/
@Autowired
private UserDao userDao;
private UserDao userDao;
/**
* Data access object for projects.
*/
@Autowired
private ProjectDao projectDao;
private ProjectDao projectDao;
/**
* Data access object for privileges.
*/
@Autowired
private PrivilegeDao privilegeDao;
private PrivilegeDao privilegeDao;
/**
* Factory object for {@link UserView} elements.
*/
@Autowired
private UserViewFactory userViewFactory;
private UserViewFactory userViewFactory;
/**
* Service that provides password encoding.
*/
@Autowired
private PasswordEncoder passwordEncoder;
private PasswordEncoder passwordEncoder;
/**
* Service used for logging.
*/
@Autowired
private ILogService logService;
private ILogService logService;
/**
* Service used for accessing confguration parameters.
*/
@Autowired
private IConfigurationService configurationService;
private IConfigurationService configurationService;
@Override
public boolean login(String login, String password) {
return userDao.getUserByLoginAndPassword(login, password) != null;
public AuthenticationToken login(String login, String password) {
User user = userDao.getUserByLoginAndPassword(login, password);
if (login.equals(Configuration.ANONYMOUS_LOGIN)) {
user = getUserByLogin(Configuration.ANONYMOUS_LOGIN);
}
if (user != null) {
int count = 0;
synchronized (authenticationTokens) {
count = authenticationTokens.size();
}
if (count > 1000) {
clearAuthenticationTokens();
}
AuthenticationToken authenticationToken = new AuthenticationToken();
synchronized (authenticationTokens) {
authenticationTokens.put(authenticationToken.getId(), authenticationToken);
authenticatedUsers.put(authenticationToken, user);
}
return authenticationToken;
} else {
return null;
}
}
private void clearAuthenticationTokens() {
synchronized (authenticationTokens) {
List<String> toRemove = new ArrayList<>();
for (AuthenticationToken token : authenticationTokens.values()) {
if (token.getExpires().before(Calendar.getInstance())) {
toRemove.add(token.getId());
}
}
}
}
@Override
......@@ -462,4 +507,48 @@ public class UserService implements IUserService {
public void setConfigurationService(IConfigurationService configurationService) {
this.configurationService = configurationService;
}
@Override
public User getUserByToken(AuthenticationToken token) {
User result = null;
if (Calendar.getInstance().before(token.getExpires())) {
synchronized (authenticationTokens) {
result = authenticatedUsers.get(token);
}
}
return result;
}
@Override
public User getUserByToken(String tokenString) throws SecurityException {
return getUserByToken(getToken(tokenString));
}
@Override
public AuthenticationToken getToken(String tokenString) throws SecurityException {
AuthenticationToken result = null;
synchronized (authenticationTokens) {
result = authenticationTokens.get(tokenString);
}
if (result == null) {
throw new InvalidTokenException("Token string is invalid");
}
if (result.getExpires().before(Calendar.getInstance())) {
logout(result);
throw new AuthenticationTokenExpireException("Token validity expired");
}
return result;
}
public void logout(AuthenticationToken result) {
synchronized (authenticationTokens) {
authenticationTokens.remove(result.getId());
authenticatedUsers.remove(result);
}
}
@Override
public boolean userHasPrivilege(AuthenticationToken token, PrivilegeType type, Object object) {
return userHasPrivilege(getUserByToken(token), type, object);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment