From 023f9b39fa5f02022522b07824b7623c0e966088 Mon Sep 17 00:00:00 2001 From: Felix Jordan Date: Wed, 12 Oct 2022 12:00:37 +0200 Subject: [PATCH 01/42] WIP: Add gamification basics using Gamification Framework --- ...is.bazaar.service.BazaarService.properties | 5 + .../acis/bazaar/service/BazaarService.java | 18 ++- .../service/dal/entities/EntityBase.java | 17 +++ .../service/gamification/GFNotification.java | 11 ++ .../GamificationFrameworkClient.java | 105 ++++++++++++++++++ .../gamification/GamificationManager.java | 89 +++++++++++++++ .../resources/RequirementsResource.java | 6 + 7 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GFNotification.java create mode 100644 reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java create mode 100644 reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java diff --git a/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties b/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties index 7ce0879a..f265e440 100644 --- a/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties +++ b/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties @@ -15,3 +15,8 @@ twitterApiKey= twitterApiKeySecret= twitterClientId= twitterClientSecret= +gfGameServiceUrl= +gfVisualizationServiceUrl= +gfUsername= +gfPassword= +gfGameId= \ No newline at end of file diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java index 3bf33997..15e86498 100755 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -32,6 +32,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import de.rwth.dbis.acis.bazaar.service.gamification.GamificationManager; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.notification.ActivityDispatcher; import de.rwth.dbis.acis.bazaar.service.notification.EmailDispatcher; @@ -53,6 +54,7 @@ import i5.las2peer.restMapper.annotations.ServicePath; import io.swagger.annotations.*; import lombok.Getter; +import okhttp3.HttpUrl; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.http.client.utils.URIBuilder; import org.jooq.SQLDialect; @@ -91,6 +93,7 @@ public class BazaarService extends RESTService { private final List functionRegistrar; private final NotificationDispatcher notificationDispatcher; private final TweetDispatcher tweetDispatcher; + private final GamificationManager gamificationManager; private final DataSource dataSource; //CONFIG PROPERTIES @@ -111,6 +114,12 @@ public class BazaarService extends RESTService { protected String twitterClientId; protected String twitterClientSecret; + protected String gfGameServiceUrl; + protected String gfVisualizationServiceUrl; + protected String gfUsername; + protected String gfPassword; + protected String gfGameId; + public BazaarService() throws Exception { setFieldValues(); Locale locale = new Locale(lang, country); @@ -166,9 +175,10 @@ public BazaarService() throws Exception { } tweetDispatcher = new TweetDispatcher(this, twitterApiKey, twitterApiKeySecret, twitterClientId, twitterClientSecret); - new WeeklyNewProjectsTweetTask(this).schedule(timer); + gamificationManager = new GamificationManager(gfGameServiceUrl, gfVisualizationServiceUrl, gfUsername, gfPassword, gfGameId); + notificationDispatcher.setBazaarService(this); } @@ -236,6 +246,10 @@ public TweetDispatcher getTweetDispatcher() { return tweetDispatcher; } + public GamificationManager getGamificationManager() { + return gamificationManager; + } + private void registerUserAtFirstLogin() throws Exception { Agent agent = Context.getCurrent().getMainAgent(); @@ -274,6 +288,8 @@ private void registerUserAtFirstLogin() throws Exception { int userId = user.getId(); // this.getNotificationDispatcher().dispatchNotification(user.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_55, userId, Activity.DataType.USER, userId); dalFacade.addUserToRole(userId, "LoggedInUser", null); + + gamificationManager.initializeUser(userId); } else { // update lastLoginDate dalFacade.updateLastLoginDate(userIdByLAS2PeerId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java index df72d589..3fb4a4a4 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java @@ -20,17 +20,25 @@ package de.rwth.dbis.acis.bazaar.service.dal.entities; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import de.rwth.dbis.acis.bazaar.service.dal.helpers.SerializerViews; +import de.rwth.dbis.acis.bazaar.service.gamification.GFNotification; +import org.apache.commons.lang3.Validate; /** * @since 9/16/2014 */ public abstract class EntityBase implements IdentifiedById { + private List gamificationNotifications = new ArrayList<>(); + public String toJSON() throws JsonProcessingException { return new ObjectMapper().registerModule(new JavaTimeModule()) .setSerializationInclusion(JsonInclude.Include.NON_NULL) @@ -45,4 +53,13 @@ public String toPrivateJSON() throws JsonProcessingException { .writerWithView(SerializerViews.Private.class) .writeValueAsString(this); } + + public void setGamificationNotifications(List gamificationNotifications) { + Validate.notNull(gamificationNotifications); + gamificationNotifications = gamificationNotifications; + } + + public List getGamificationNotifications() { + return gamificationNotifications; + } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GFNotification.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GFNotification.java new file mode 100644 index 00000000..cb80ff3d --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GFNotification.java @@ -0,0 +1,11 @@ +package de.rwth.dbis.acis.bazaar.service.gamification; + +import java.util.Map; + +import lombok.Value; + +@Value +public class GFNotification { + + private Map data; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java new file mode 100644 index 00000000..e12feac3 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -0,0 +1,105 @@ +package de.rwth.dbis.acis.bazaar.service.gamification; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.MapType; +import i5.las2peer.logging.L2pLogger; +import okhttp3.*; +import org.apache.commons.lang3.Validate; + +public class GamificationFrameworkClient { + + private final L2pLogger logger = L2pLogger.getInstance(GamificationFrameworkClient.class.getName()); + + private final HttpUrl gfGameServiceUrl; + private final HttpUrl gfVisualizationServiceUrl; + + private final OkHttpClient httpClient; + private final ObjectMapper objectMapper = new ObjectMapper(); + + public GamificationFrameworkClient(String gfGameServiceUrl, String gfVisualizationServiceUrl, String gfUsername, String gfPassword) { + this.gfGameServiceUrl = HttpUrl.parse(gfGameServiceUrl); + this.gfVisualizationServiceUrl = HttpUrl.parse(gfVisualizationServiceUrl); + + httpClient = new OkHttpClient.Builder() + .authenticator((route, response) -> { + if (response.request().header("Authorization") != null) { + return null; + } + String credential = Credentials.basic(gfUsername, gfPassword); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + }) + .build(); + } + + public void addMemberToGame(String gameId, String memberUsername) throws IOException { + Validate.notBlank(gameId); + Validate.notBlank(memberUsername); + + Request request = new Request.Builder() + .url(gfGameServiceUrl.newBuilder() + .addPathSegment("data") + .addPathSegment(gameId) + .addPathSegment(memberUsername) + .build() + ) + .method("POST", null) + .build(); + + try (Response response = httpClient.newCall(request).execute()) { + if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + + logger.info("Added member " + memberUsername + " to game " + gameId + " (response: " + response.body().string() + ")"); + } + } + + public List triggerAction(String gameId, String actionId, String username) throws IOException { + Validate.notBlank(gameId); + Validate.notBlank(actionId); + Validate.notBlank(username); + + Request request = new Request.Builder() + .url(gfVisualizationServiceUrl.newBuilder() + .addPathSegment("actions") + .addPathSegment(gameId) + .addPathSegment(actionId) + .addPathSegment(username) + .build() + ) + .method("POST", null) + .build(); + + try (Response response = httpClient.newCall(request).execute()) { + if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + + String rawResponse = response.body().string(); + logger.info("Triggered action " + actionId + " on game " + gameId + " for user " + username + " (response: " + rawResponse + ")"); + + final MapType mapType = objectMapper.getTypeFactory().constructMapType( + Map.class, String.class, Object.class); + Map responseJson = objectMapper.readValue(rawResponse, mapType); + + // process notifications + List notifications = new ArrayList<>(); + if (responseJson.containsKey("notification")) { + Object notificationRoot = responseJson.get("notification"); + if (notificationRoot instanceof List) { + ((List) notificationRoot).forEach(notificationJson -> { + notifications.add(new GFNotification((Map) notificationJson)); + }); + } else if (notificationRoot instanceof Map) { + notifications.add(new GFNotification((Map) notificationRoot)); + } else { + logger.warning("Unexpected value of 'notification' object: " + notificationRoot); + } + } + return notifications; + } + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java new file mode 100644 index 00000000..b4ccfee8 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -0,0 +1,89 @@ +package de.rwth.dbis.acis.bazaar.service.gamification; + +import java.io.IOException; +import java.util.*; + +import i5.las2peer.logging.L2pLogger; +import org.apache.commons.lang3.StringUtils; + +public class GamificationManager { + + private final L2pLogger logger = L2pLogger.getInstance(GamificationManager.class.getName()); + + private final GamificationFrameworkClient gfClient; + private final String gfGameId; + + /** + * Notifications returned by the framework during request processing. + * + * Can be returned to the client by querying + */ + private Map> notificationCache = new HashMap<>(); + + public GamificationManager(String gfGameServiceUrl, String gfVisualizationServiceUrl, String gfUsername, String gfPassword, String gfGameId) { + this.gfGameId = gfGameId; + + if (StringUtils.isAnyBlank(gfGameServiceUrl, gfVisualizationServiceUrl, gfUsername, gfPassword, gfGameId)) { + logger.warning("Gamification functionality cannot be used without GamificationFramework credentials!"); + gfClient = null; + } else { + gfClient = new GamificationFrameworkClient(gfGameServiceUrl, gfVisualizationServiceUrl, gfUsername, gfPassword); + } + } + + public void initializeUser(Integer userId) { + if (!isAvailable()) { + logger.warning("Cannot add user to Gamification Framework. Gamification is not configured"); + return; + } + + try { + gfClient.addMemberToGame(gfGameId, userId.toString()); + } catch (IOException e) { + logger.warning("Failed to add user to gamification framework: " + e.getMessage()); + e.printStackTrace(); + } + } + + public void triggerCreateRequirementAction(Integer userId) { + triggerActionIfGamificationAvailable(Actions.CREATE_REQUIREMENT, userId); + } + + private void triggerActionIfGamificationAvailable(String actionId, Integer userId) { + if (!isAvailable()) { + logger.warning("Cannot trigger action " + actionId + ". Gamification is not configured"); + return; + } + + try { + List notifications = gfClient.triggerAction(gfGameId, actionId, userId.toString()); + storeUserNotifications(userId, notifications); + } catch (IOException e) { + logger.warning("Failed to trigger action " + actionId + " for user " + userId); + e.printStackTrace(); + } + } + + public List getUserNotifications(Integer userId) { + if (notificationCache.containsKey(userId)) { + return Collections.unmodifiableList(notificationCache.get(userId)); + } + return Collections.emptyList(); + } + + private void storeUserNotifications(Integer userId, List notifications) { + if (notificationCache.containsKey(userId)) { + notificationCache.get(userId).addAll(notifications); + } else { + notificationCache.put(userId, new ArrayList<>(notifications)); + } + } + + private boolean isAvailable() { + return gfClient != null; + } + + private static class Actions { + private static final String CREATE_REQUIREMENT = "create_req"; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index 6a682973..75fd8be4 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -519,6 +519,12 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir createdRequirement = dalFacade.getRequirementById(createdRequirement.getId(), internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_26, createdRequirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); + + // trigger Gamification Framework + bazaarService.getGamificationManager().triggerCreateRequirementAction(internalUserId); + // add notifications to response + createdRequirement.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); + return Response.status(Response.Status.CREATED).entity(createdRequirement.toJSON()).build(); } catch (BazaarException bex) { if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { From 5a9823d96fb3cf16a8ec1d73f117276d3a6e7a35 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 3 Jan 2023 12:10:09 +0100 Subject: [PATCH 02/42] docs: update java version --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9b4cd6f5..ec4b06f9 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ However you'll have to apply the migrations with liquibase manually to this data The build and test process is done with gradle. A simple `gradle build` should be sufficient to build the project and run the test cases. -You may have to adjust either your global java environment or the one in your IDE to use Java 14 or the built asset won't start. +You may have to adjust either your global java environment or the one in your IDE to use Java 17 or the built asset won't start. ### Debugging From 71300ad8ffedae5cd94d188bab8d22da9a29dd65 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 3 Jan 2023 12:11:11 +0100 Subject: [PATCH 03/42] fix: emojis in test not working on windows --- .../de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java index 0c053333..950ba6b7 100644 --- a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java +++ b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java @@ -85,7 +85,7 @@ public void testCreateGetProject() throws Exception { assertEquals(project.getName(), projectById.getName()); assertEquals(project.getDescription(), projectById.getDescription()); - assertEquals("An 😀awesome 😃string with a few 😉emojis!", projectById.getDescription()); + assertEquals("An \uD83D\uDE00awesome \uD83D\uDE03string with a few \uD83D\uDE09emojis!", projectById.getDescription()); assertEquals(project.getLeader().getId(), projectById.getLeader().getId()); assertEquals(project.getVisibility(), projectById.getVisibility()); assertTrue(projectById.isOwner(initUser)); From 2deed02807b7afdb2889ea0993b161db5b581804 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 3 Jan 2023 12:12:17 +0100 Subject: [PATCH 04/42] refactor: reduce complexity in CategoryResource --- .../service/resources/CategoryResource.java | 132 +++++++++--------- 1 file changed, 69 insertions(+), 63 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java index 5954f481..a65bb2a7 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java @@ -1,5 +1,6 @@ package de.rwth.dbis.acis.bazaar.service.resources; +import com.fasterxml.jackson.core.JsonProcessingException; import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; @@ -18,6 +19,7 @@ import i5.las2peer.api.security.Agent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; +import org.jetbrains.annotations.NotNull; import javax.validation.ConstraintViolation; import javax.ws.rs.*; @@ -25,6 +27,7 @@ import javax.ws.rs.core.Response; import javax.xml.bind.DatatypeConverter; import java.net.HttpURLConnection; +import java.net.URISyntaxException; import java.text.MessageFormat; import java.time.OffsetDateTime; import java.util.*; @@ -76,37 +79,13 @@ public Response getCategoriesForProject(int projectId, int page, int perPage, St Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } - List sortList = new ArrayList<>(); - for (String sortOption : sort) { - Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); - sortList.add(sortField); - } + checkRegistrarErrors(registrarErrors); + List sortList = getSortFieldList(sort, sortDirection); PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), sortList, search); // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } - + checkViolations(pageInfo); dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - if (dalFacade.getProjectById(projectId, internalUserId) == null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "category")); - } - if (dalFacade.isProjectPublic(projectId)) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); - } - } + Integer internalUserId = getInternalUserId(projectId, dalFacade, userId); PaginationResult categoriesResult = dalFacade.listCategoriesByProjectId(projectId, pageInfo, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_13, projectId, Activity.DataType.PROJECT, internalUserId); @@ -124,10 +103,7 @@ public Response getCategoriesForProject(int projectId, int page, int perPage, St } parameter.put("sort", sort); - Response.ResponseBuilder responseBuilder = Response.ok(); - responseBuilder = responseBuilder.entity(categoriesResult.toJSON()); - responseBuilder = bazaarService.paginationLinks(responseBuilder, categoriesResult, "projects/" + String.valueOf(projectId) + "/categories", parameter); - responseBuilder = bazaarService.xHeaderFields(responseBuilder, categoriesResult); + Response.ResponseBuilder responseBuilder = buildCategoryForProjectResponse(projectId, categoriesResult, parameter); return responseBuilder.build(); } catch (BazaarException bex) { @@ -150,6 +126,57 @@ public Response getCategoriesForProject(int projectId, int page, int perPage, St } } + private Response.ResponseBuilder buildCategoryForProjectResponse(int projectId, PaginationResult categoriesResult, Map> parameter) throws JsonProcessingException, URISyntaxException { + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(categoriesResult.toJSON()); + responseBuilder = bazaarService.paginationLinks(responseBuilder, categoriesResult, "projects/" + String.valueOf(projectId) + "/categories", parameter); + responseBuilder = bazaarService.xHeaderFields(responseBuilder, categoriesResult); + return responseBuilder; + } + + @NotNull + private static Integer getInternalUserId(int projectId, DALFacade dalFacade, String userId) throws Exception { + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + if (dalFacade.getProjectById(projectId, internalUserId) == null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "category")); + } + if (dalFacade.isProjectPublic(projectId)) { + boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, projectId, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, projectId, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); + } + } + return internalUserId; + } + + private void checkViolations(PageInfo pageInfo) throws BazaarException { + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + } + + @NotNull + private static List getSortFieldList(List sort, String sortDirection) { + List sortList = new ArrayList<>(); + for (String sortOption : sort) { + Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); + sortList.add(sortField); + } + return sortList; + } + + private static void checkRegistrarErrors(String registrarErrors) throws BazaarException { + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + } + /** * This method allows to retrieve a certain category. * @@ -172,9 +199,7 @@ public Response getCategory(@PathParam("categoryId") int categoryId) { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + checkRegistrarErrors(registrarErrors); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category categoryToReturn = dalFacade.getCategoryById(categoryId, internalUserId); @@ -236,9 +261,7 @@ public Response createCategory(@ApiParam(value = "Category entity", required = t // TODO: check whether the current user may create a new project // TODO: check whether all required parameters are entered String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + checkRegistrarErrors(registrarErrors); // Take Object for generic error handling Set> violations = bazaarService.validateCreate(categoryToCreate); if (violations.size() > 0) { @@ -296,9 +319,7 @@ public Response updateCategory(@ApiParam(value = "Category entity", required = t DALFacade dalFacade = null; try { String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + checkRegistrarErrors(registrarErrors); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); // Take Object for generic error handling @@ -363,9 +384,7 @@ public Response deleteCategory(@PathParam("categoryId") int categoryId) { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + checkRegistrarErrors(registrarErrors); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category categoryToDelete = dalFacade.getCategoryById(categoryId, internalUserId); @@ -428,9 +447,7 @@ public Response followCategory(@PathParam("categoryId") int categoryId) { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + checkRegistrarErrors(registrarErrors); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); @@ -484,9 +501,7 @@ public Response unfollowCategory(@PathParam("categoryId") int categoryId) { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + checkRegistrarErrors(registrarErrors); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); @@ -541,9 +556,7 @@ public Response getStatisticsForCategory( DALFacade dalFacade = null; try { String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + checkRegistrarErrors(registrarErrors); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); @@ -596,9 +609,7 @@ public Response getContributorsForCategory(@PathParam("categoryId") int category Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + checkRegistrarErrors(registrarErrors); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); @@ -652,15 +663,10 @@ public Response getFollowersForCategory(@PathParam("categoryId") int categoryId, Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + checkRegistrarErrors(registrarErrors); PageInfo pageInfo = new PageInfo(page, perPage); // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + checkViolations(pageInfo); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); From 8972f0040a04ec5353626c8d6801858c8f59d1c7 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 10 Jan 2023 11:27:05 +0100 Subject: [PATCH 05/42] Refactor: refactoring duplications in resources --- .../service/resources/AdminResource.java | 9 +- .../service/resources/CategoryResource.java | 40 +++--- .../service/resources/CommentsResource.java | 34 ++--- .../service/resources/FeedbackResource.java | 10 +- .../PersonalisationDataResource.java | 14 +-- .../service/resources/ProjectsResource.java | 84 +++---------- .../resources/RequirementsResource.java | 119 ++++-------------- .../service/resources/UsersResource.java | 34 ++--- .../service/resources/WebhookResource.java | 9 +- .../resources/helpers/ResourceHelper.java | 25 ++++ 10 files changed, 128 insertions(+), 250 deletions(-) create mode 100644 reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java index d50f7df3..41711266 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java @@ -24,6 +24,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import de.rwth.dbis.acis.bazaar.service.twitter.WeeklyNewProjectsTweetTask; import i5.las2peer.api.Context; @@ -62,11 +63,14 @@ public class AdminResource { private L2pLogger logger = L2pLogger.getInstance(AdminResource.class.getName()); private BazaarService bazaarService; + private ResourceHelper resourceHelper; + @javax.ws.rs.core.Context UriInfo uriInfo; public AdminResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); + resourceHelper = new ResourceHelper(bazaarService); } @POST @@ -220,10 +224,7 @@ private Response handleAuthenticatedRequest( try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java index a65bb2a7..bb30e4b9 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java @@ -13,6 +13,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; @@ -58,8 +59,11 @@ public class CategoryResource { private final L2pLogger logger = L2pLogger.getInstance(CategoryResource.class.getName()); private final BazaarService bazaarService; + private ResourceHelper resourceHelper; + public CategoryResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); + resourceHelper = new ResourceHelper(bazaarService); } /** @@ -78,8 +82,7 @@ public Response getCategoriesForProject(int projectId, int page, int perPage, St try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); List sortList = getSortFieldList(sort, sortDirection); PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), sortList, search); // Take Object for generic error handling @@ -171,12 +174,6 @@ private static List getSortFieldList(List sort, Stri return sortList; } - private static void checkRegistrarErrors(String registrarErrors) throws BazaarException { - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } - } - /** * This method allows to retrieve a certain category. * @@ -198,8 +195,7 @@ public Response getCategory(@PathParam("categoryId") int categoryId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category categoryToReturn = dalFacade.getCategoryById(categoryId, internalUserId); @@ -260,8 +256,7 @@ public Response createCategory(@ApiParam(value = "Category entity", required = t String userId = agent.getIdentifier(); // TODO: check whether the current user may create a new project // TODO: check whether all required parameters are entered - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); // Take Object for generic error handling Set> violations = bazaarService.validateCreate(categoryToCreate); if (violations.size() > 0) { @@ -318,8 +313,7 @@ public Response updateCategory(@ApiParam(value = "Category entity", required = t DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); // Take Object for generic error handling @@ -383,8 +377,7 @@ public Response deleteCategory(@PathParam("categoryId") int categoryId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category categoryToDelete = dalFacade.getCategoryById(categoryId, internalUserId); @@ -446,8 +439,7 @@ public Response followCategory(@PathParam("categoryId") int categoryId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); @@ -500,8 +492,7 @@ public Response unfollowCategory(@PathParam("categoryId") int categoryId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); @@ -555,8 +546,7 @@ public Response getStatisticsForCategory( @ApiParam(value = "Since timestamp, ISO-8601 e.g. 2017-12-30 or 2017-12-30T18:30:00Z", required = false) @QueryParam("since") String since) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); @@ -608,8 +598,7 @@ public Response getContributorsForCategory(@PathParam("categoryId") int category try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); @@ -662,8 +651,7 @@ public Response getFollowersForCategory(@PathParam("categoryId") int categoryId, try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - checkRegistrarErrors(registrarErrors); + resourceHelper.checkRegistrarErrors(); PageInfo pageInfo = new PageInfo(page, perPage); // Take Object for generic error handling checkViolations(pageInfo); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java index 7db68afa..944d736e 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java @@ -12,6 +12,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; @@ -54,8 +55,11 @@ public class CommentsResource { private final L2pLogger logger = L2pLogger.getInstance(CommentsResource.class.getName()); private final BazaarService bazaarService; + private ResourceHelper resourceHelper; + public CommentsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); + resourceHelper = new ResourceHelper(bazaarService); } @@ -88,10 +92,7 @@ public Response getAllComments( DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); List sortList = new ArrayList<>(); @@ -182,10 +183,7 @@ public Response getCommentsForRequirement(int requirementId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); //Todo use requirement's projectId for security context, not the one sent from client @@ -252,10 +250,7 @@ public Response getComment(@PathParam("commentId") int commentId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Comment comment = dalFacade.getCommentById(commentId); @@ -318,10 +313,7 @@ public Response createComment(@ApiParam(value = "Comment entity", required = tru String userId = agent.getIdentifier(); // TODO: check whether the current user may create a new requirement // TODO: check whether all required parameters are entered - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(commentToCreate.getRequirementId(), internalUserId); @@ -379,10 +371,7 @@ public Response updateComment(@ApiParam(value = "Comment entity", required = tru try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -443,10 +432,7 @@ public Response deleteComment(@PathParam("commentId") int commentId) { // TODO: check if the user may delete this requirement. Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java index 42351001..d284b5a8 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java @@ -14,6 +14,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; @@ -57,8 +58,11 @@ public class FeedbackResource { private final L2pLogger logger = L2pLogger.getInstance(CommentsResource.class.getName()); private final BazaarService bazaarService; + private ResourceHelper resourceHelper; + public FeedbackResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); + resourceHelper = new ResourceHelper(bazaarService); } /** @@ -74,10 +78,7 @@ public Response getFeedbackForProject(int projectId, int page, int perPage) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); PageInfo pageInfo = new PageInfo(page, perPage); // Take Object for generic error handling Set> violations = bazaarService.validate(pageInfo); @@ -133,6 +134,7 @@ public Response getFeedbackForProject(int projectId, int page, int perPage) { } } + /** * This method allows to create a new comment. * diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java index b1b81085..0fde6013 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java @@ -10,6 +10,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; @@ -51,8 +52,11 @@ public class PersonalisationDataResource { private final L2pLogger logger = L2pLogger.getInstance(PersonalisationDataResource.class.getName()); private BazaarService bazaarService; + private ResourceHelper resourceHelper; + public PersonalisationDataResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); + resourceHelper = new ResourceHelper(bazaarService); } @@ -79,10 +83,7 @@ public Response getPersonalisationData(@PathParam("key") String key, @PathParam( try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -135,10 +136,7 @@ public Response setPersonalisationData(@PathParam("key") String key, @PathParam( Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java index 92c7e3ea..5c83514b 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java @@ -13,6 +13,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; @@ -56,8 +57,11 @@ public class ProjectsResource { private final L2pLogger logger = L2pLogger.getInstance(ProjectsResource.class.getName()); private final BazaarService bazaarService; + private ResourceHelper resourceHelper; + public ProjectsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); + resourceHelper = new ResourceHelper(bazaarService); } /** @@ -89,10 +93,7 @@ public Response getProjects( @ApiParam(value = "Also search in projects requirements", required = false) @DefaultValue("false") @QueryParam("recursive") boolean recursive) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); List sortList = new ArrayList<>(); @@ -184,10 +185,7 @@ public Response getProjects( public Response getProject(@PathParam("projectId") int projectId) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); @@ -253,10 +251,7 @@ public Response getProject(@PathParam("projectId") int projectId) { public Response createProject(@ApiParam(value = "Project entity", required = true) Project projectToCreate) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); @@ -315,10 +310,7 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru public Response updateProject(@ApiParam(value = "Project entity", required = true) Project projectToUpdate) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); @@ -380,10 +372,7 @@ public Response deleteProject(@PathParam("projectId") int projectId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -437,10 +426,7 @@ public Response followProject(@PathParam("projectId") int projectId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); @@ -493,10 +479,7 @@ public Response unfollowProject(@PathParam("projectId") int projectId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); @@ -550,10 +533,7 @@ public Response getStatisticsForProject( @ApiParam(value = "Since timestamp, ISO-8601 e.g. 2017-12-30 or 2017-12-30T18:30:00Z", required = false) @QueryParam("since") String since) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); dalFacade = bazaarService.getDBConnection(); @@ -604,10 +584,7 @@ public Response getContributorsForProject(@PathParam("projectId") int projectId) try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); ProjectContributors projectContributors = dalFacade.listContributorsForProject(projectId); @@ -659,10 +636,7 @@ public Response getFollowersForProject(@PathParam("projectId") int projectId, try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); PageInfo pageInfo = new PageInfo(page, perPage); // Take Object for generic error handling @@ -826,10 +800,7 @@ public Response getTagsForProject( try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -904,10 +875,7 @@ public Response createTag(@PathParam("projectId") int projectId, try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -966,10 +934,7 @@ public Response addMember(@PathParam("projectId") int projectId, @ApiParam(value = "New project member", required = true) ProjectMember projectMember) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); @@ -1050,10 +1015,7 @@ public Response updateMember(@PathParam("projectId") int projectId, @ApiParam(value = "New or updated project member", required = true) List projectMembers) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); @@ -1131,10 +1093,7 @@ public Response getMembers(@PathParam("projectId") int projectId, DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); @@ -1204,10 +1163,7 @@ public Response removeMember( @ApiParam(value = "User ID of the member to remove") @PathParam("memberUserId") int memberUserId) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index 6a682973..817098c2 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -13,6 +13,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; @@ -58,8 +59,11 @@ public class RequirementsResource { private final L2pLogger logger = L2pLogger.getInstance(RequirementsResource.class.getName()); private final BazaarService bazaarService; + private ResourceHelper resourceHelper; + public RequirementsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); + resourceHelper = new ResourceHelper(bazaarService); } @@ -91,10 +95,7 @@ public Response getRequirements( DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); List sortList = new ArrayList<>(); @@ -187,10 +188,7 @@ public Response getRequirementsForProject(int projectId, int page, int perPage, try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); HashMap filters = new HashMap<>(); if (!Objects.equals(stateFilter, "all")) { filters.put("realized", stateFilter); @@ -287,10 +285,7 @@ public Response getRequirementsForCategory(int categoryId, int page, int perPage try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); HashMap filters = new HashMap<>(); if (!Objects.equals(stateFilter, "all")) { filters.put("realized", stateFilter); @@ -394,10 +389,7 @@ public Response getRequirement(@PathParam("requirementId") int requirementId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); @@ -460,10 +452,7 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_REQUIREMENT, requirementToCreate.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.create")); @@ -557,10 +546,7 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir public Response updateRequirement(@ApiParam(value = "Requirement entity", required = true) Requirement requirementToUpdate) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); // Take Object for generic error handling @@ -626,10 +612,7 @@ public Response deleteRequirement(@PathParam("requirementId") int requirementId) try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirementToDelete = dalFacade.getRequirementById(requirementId, internalUserId); @@ -703,10 +686,7 @@ public Response leaddevelopRequirement(@PathParam("requirementId") int requireme try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); @@ -758,10 +738,7 @@ public Response unleaddevelopRequirement(@PathParam("requirementId") int require try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); @@ -817,10 +794,7 @@ public Response developRequirement(@PathParam("requirementId") int requirementId try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); @@ -877,10 +851,7 @@ public Response undevelopRequirement(@PathParam("requirementId") int requirement try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); @@ -936,10 +907,7 @@ public Response moveRequirement(@PathParam("requirementId") int requirementId, N try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); // ensure requirement exists @@ -1014,10 +982,7 @@ public Response followRequirement(@PathParam("requirementId") int requirementId) try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); @@ -1070,10 +1035,7 @@ public Response unfollowRequirement(@PathParam("requirementId") int requirementI try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); @@ -1128,10 +1090,7 @@ public Response vote(@PathParam("requirementId") int requirementId, try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -1187,10 +1146,7 @@ public Response unvote(@PathParam("requirementId") int requirementId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_VOTE, dalFacade); @@ -1240,10 +1196,7 @@ public Response realize(@PathParam("requirementId") int requirementId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); @@ -1296,10 +1249,7 @@ public Response unrealize(@PathParam("requirementId") int requirementId) { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -1356,10 +1306,7 @@ public Response getStatisticsForRequirement( @ApiParam(value = "Since timestamp, ISO-8601 e.g. 2017-12-30 or 2017-12-30T18:30:00Z", required = false) @QueryParam("since") String since) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); dalFacade = bazaarService.getDBConnection(); @@ -1414,10 +1361,7 @@ public Response getDevelopersForRequirement(@PathParam("requirementId") int requ try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); PageInfo pageInfo = new PageInfo(page, perPage); // Take Object for generic error handling Set> violations = bazaarService.validate(pageInfo); @@ -1486,10 +1430,7 @@ public Response getContributorsForRequirement(@PathParam("requirementId") int re try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); RequirementContributors requirementContributors = dalFacade.listContributorsForRequirement(requirementId); @@ -1541,10 +1482,7 @@ public Response getFollowersForRequirement(@PathParam("requirementId") int requi try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); PageInfo pageInfo = new PageInfo(page, perPage); // Take Object for generic error handling Set> violations = bazaarService.validate(pageInfo); @@ -1638,10 +1576,7 @@ public Response getAttachmentsForRequirement(@PathParam("requirementId") int req try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); PageInfo pageInfo = new PageInfo(page, perPage); Set> violations = bazaarService.validate(pageInfo); if (violations.size() > 0) { diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java index 8e52beb3..9052c005 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java @@ -12,6 +12,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; @@ -53,8 +54,11 @@ public class UsersResource { private final L2pLogger logger = L2pLogger.getInstance(UsersResource.class.getName()); private final BazaarService bazaarService; + private ResourceHelper resourceHelper; + public UsersResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); + resourceHelper = new ResourceHelper(bazaarService); } /** @@ -76,10 +80,7 @@ public Response searchUser(@ApiParam(value = "Search filter", required = false) @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); dalFacade = bazaarService.getDBConnection(); @@ -162,10 +163,7 @@ public Response getUser(@PathParam("userId") int userId) { DALFacade dalFacade = null; try { // TODO: check whether the current user may request this project - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); User user = dalFacade.getUserById(userId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_53, @@ -212,10 +210,7 @@ public Response getActiveUser() { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); // Block anonymous user if (userId.equals("anonymous")) { @@ -268,10 +263,7 @@ public Response getUserDashboard() { try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); // Block anonymous user if (userId.equals("anonymous")) { @@ -326,10 +318,7 @@ public Response updateUser(@PathParam("userId") int userId, @ApiParam(value = "User entity as JSON", required = true) User userToUpdate) { DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); // Take Object for generic error handling @@ -396,10 +385,7 @@ public Response getEntityOverview( //Possibly allow filtertype "all"? DALFacade dalFacade = null; try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); List sortList = new ArrayList<>(); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/WebhookResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/WebhookResource.java index c062d811..f02e6e46 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/WebhookResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/WebhookResource.java @@ -13,6 +13,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; import i5.las2peer.api.security.Agent; @@ -58,12 +59,15 @@ public class WebhookResource { private L2pLogger logger = L2pLogger.getInstance(WebhookResource.class.getName()); private BazaarService bazaarService; + private ResourceHelper resourceHelper; + private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public WebhookResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); + resourceHelper = new ResourceHelper(bazaarService); } /** @@ -107,10 +111,7 @@ public Response handleWebhook(@PathParam("projectId") int projectId, String requ // DB Operations DALFacade dalFacade = null; - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION,BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if(registrarErrors != null){ - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } + resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java new file mode 100644 index 00000000..231f1771 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java @@ -0,0 +1,25 @@ +package de.rwth.dbis.acis.bazaar.service.resources.helpers; + +import de.rwth.dbis.acis.bazaar.service.BazaarFunction; +import de.rwth.dbis.acis.bazaar.service.BazaarService; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; + +import java.util.EnumSet; + +public class ResourceHelper { + private final BazaarService bazaarService; + + public ResourceHelper(BazaarService service){ + this.bazaarService = service; + } + + public void checkRegistrarErrors() throws BazaarException { + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + } +} From 582b514b5ace2d832d4457e06ec1aa10546d231c Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 10 Jan 2023 12:24:42 +0100 Subject: [PATCH 06/42] Refactor: refactoring duplicate response map building --- .../service/resources/CategoryResource.java | 22 ++------------ .../service/resources/CommentsResource.java | 13 +------- .../service/resources/FeedbackResource.java | 8 +---- .../service/resources/ProjectsResource.java | 22 ++------------ .../service/resources/UsersResource.java | 13 +------- .../resources/helpers/ResourceHelper.java | 30 +++++++++++++++++-- 6 files changed, 34 insertions(+), 74 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java index bb30e4b9..79111ed2 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java @@ -92,19 +92,7 @@ public Response getCategoriesForProject(int projectId, int page, int perPage, St PaginationResult categoriesResult = dalFacade.listCategoriesByProjectId(projectId, pageInfo, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_13, projectId, Activity.DataType.PROJECT, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); - if (search != null) { - parameter.put("search", new ArrayList() {{ - add(String.valueOf(search)); - }}); - } - parameter.put("sort", sort); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, search, sort); Response.ResponseBuilder responseBuilder = buildCategoryForProjectResponse(projectId, categoriesResult, parameter); @@ -662,13 +650,7 @@ public Response getFollowersForCategory(@PathParam("categoryId") int categoryId, PaginationResult categoryFollowers = dalFacade.listFollowersForCategory(categoryId, pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_23, categoryId, Activity.DataType.CATEGORY, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(categoryFollowers.toJSON()); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java index 944d736e..792daed9 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java @@ -129,18 +129,7 @@ public Response getAllComments( //bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, // 0, Activity.DataType.COMMENT, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); - if (search != null) { - parameter.put("search", new ArrayList() {{ - add(String.valueOf(search)); - }}); - } + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); parameter.put("embedParents", embedParents); parameter.put("sort", sort); parameter.put("filters", filters); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java index d284b5a8..9b33f158 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java @@ -100,13 +100,7 @@ public Response getFeedbackForProject(int projectId, int page, int perPage) { PaginationResult feedbackResult = dalFacade.getFeedbackByProject(projectId, pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_43, projectId, Activity.DataType.FEEDBACK, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(feedbackResult.toJSON()); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java index 5c83514b..3e2c2e6d 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java @@ -132,19 +132,7 @@ public Response getProjects( bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, 0, Activity.DataType.PROJECT, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); - if (search != null) { - parameter.put("search", new ArrayList() {{ - add(String.valueOf(search)); - }}); - } - parameter.put("sort", sort); + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(projectsResult.toJSON()); @@ -651,13 +639,7 @@ public Response getFollowersForProject(@PathParam("projectId") int projectId, bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_12, projectId, Activity.DataType.PROJECT, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(projectFollowers.toJSON()); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java index 9052c005..9f1b5342 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java @@ -104,18 +104,7 @@ public Response searchUser(@ApiParam(value = "Search filter", required = false) bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_53, internalUserId, Activity.DataType.USER, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); - if (search != null) { - parameter.put("search", new ArrayList() {{ - add(String.valueOf(search)); - }}); - } + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(users.toJSON()); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java index 231f1771..0eb4c577 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java @@ -6,13 +6,14 @@ import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.jetbrains.annotations.NotNull; -import java.util.EnumSet; +import java.util.*; public class ResourceHelper { private final BazaarService bazaarService; - public ResourceHelper(BazaarService service){ + public ResourceHelper(BazaarService service) { this.bazaarService = service; } @@ -22,4 +23,27 @@ public void checkRegistrarErrors() throws BazaarException { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } } -} + + @NotNull + public Map> getSortResponseMap(int page, int perPage, String search, List sort) { + Map> parameter = new HashMap<>(); + + ArrayList pageList = new ArrayList<>(); + pageList.add(String.valueOf(page)); + ArrayList perPageList = new ArrayList<>(); + perPageList.add(String.valueOf(perPage)); + + parameter.put("page", pageList); + parameter.put("per_page", perPageList); + if (search != "") { + ArrayList searchList = new ArrayList<>(); + searchList.add(search); + parameter.put("search", searchList); + } + + if (sort != null) { + parameter.put("sort", sort); + } + return parameter; + } +} \ No newline at end of file From 150acac182fdccd4a4ac5cbf6cbd29a297eb6cb8 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 10 Jan 2023 13:58:56 +0100 Subject: [PATCH 07/42] Refactor: remove duplicated code --- .../service/resources/CategoryResource.java | 123 +--- .../resources/RequirementsResource.java | 567 ++++-------------- .../resources/helpers/ResourceHelper.java | 66 +- 3 files changed, 192 insertions(+), 564 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java index 79111ed2..8658d95d 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java @@ -80,13 +80,10 @@ public CategoryResource() throws Exception { public Response getCategoriesForProject(int projectId, int page, int perPage, String search, List sort, String sortDirection) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); - List sortList = getSortFieldList(sort, sortDirection); + String userId = resourceHelper.getUserId(); + List sortList = resourceHelper.getSortFieldList(sort, sortDirection); PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), sortList, search); - // Take Object for generic error handling - checkViolations(pageInfo); + resourceHelper.checkViolations(pageInfo); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = getInternalUserId(projectId, dalFacade, userId); PaginationResult categoriesResult = dalFacade.listCategoriesByProjectId(projectId, pageInfo, internalUserId); @@ -126,42 +123,19 @@ private Response.ResponseBuilder buildCategoryForProjectResponse(int projectId, } @NotNull - private static Integer getInternalUserId(int projectId, DALFacade dalFacade, String userId) throws Exception { + public Integer getInternalUserId(int projectId, DALFacade dalFacade, String userId) throws Exception { Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); if (dalFacade.getProjectById(projectId, internalUserId) == null) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "category")); } if (dalFacade.isProjectPublic(projectId)) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, projectId, dalFacade), "error.authorization.anonymous"); } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, projectId, dalFacade), "error.authorization.category.read"); } return internalUserId; } - private void checkViolations(PageInfo pageInfo) throws BazaarException { - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } - } - - @NotNull - private static List getSortFieldList(List sort, String sortDirection) { - List sortList = new ArrayList<>(); - for (String sortOption : sort) { - Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); - sortList.add(sortField); - } - return sortList; - } - /** * This method allows to retrieve a certain category. * @@ -181,24 +155,16 @@ private static List getSortFieldList(List sort, Stri public Response getCategory(@PathParam("categoryId") int categoryId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category categoryToReturn = dalFacade.getCategoryById(categoryId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_15, categoryId, Activity.DataType.CATEGORY, internalUserId); if (dalFacade.isCategoryPublic(categoryId)) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, categoryToReturn.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, categoryToReturn.getProjectId(), dalFacade), "error.authorization.anonymous"); } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, categoryToReturn.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, categoryToReturn.getProjectId(), dalFacade), "error.authorization.category.read"); } return Response.ok(categoryToReturn.toJSON()).build(); } catch (BazaarException bex) { @@ -240,23 +206,12 @@ public Response getCategory(@PathParam("categoryId") int categoryId) { public Response createCategory(@ApiParam(value = "Category entity", required = true) Category categoryToCreate) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - // TODO: check whether the current user may create a new project - // TODO: check whether all required parameters are entered - resourceHelper.checkRegistrarErrors(); - // Take Object for generic error handling - Set> violations = bazaarService.validateCreate(categoryToCreate); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + String userId = resourceHelper.getUserId(); + resourceHelper.handleGenericError(bazaarService.validateCreate(categoryToCreate)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_CATEGORY, categoryToCreate.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_CATEGORY, categoryToCreate.getProjectId(), dalFacade), "error.authorization.category.create"); categoryToCreate.setCreator(dalFacade.getUserById(internalUserId)); Category createdCategory = dalFacade.createCategory(categoryToCreate, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(createdCategory.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_16, @@ -304,21 +259,14 @@ public Response updateCategory(@ApiParam(value = "Category entity", required = t resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - // Take Object for generic error handling - Set> violations = bazaarService.validate(categoryToUpdate); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(categoryToUpdate)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - // Prevent forged project ids + // Prevent forget project ids Category internalCategory = dalFacade.getCategoryById(categoryToUpdate.getId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_CATEGORY, internalCategory.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.modify")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_CATEGORY, internalCategory.getProjectId(), dalFacade), "error.authorization.category.modify"); Category updatedCategory = dalFacade.modifyCategory(categoryToUpdate); bazaarService.getNotificationDispatcher().dispatchNotification(updatedCategory.getLastUpdatedDate(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_17, @@ -363,17 +311,12 @@ public Response updateCategory(@ApiParam(value = "Category entity", required = t public Response deleteCategory(@PathParam("categoryId") int categoryId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category categoryToDelete = dalFacade.getCategoryById(categoryId, internalUserId); Project project = dalFacade.getProjectById(categoryToDelete.getProjectId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_CATEGORY, project.getId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.modify")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_CATEGORY, project.getId(), dalFacade), "error.authorization.category.modify"); if (project.getDefaultCategoryId() != null && project.getDefaultCategoryId() == categoryId) { ExceptionHandler.getInstance().convertAndThrowException( new Exception(), @@ -425,15 +368,10 @@ public Response deleteCategory(@PathParam("categoryId") int categoryId) { public Response followCategory(@PathParam("categoryId") int categoryId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade), "error.authorization.follow.create"); dalFacade.followCategory(internalUserId, categoryId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_19, @@ -478,15 +416,10 @@ public Response followCategory(@PathParam("categoryId") int categoryId) { public Response unfollowCategory(@PathParam("categoryId") int categoryId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.delete")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade), "error.authorization.follow.delete"); dalFacade.unFollowCategory(internalUserId, categoryId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_20, @@ -540,7 +473,6 @@ public Response getStatisticsForCategory( Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Category category = dalFacade.getCategoryById(categoryId, internalUserId); Statistic categoryStatistics = dalFacade.getStatisticsForCategory(internalUserId, categoryId, sinceCal); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_21, categoryId, Activity.DataType.CATEGORY, internalUserId); @@ -584,12 +516,9 @@ public Response getStatisticsForCategory( public Response getContributorsForCategory(@PathParam("categoryId") int categoryId) throws Exception { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Category category = dalFacade.getCategoryById(categoryId, internalUserId); CategoryContributors categoryContributors = dalFacade.listContributorsForCategory(categoryId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_22, categoryId, Activity.DataType.CATEGORY, internalUserId); @@ -637,16 +566,12 @@ public Response getFollowersForCategory(@PathParam("categoryId") int categoryId, @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) throws Exception { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); PageInfo pageInfo = new PageInfo(page, perPage); - // Take Object for generic error handling - checkViolations(pageInfo); + resourceHelper.checkViolations(pageInfo); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Category category = dalFacade.getCategoryById(categoryId, internalUserId); PaginationResult categoryFollowers = dalFacade.listFollowersForCategory(categoryId, pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_23, categoryId, Activity.DataType.CATEGORY, internalUserId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index 817098c2..ff5dfc50 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -23,6 +23,7 @@ import io.swagger.annotations.*; import lombok.AllArgsConstructor; import lombok.Getter; +import org.jetbrains.annotations.NotNull; import javax.validation.ConstraintViolation; import javax.ws.rs.*; @@ -98,26 +99,15 @@ public Response getRequirements( resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - List sortList = new ArrayList<>(); - for (String sortOption : sort) { - Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); - sortList.add(sortField); - } + List sortList = resourceHelper.getSortFieldList(sort, sortDirection); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - HashMap filterMap = new HashMap<>(); - for (String filterOption : filters) { - filterMap.put(filterOption, internalUserId.toString()); - } + HashMap filterMap = resourceHelper.getFilterMap(filters, internalUserId); PageInfo pageInfo = new PageInfo(page, perPage, filterMap, sortList, search, null, embedParents); - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); PaginationResult requirementsResult = null; @@ -131,19 +121,7 @@ public Response getRequirements( //bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, // 0, Activity.DataType.REQUIREMENT, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); - if (search != null) { - parameter.put("search", new ArrayList() {{ - add(String.valueOf(search)); - }}); - } - parameter.put("sort", sort); + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementsResult.toJSON()); @@ -152,26 +130,14 @@ public Response getRequirements( return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get all requirements"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Get all requirements"); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get all requirements"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get all requirements",logger); } finally { bazaarService.closeDBConnection(dalFacade); } } - /** * This method returns the list of requirements for a specific project. * @@ -186,24 +152,14 @@ public Response getRequirements( public Response getRequirementsForProject(int projectId, int page, int perPage, String search, String stateFilter, List sort, String sortDirection) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); HashMap filters = new HashMap<>(); if (!Objects.equals(stateFilter, "all")) { filters.put("realized", stateFilter); } - List sortList = new ArrayList<>(); - for (String sortOption : sort) { - Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); - sortList.add(sortField); - } + List sortList = resourceHelper.getSortFieldList(sort, sortDirection); PageInfo pageInfo = new PageInfo(page, perPage, filters, sortList, search); - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -225,22 +181,10 @@ public Response getRequirementsForProject(int projectId, int page, int perPage, bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_14, projectId, Activity.DataType.PROJECT, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); - if (search != null) { - parameter.put("search", new ArrayList() {{ - add(String.valueOf(search)); - }}); - } + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); parameter.put("state", new ArrayList() {{ add(String.valueOf(stateFilter)); }}); - parameter.put("sort", sort); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementsResult.toJSON()); @@ -249,25 +193,26 @@ public Response getRequirementsForProject(int projectId, int page, int perPage, return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get requirements for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Get requirements for project " + projectId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get requirements for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get requirements for project " + projectId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + private Response handleBazaarException(BazaarException bex, String projectId) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, projectId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } + /** * This method returns the list of requirements for a specific category. * @@ -290,17 +235,9 @@ public Response getRequirementsForCategory(int categoryId, int page, int perPage if (!Objects.equals(stateFilter, "all")) { filters.put("realized", stateFilter); } - List sortList = new ArrayList<>(); - for (String sortOption : sort) { - Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); - sortList.add(sortField); - } + List sortList = resourceHelper.getSortFieldList(sort, sortDirection); PageInfo pageInfo = new PageInfo(page, perPage, filters, sortList, search); - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -324,22 +261,10 @@ public Response getRequirementsForCategory(int categoryId, int page, int perPage bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_24, categoryId, Activity.DataType.CATEGORY, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); - if (search != null) { - parameter.put("search", new ArrayList() {{ - add(String.valueOf(search)); - }}); - } + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); parameter.put("state", new ArrayList() {{ add(String.valueOf(stateFilter)); }}); - parameter.put("sort", sort); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementsResult.toJSON()); @@ -348,20 +273,9 @@ public Response getRequirementsForCategory(int categoryId, int page, int perPage return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get requirements for category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Get requirements for category " + categoryId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get requirements for category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get requirements for category " + categoryId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -408,20 +322,9 @@ public Response getRequirement(@PathParam("requirementId") int requirementId) { } return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Get requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -462,19 +365,10 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir requirementToCreate.setCreator(dalFacade.getUserById(internalUserId)); requirementToCreate.setLastUpdatingUser(requirementToCreate.getCreator()); requirementToCreate.setLastUpdatedDate(OffsetDateTime.now()); - // Take Object for generic error handling - Set> violations = bazaarService.validateCreate(requirementToCreate); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validateCreate(requirementToCreate)); + Set> violations; - // check if all categories are in the same project - for (Integer catId : requirementToCreate.getCategories()) { - Category category = dalFacade.getCategoryById(catId, internalUserId); - if (requirementToCreate.getProjectId() != category.getProjectId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.VALIDATION, "Category does not fit with project"); - } - } + isCategorySameProject(requirementToCreate, dalFacade, internalUserId); List validatedTags = new ArrayList<>(); for (Tag tag : requirementToCreate.getTags()) { @@ -497,10 +391,7 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir attachment.setCreator(dalFacade.getUserById(internalUserId)); attachment.setRequirementId(createdRequirement.getId()); // Take Object for generic error handling - violations = bazaarService.validate(attachment); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(attachment)); dalFacade.createAttachment(attachment); } @@ -518,15 +409,21 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create requirement"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Create requirement",logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + private static void isCategorySameProject(Requirement requirementToCreate, DALFacade dalFacade, Integer internalUserId) throws Exception { + for (Integer catId : requirementToCreate.getCategories()) { + Category category = dalFacade.getCategoryById(catId, internalUserId); + if (requirementToCreate.getProjectId() != category.getProjectId()) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.VALIDATION, "Category does not fit with project"); + } + } + } + /** * This method updates a specific requirement within a project and category. * @@ -549,11 +446,7 @@ public Response updateRequirement(@ApiParam(value = "Requirement entity", requir resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - // Take Object for generic error handling - Set> violations = bazaarService.validate(requirementToUpdate); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(requirementToUpdate)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -572,20 +465,9 @@ public Response updateRequirement(@ApiParam(value = "Requirement entity", requir updatedRequirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(updatedRequirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update requirement " + requirementToUpdate.getId()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Update requirement " + requirementToUpdate.getId()); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update requirement " + requirementToUpdate.getId()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Update requirement " + requirementToUpdate.getId(),logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -610,9 +492,7 @@ public Response updateRequirement(@ApiParam(value = "Requirement entity", requir public Response deleteRequirement(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirementToDelete = dalFacade.getRequirementById(requirementId, internalUserId); @@ -626,15 +506,7 @@ public Response deleteRequirement(@PathParam("requirementId") int requirementId) requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(deletedRequirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Delete requirement " + requirementId); } catch (Exception ex) { BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete requirement " + requirementId); @@ -684,9 +556,7 @@ private boolean isUserAuthorizedToDeleteRequirement(DALFacade dalFacade, Integer public Response leaddevelopRequirement(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); @@ -698,20 +568,9 @@ public Response leaddevelopRequirement(@PathParam("requirementId") int requireme requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Leaddevelop requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Leaddevelop requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Leaddevelop requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Leaddevelop requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -736,9 +595,7 @@ public Response leaddevelopRequirement(@PathParam("requirementId") int requireme public Response unleaddevelopRequirement(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); @@ -754,20 +611,9 @@ public Response unleaddevelopRequirement(@PathParam("requirementId") int require requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unleaddevelop requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Unleaddevelop requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unleaddevelop requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Unleaddevelop requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -792,9 +638,7 @@ public Response unleaddevelopRequirement(@PathParam("requirementId") int require public Response developRequirement(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); @@ -811,20 +655,9 @@ public Response developRequirement(@PathParam("requirementId") int requirementId requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Develop requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Develop requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Develop requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Develop requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -867,20 +700,9 @@ public Response undevelopRequirement(@PathParam("requirementId") int requirement requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Undevelop requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Undevelop requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Undevelop requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Undevelop requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -936,20 +758,9 @@ public Response moveRequirement(@PathParam("requirementId") int requirementId, N requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Move requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Move requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Move requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Move requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -980,9 +791,7 @@ public static class NewRequirementLocation { public Response followRequirement(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); @@ -995,20 +804,9 @@ public Response followRequirement(@PathParam("requirementId") int requirementId) requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Follow requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Follow requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Follow requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Follow requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1033,9 +831,7 @@ public Response followRequirement(@PathParam("requirementId") int requirementId) public Response unfollowRequirement(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); @@ -1048,20 +844,9 @@ public Response unfollowRequirement(@PathParam("requirementId") int requirementI requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unfollow requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Unfollow requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unfollow requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Unfollow requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1088,9 +873,7 @@ public Response vote(@PathParam("requirementId") int requirementId, @ApiParam(value = "Vote direction", required = true) Direction direction) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -1106,20 +889,9 @@ public Response vote(@PathParam("requirementId") int requirementId, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.SEE_OTHER).location(URI.create(bazaarService.getBaseURL() + "requirements/" + requirementId)).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unfollow requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Unfollow requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unfollow requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Unfollow requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1144,9 +916,7 @@ public Response vote(@PathParam("requirementId") int requirementId, public Response unvote(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_VOTE, dalFacade); @@ -1156,20 +926,9 @@ public Response unvote(@PathParam("requirementId") int requirementId) { dalFacade.unVote(internalUserId, requirementId); return Response.noContent().build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unvote requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Unvote requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unvote requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Unvote requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1194,9 +953,7 @@ public Response unvote(@PathParam("requirementId") int requirementId) { public Response realize(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); @@ -1209,20 +966,9 @@ public Response realize(@PathParam("requirementId") int requirementId) { requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Realize requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Realize requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Realize requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Realize requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1247,9 +993,7 @@ public Response realize(@PathParam("requirementId") int requirementId) { public Response unrealize(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -1265,20 +1009,9 @@ public Response unrealize(@PathParam("requirementId") int requirementId) { requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unrealize requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Unrealize requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unrealize requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Unrealize requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1306,9 +1039,7 @@ public Response getStatisticsForRequirement( @ApiParam(value = "Since timestamp, ISO-8601 e.g. 2017-12-30 or 2017-12-30T18:30:00Z", required = false) @QueryParam("since") String since) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); @@ -1317,20 +1048,9 @@ public Response getStatisticsForRequirement( requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirementStatistics.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get statistics for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Get statistics for requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get statistics for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get statistics for requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1359,15 +1079,9 @@ public Response getDevelopersForRequirement(@PathParam("requirementId") int requ @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) throws Exception { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); PageInfo pageInfo = new PageInfo(page, perPage); - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -1375,13 +1089,7 @@ public Response getDevelopersForRequirement(@PathParam("requirementId") int requ bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_40, requirementId, Activity.DataType.REQUIREMENT, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementDevelopers.toJSON()); @@ -1390,20 +1098,9 @@ public Response getDevelopersForRequirement(@PathParam("requirementId") int requ return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get developers for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Get developers for requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get developers for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get developers for requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1428,9 +1125,7 @@ public Response getDevelopersForRequirement(@PathParam("requirementId") int requ public Response getContributorsForRequirement(@PathParam("requirementId") int requirementId) throws Exception { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); RequirementContributors requirementContributors = dalFacade.listContributorsForRequirement(requirementId); @@ -1438,20 +1133,9 @@ public Response getContributorsForRequirement(@PathParam("requirementId") int re requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirementContributors.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get contributors for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Get contributors for requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get contributors for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get contributors for requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1480,15 +1164,9 @@ public Response getFollowersForRequirement(@PathParam("requirementId") int requi @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) throws Exception { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); PageInfo pageInfo = new PageInfo(page, perPage); - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -1496,13 +1174,7 @@ public Response getFollowersForRequirement(@PathParam("requirementId") int requi bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_42, requirementId, Activity.DataType.REQUIREMENT, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementFollowers.toJSON()); @@ -1511,20 +1183,9 @@ public Response getFollowersForRequirement(@PathParam("requirementId") int requi return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Get followers for requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get followers for requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1574,14 +1235,9 @@ public Response getAttachmentsForRequirement(@PathParam("requirementId") int req @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); PageInfo pageInfo = new PageInfo(page, perPage); - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); //Todo use requirement's projectId for security context, not the one sent from client @@ -1603,13 +1259,7 @@ public Response getAttachmentsForRequirement(@PathParam("requirementId") int req } PaginationResult attachmentsResult = dalFacade.listAttachmentsByRequirementId(requirementId, pageInfo); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); + Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(attachmentsResult.toJSON()); @@ -1618,20 +1268,9 @@ public Response getAttachmentsForRequirement(@PathParam("requirementId") int req return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get attachments for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return handleBazaarException(bex, "Get attachments for requirement " + requirementId); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get attachments for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get attachments for requirement " + requirementId,logger); } finally { bazaarService.closeDBConnection(dalFacade); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java index 0eb4c577..c6f06c2c 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java @@ -2,12 +2,21 @@ import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import i5.las2peer.api.Context; +import i5.las2peer.api.logging.MonitoringEvent; +import i5.las2peer.api.security.Agent; +import i5.las2peer.logging.L2pLogger; import org.jetbrains.annotations.NotNull; +import javax.validation.ConstraintViolation; +import javax.ws.rs.core.Response; import java.util.*; public class ResourceHelper { @@ -35,7 +44,7 @@ public Map> getSortResponseMap(int page, int perPage, Strin parameter.put("page", pageList); parameter.put("per_page", perPageList); - if (search != "") { + if (search != null) { ArrayList searchList = new ArrayList<>(); searchList.add(search); parameter.put("search", searchList); @@ -46,4 +55,59 @@ public Map> getSortResponseMap(int page, int perPage, Strin } return parameter; } + + @NotNull + public List getSortFieldList(List sort, String sortDirection) { + List sortList = new ArrayList<>(); + for (String sortOption : sort) { + Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); + sortList.add(sortField); + } + return sortList; + } + + public void handleGenericError(Set> bazaarService) throws BazaarException { + Set> violations = bazaarService; + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + } + + public void checkViolations(PageInfo pageInfo) throws BazaarException { + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + } + + public void checkAuthorization(boolean internalUserId, String key) throws BazaarException { + boolean authorized = internalUserId; + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString(key)); + } + } + + public String getUserId() throws BazaarException { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + checkRegistrarErrors(); + return userId; + } + + @NotNull + public HashMap getFilterMap(List filters, Integer internalUserId) { + HashMap filterMap = new HashMap<>(); + for (String filterOption : filters) { + filterMap.put(filterOption, internalUserId.toString()); + } + return filterMap; + } + + public Response handleException(Exception ex, String key, L2pLogger logger) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, key); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } \ No newline at end of file From 1289eb928a21fb8c5ad8b4ce8bda23fb4dfe1aa6 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 11 Jan 2023 09:48:11 +0100 Subject: [PATCH 08/42] Refactor: reduce complexity of RequirementsResource --- .../service/resources/CategoryResource.java | 5 +- .../resources/RequirementsResource.java | 423 +++++++----------- .../resources/helpers/ResourceHelper.java | 21 +- 3 files changed, 182 insertions(+), 267 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java index 8658d95d..f6aa6260 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java @@ -105,10 +105,7 @@ public Response getCategoriesForProject(int projectId, int page, int perPage, St return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get categories for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex,"Get categories for project ",logger); } finally { bazaarService.closeDBConnection(dalFacade); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index ff5dfc50..7fa6cccd 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -1,6 +1,5 @@ package de.rwth.dbis.acis.bazaar.service.resources; -import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.Tag; @@ -21,11 +20,10 @@ import i5.las2peer.api.security.AnonymousAgent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; -import lombok.AllArgsConstructor; import lombok.Getter; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -96,9 +94,8 @@ public Response getRequirements( DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); List sortList = resourceHelper.getSortFieldList(sort, sortDirection); dalFacade = bazaarService.getDBConnection(); @@ -121,7 +118,7 @@ public Response getRequirements( //bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, // 0, Activity.DataType.REQUIREMENT, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, search, sort); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementsResult.toJSON()); @@ -130,9 +127,9 @@ public Response getRequirements( return responseBuilder.build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Get all requirements"); + return resourceHelper.handleBazaarException(bex, "Get all requirements", logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Get all requirements",logger); + return resourceHelper.handleException(ex, "Get all requirements", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -153,38 +150,20 @@ public Response getRequirementsForProject(int projectId, int page, int perPage, DALFacade dalFacade = null; try { String userId = resourceHelper.getUserId(); - HashMap filters = new HashMap<>(); - if (!Objects.equals(stateFilter, "all")) { - filters.put("realized", stateFilter); - } + HashMap filters = buildFilters(stateFilter); List sortList = resourceHelper.getSortFieldList(sort, sortDirection); PageInfo pageInfo = new PageInfo(page, perPage, filters, sortList, search); resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - if (dalFacade.getProjectById(projectId, internalUserId) == null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "resource")); - } - if (dalFacade.isProjectPublic(projectId)) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_REQUIREMENT, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); - } - } + ensureCatIsInProject(dalFacade.getProjectById(projectId, internalUserId) == null, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "resource")); + isPublicCheck(dalFacade.isProjectPublic(projectId), internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, projectId, dalFacade, PrivilegeEnum.Read_REQUIREMENT, "error.authorization.category.read"); PaginationResult requirementsResult = dalFacade.listRequirementsByProject(projectId, pageInfo, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_14, projectId, Activity.DataType.PROJECT, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); - parameter.put("state", new ArrayList() {{ - add(String.valueOf(stateFilter)); - }}); + Map> parameter = getParameters(page, perPage, search, stateFilter, sort); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementsResult.toJSON()); @@ -193,26 +172,14 @@ public Response getRequirementsForProject(int projectId, int page, int perPage, return responseBuilder.build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Get requirements for project " + projectId); + return resourceHelper.handleBazaarException(bex, "Get requirements for project " + projectId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Get requirements for project " + projectId,logger); + return resourceHelper.handleException(ex, "Get requirements for project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } } - private Response handleBazaarException(BazaarException bex, String projectId) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } - } - /** * This method returns the list of requirements for a specific category. * @@ -228,43 +195,23 @@ private Response handleBazaarException(BazaarException bex, String projectId) { public Response getRequirementsForCategory(int categoryId, int page, int perPage, String search, String stateFilter, List sort, String sortDirection) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); - HashMap filters = new HashMap<>(); - if (!Objects.equals(stateFilter, "all")) { - filters.put("realized", stateFilter); - } + String userId = resourceHelper.getUserId(); + HashMap filters = buildFilters(stateFilter); List sortList = resourceHelper.getSortFieldList(sort, sortDirection); PageInfo pageInfo = new PageInfo(page, perPage, filters, sortList, search); resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - if (dalFacade.getCategoryById(categoryId, internalUserId) == null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "category")); - } + ensureCatIsInProject(dalFacade.getCategoryById(categoryId, internalUserId) == null, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "category")); Category category = dalFacade.getCategoryById(categoryId, internalUserId); Project project = dalFacade.getProjectById(category.getProjectId(), internalUserId); - if (dalFacade.isCategoryPublic(categoryId)) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, project.getId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_REQUIREMENT, project.getId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); - } - } + isPublicCheck(dalFacade.isCategoryPublic(categoryId), internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, project.getId(), dalFacade, PrivilegeEnum.Read_REQUIREMENT, "error.authorization.category.read"); PaginationResult requirementsResult = dalFacade.listRequirementsByCategory(categoryId, pageInfo, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_24, categoryId, Activity.DataType.CATEGORY, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); - parameter.put("state", new ArrayList() {{ - add(String.valueOf(stateFilter)); - }}); + Map> parameter = getParameters(page, perPage, search, stateFilter, sort); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementsResult.toJSON()); @@ -273,14 +220,32 @@ public Response getRequirementsForCategory(int categoryId, int page, int perPage return responseBuilder.build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Get requirements for category " + categoryId); + return resourceHelper.handleBazaarException(bex, "Get requirements for category " + categoryId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Get requirements for category " + categoryId,logger); + return resourceHelper.handleException(ex, "Get requirements for category " + categoryId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + @NotNull + private Map> getParameters(int page, int perPage, String search, String stateFilter, List sort) { + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, search, sort); + parameter.put("state", new ArrayList() {{ + add(String.valueOf(stateFilter)); + }}); + return parameter; + } + + @NotNull + private static HashMap buildFilters(String stateFilter) { + HashMap filters = new HashMap<>(); + if (!Objects.equals(stateFilter, "all")) { + filters.put("realized", stateFilter); + } + return filters; + } + /** * This method returns a specific requirement. @@ -301,30 +266,18 @@ public Response getRequirementsForCategory(int categoryId, int page, int perPage public Response getRequirement(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_25, requirementId, Activity.DataType.REQUIREMENT, internalUserId); - if (dalFacade.isRequirementPublic(requirementId)) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_REQUIREMENT, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); - } - } + isPublicCheck(dalFacade.isRequirementPublic(requirementId), internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, requirement.getProjectId(), dalFacade, PrivilegeEnum.Read_REQUIREMENT, "error.authorization.category.read"); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Get requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Get requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Get requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Get requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -349,78 +302,69 @@ public Response getRequirement(@PathParam("requirementId") int requirementId) { public Response createRequirement(@ApiParam(value = "Requirement entity", required = true) Requirement requirementToCreate) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); resourceHelper.checkRegistrarErrors(); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_REQUIREMENT, requirementToCreate.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_REQUIREMENT, requirementToCreate.getProjectId(), dalFacade), "error.authorization.requirement.create"); // TODO Refactor this! Such logic should be moved to the constructor requirementToCreate.setCreator(dalFacade.getUserById(internalUserId)); requirementToCreate.setLastUpdatingUser(requirementToCreate.getCreator()); requirementToCreate.setLastUpdatedDate(OffsetDateTime.now()); resourceHelper.handleGenericError(bazaarService.validateCreate(requirementToCreate)); - Set> violations; isCategorySameProject(requirementToCreate, dalFacade, internalUserId); - List validatedTags = new ArrayList<>(); - for (Tag tag : requirementToCreate.getTags()) { - Tag internalTag = dalFacade.getTagById(tag.getId()); - if (internalTag == null) { - tag.setProjectId(requirementToCreate.getProjectId()); - internalTag = dalFacade.createTag(tag); - } else if (requirementToCreate.getProjectId() != tag.getProjectId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.VALIDATION, "Tag does not fit with project"); - } - validatedTags.add(internalTag); - } - requirementToCreate.setTags(validatedTags); + setTagsForRequirement(requirementToCreate, dalFacade); Requirement createdRequirement = dalFacade.createRequirement(requirementToCreate, internalUserId); - // check if attachments are given - if (requirementToCreate.getAttachments() != null && !requirementToCreate.getAttachments().isEmpty()) { - for (Attachment attachment : requirementToCreate.getAttachments()) { - attachment.setCreator(dalFacade.getUserById(internalUserId)); - attachment.setRequirementId(createdRequirement.getId()); - // Take Object for generic error handling - resourceHelper.handleGenericError(bazaarService.validate(attachment)); - - dalFacade.createAttachment(attachment); - } - } + buildAttachments(requirementToCreate, dalFacade, internalUserId, createdRequirement); createdRequirement = dalFacade.getRequirementById(createdRequirement.getId(), internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_26, createdRequirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(createdRequirement.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create requirement"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Create requirement", logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Create requirement",logger); + return resourceHelper.handleException(ex, "Create requirement", logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + private void buildAttachments(Requirement requirementToCreate, DALFacade dalFacade, Integer internalUserId, Requirement createdRequirement) throws Exception { + if (requirementToCreate.getAttachments() != null && !requirementToCreate.getAttachments().isEmpty()) { + for (Attachment attachment : requirementToCreate.getAttachments()) { + attachment.setCreator(dalFacade.getUserById(internalUserId)); + attachment.setRequirementId(createdRequirement.getId()); + resourceHelper.handleGenericError(bazaarService.validate(attachment)); + dalFacade.createAttachment(attachment); + } + } + } + + private static void setTagsForRequirement(Requirement requirementToCreate, DALFacade dalFacade) throws Exception { + List validatedTags = new ArrayList<>(); + for (Tag tag : requirementToCreate.getTags()) { + Tag internalTag = dalFacade.getTagById(tag.getId()); + if (internalTag == null) { + tag.setProjectId(requirementToCreate.getProjectId()); + internalTag = dalFacade.createTag(tag); + } else + ensureCatIsInProject(requirementToCreate.getProjectId() != tag.getProjectId(), ErrorCode.VALIDATION, "Tag does not fit with project"); + validatedTags.add(internalTag); + } + requirementToCreate.setTags(validatedTags); + } + private static void isCategorySameProject(Requirement requirementToCreate, DALFacade dalFacade, Integer internalUserId) throws Exception { for (Integer catId : requirementToCreate.getCategories()) { Category category = dalFacade.getCategoryById(catId, internalUserId); - if (requirementToCreate.getProjectId() != category.getProjectId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.VALIDATION, "Category does not fit with project"); - } + ensureCatIsInProject(requirementToCreate.getProjectId() != category.getProjectId(), ErrorCode.VALIDATION, "Category does not fit with project"); } } @@ -443,9 +387,7 @@ private static void isCategorySameProject(Requirement requirementToCreate, DALFa public Response updateRequirement(@ApiParam(value = "Requirement entity", required = true) Requirement requirementToUpdate) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); resourceHelper.handleGenericError(bazaarService.validate(requirementToUpdate)); dalFacade = bazaarService.getDBConnection(); @@ -454,10 +396,7 @@ public Response updateRequirement(@ApiParam(value = "Requirement entity", requir // Get internal requirement, so a malicious actor can't provide another project id Requirement internalRequirement = dalFacade.getRequirementById(requirementToUpdate.getId(), internalUserId); boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, internalRequirement.getProjectId(), dalFacade); - if (!authorized && !internalRequirement.isOwner(internalUserId)) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.modify")); - } - + ensureCatIsInProject(!authorized && !internalRequirement.isOwner(internalUserId), ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.modify")); dalFacade.followRequirement(internalUserId, requirementToUpdate.getId()); Requirement updatedRequirement = dalFacade.modifyRequirement(requirementToUpdate, internalUserId); @@ -465,9 +404,9 @@ public Response updateRequirement(@ApiParam(value = "Requirement entity", requir updatedRequirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(updatedRequirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Update requirement " + requirementToUpdate.getId()); + return resourceHelper.handleBazaarException(bex, "Update requirement " + requirementToUpdate.getId(), logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Update requirement " + requirementToUpdate.getId(),logger); + return resourceHelper.handleException(ex, "Update requirement " + requirementToUpdate.getId(), logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -497,21 +436,15 @@ public Response deleteRequirement(@PathParam("requirementId") int requirementId) Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirementToDelete = dalFacade.getRequirementById(requirementId, internalUserId); Project project = dalFacade.getProjectById(requirementToDelete.getProjectId(), internalUserId); - boolean authorized = isUserAuthorizedToDeleteRequirement(dalFacade, internalUserId, project, requirementToDelete); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.delete")); - } + resourceHelper.checkAuthorization(isUserAuthorizedToDeleteRequirement(dalFacade, internalUserId, project, requirementToDelete), "error.authorization.requirement.delete"); Requirement deletedRequirement = dalFacade.deleteRequirementById(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_28, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(deletedRequirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Delete requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Delete requirement " + requirementId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete requirement " + requirementId); - logger.warning(bex.getMessage()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Delete requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -520,10 +453,10 @@ public Response deleteRequirement(@PathParam("requirementId") int requirementId) /** * Returns whether the given user is authorized to delete a certain requirement. * - * @param dalFacade facade for database access - * @param userId the user to test authorization for + * @param dalFacade facade for database access + * @param userId the user to test authorization for * @param projectOfRequirement the project of which the requirement is part of - * @param requirement the requirement to delete + * @param requirement the requirement to delete * @return * @throws BazaarException */ @@ -559,18 +492,15 @@ public Response leaddevelopRequirement(@PathParam("requirementId") int requireme String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade), "error.authorization.vote.create"); Requirement requirement = dalFacade.setUserAsLeadDeveloper(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.LEADDEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_29, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Leaddevelop requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Leaddevelop requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Leaddevelop requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Leaddevelop requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -598,22 +528,17 @@ public Response unleaddevelopRequirement(@PathParam("requirementId") int require String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.delete")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade), "error.authorization.vote.delete"); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - if (requirement.getLeadDeveloper().getId() != internalUserId) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, "You are not lead developer."); - } + ensureCatIsInProject(requirement.getLeadDeveloper().getId() != internalUserId, ErrorCode.AUTHORIZATION, "You are not lead developer."); requirement = dalFacade.deleteUserAsLeadDeveloper(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNLEADDEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_30, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Unleaddevelop requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Unleaddevelop requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Unleaddevelop requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Unleaddevelop requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -642,10 +567,7 @@ public Response developRequirement(@PathParam("requirementId") int requirementId dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_DEVELOP, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.develop.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_DEVELOP, requirement.getProjectId(), dalFacade), "error.authorization.develop.create"); dalFacade.wantToDevelop(internalUserId, requirementId); dalFacade.followRequirement(internalUserId, requirementId); @@ -655,9 +577,9 @@ public Response developRequirement(@PathParam("requirementId") int requirementId requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Develop requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Develop requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Develop requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Develop requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -682,16 +604,11 @@ public Response developRequirement(@PathParam("requirementId") int requirementId public Response undevelopRequirement(@PathParam("requirementId") int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Delete_DEVELOP, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.develop.delete")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Delete_DEVELOP, requirement.getProjectId(), dalFacade), "error.authorization.develop.delete"); dalFacade.notWantToDevelop(internalUserId, requirementId); // refresh requirement object @@ -700,9 +617,9 @@ public Response undevelopRequirement(@PathParam("requirementId") int requirement requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Undevelop requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Undevelop requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Undevelop requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Undevelop requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -727,9 +644,7 @@ public Response undevelopRequirement(@PathParam("requirementId") int requirement public Response moveRequirement(@PathParam("requirementId") int requirementId, NewRequirementLocation requirementLocation) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); // ensure requirement exists @@ -738,15 +653,10 @@ public Response moveRequirement(@PathParam("requirementId") int requirementId, N Project targetProject = dalFacade.getProjectById(requirementLocation.getProjectId(), internalUserId); // ensure target category exists Category targetCategory = dalFacade.getCategoryById(requirementLocation.getCategoryId(), internalUserId); - // ensure target category is in target project - if (targetCategory.getProjectId() != targetProject.getId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.VALIDATION, Localization.getInstance().getResourceBundle().getString("error.validation.categoryNotInTargetProject")); - } + ensureCatIsInProject(targetCategory.getProjectId() != targetProject.getId(), ErrorCode.VALIDATION, Localization.getInstance().getResourceBundle().getString("error.validation.categoryNotInTargetProject")); boolean authorizedToModifyRequirement = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, requirement.getProjectId(), dalFacade); boolean authorizedToCreateRequirementInTargetProject = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_REQUIREMENT, targetProject.getId(), dalFacade); - if (!(authorizedToModifyRequirement && authorizedToCreateRequirementInTargetProject)) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.move")); - } + ensureCatIsInProject(isTargetCategory(authorizedToModifyRequirement, authorizedToCreateRequirementInTargetProject), ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.move")); requirement.setProjectId(targetProject.getId()); requirement.setCategories(Arrays.asList(targetCategory.getId())); @@ -758,14 +668,24 @@ public Response moveRequirement(@PathParam("requirementId") int requirementId, N requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Move requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Move requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Move requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Move requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + private static boolean isTargetCategory(boolean authorizedToModifyRequirement, boolean authorizedToCreateRequirementInTargetProject) { + return !(authorizedToModifyRequirement && authorizedToCreateRequirementInTargetProject); + } + + private static void ensureCatIsInProject(boolean targetCategory, ErrorCode validation, String String) throws BazaarException { + if (targetCategory) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, validation, String); + } + } + @Getter public static class NewRequirementLocation { private int projectId; @@ -794,19 +714,16 @@ public Response followRequirement(@PathParam("requirementId") int requirementId) String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade), "error.authorization.follow.create"); dalFacade.followRequirement(internalUserId, requirementId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_33, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Follow requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Follow requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Follow requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Follow requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -834,19 +751,16 @@ public Response unfollowRequirement(@PathParam("requirementId") int requirementI String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.delete")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade), "error.authorization.follow.delete"); dalFacade.unFollowRequirement(internalUserId, requirementId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_34, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Unfollow requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Unfollow requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Unfollow requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Unfollow requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -877,26 +791,27 @@ public Response vote(@PathParam("requirementId") int requirementId, dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_VOTE, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_VOTE, dalFacade), "error.authorization.vote.create"); dalFacade.vote(internalUserId, requirementId, direction.isUpVote()); - if (direction.isUpVote()) { - dalFacade.followRequirement(internalUserId, requirementId); - } + followUpvote(requirementId, direction, dalFacade, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.VOTE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_35, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.SEE_OTHER).location(URI.create(bazaarService.getBaseURL() + "requirements/" + requirementId)).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Unfollow requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Unfollow requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Unfollow requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Unfollow requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + private static void followUpvote(int requirementId, Direction direction, DALFacade dalFacade, Integer internalUserId) throws BazaarException { + if (direction.isUpVote()) { + dalFacade.followRequirement(internalUserId, requirementId); + } + } + /** * This method removes the vote of the given requirement made by the current user. * @@ -919,16 +834,13 @@ public Response unvote(@PathParam("requirementId") int requirementId) { String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_VOTE, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.delete")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_VOTE, dalFacade), "error.authorization.vote.delete"); dalFacade.unVote(internalUserId, requirementId); return Response.noContent().build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Unvote requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Unvote requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Unvote requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Unvote requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -957,18 +869,15 @@ public Response realize(@PathParam("requirementId") int requirementId) { dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.realize")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade), "error.authorization.requirement.realize"); requirement = dalFacade.setRequirementToRealized(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.REALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_37, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Realize requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Realize requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Realize requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Realize requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -996,22 +905,18 @@ public Response unrealize(@PathParam("requirementId") int requirementId) { String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.realize")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade), "error.authorization.requirement.realize"); requirement = dalFacade.setRequirementToUnRealized(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNREALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_38, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Unrealize requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Unrealize requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Unrealize requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Unrealize requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1042,20 +947,25 @@ public Response getStatisticsForRequirement( String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); + Calendar sinceCal = getSinceCal(since); Statistic requirementStatistics = dalFacade.getStatisticsForRequirement(internalUserId, requirementId, sinceCal); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_39, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirementStatistics.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Get statistics for requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Get statistics for requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Get statistics for requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Get statistics for requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + @Nullable + private static Calendar getSinceCal(String since) { + return since == null ? null : DatatypeConverter.parseDateTime(since); + } + /** * This method returns the list of developers for a specific requirement. * @@ -1082,14 +992,12 @@ public Response getDevelopersForRequirement(@PathParam("requirementId") int requ String userId = resourceHelper.getUserId(); PageInfo pageInfo = new PageInfo(page, perPage); resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); - dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); PaginationResult requirementDevelopers = dalFacade.listDevelopersForRequirement(requirementId, pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_40, requirementId, Activity.DataType.REQUIREMENT, internalUserId); - - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, null, null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementDevelopers.toJSON()); @@ -1098,9 +1006,9 @@ public Response getDevelopersForRequirement(@PathParam("requirementId") int requ return responseBuilder.build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Get developers for requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Get developers for requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Get developers for requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Get developers for requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1133,9 +1041,9 @@ public Response getContributorsForRequirement(@PathParam("requirementId") int re requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirementContributors.toJSON()).build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Get contributors for requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Get contributors for requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Get contributors for requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Get contributors for requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1174,7 +1082,7 @@ public Response getFollowersForRequirement(@PathParam("requirementId") int requi bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_42, requirementId, Activity.DataType.REQUIREMENT, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, null, null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(requirementFollowers.toJSON()); @@ -1183,9 +1091,10 @@ public Response getFollowersForRequirement(@PathParam("requirementId") int requi return responseBuilder.build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Get followers for requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Get followers for requirement " + requirementId, logger + ); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Get followers for requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Get followers for requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1246,20 +1155,10 @@ public Response getAttachmentsForRequirement(@PathParam("requirementId") int req Project project = dalFacade.getProjectById(requirement.getProjectId(), internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_44, requirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); - if (dalFacade.isRequirementPublic(requirementId)) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, project.getId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_COMMENT, project.getId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); - } - } + isPublicCheck(dalFacade.isRequirementPublic(requirementId), internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, project.getId(), dalFacade, PrivilegeEnum.Read_COMMENT, "error.authorization.comment.read"); PaginationResult attachmentsResult = dalFacade.listAttachmentsByRequirementId(requirementId, pageInfo); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, null, null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(attachmentsResult.toJSON()); @@ -1268,11 +1167,19 @@ public Response getAttachmentsForRequirement(@PathParam("requirementId") int req return responseBuilder.build(); } catch (BazaarException bex) { - return handleBazaarException(bex, "Get attachments for requirement " + requirementId); + return resourceHelper.handleBazaarException(bex, "Get attachments for requirement " + requirementId, logger); } catch (Exception ex) { - return resourceHelper.handleException(ex, "Get attachments for requirement " + requirementId,logger); + return resourceHelper.handleException(ex, "Get attachments for requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + + private void isPublicCheck(boolean dalFacade, Integer internalUserId, PrivilegeEnum read_PUBLIC_COMMENT, int project, DALFacade dalFacade1, PrivilegeEnum read_COMMENT, String key) throws BazaarException { + if (dalFacade) { + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, read_PUBLIC_COMMENT, project, dalFacade1), "error.authorization.anonymous"); + } else { + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, read_COMMENT, project, dalFacade1), key); + } + } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java index c6f06c2c..e3bdcfe4 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java @@ -66,9 +66,9 @@ public List getSortFieldList(List sort, String sortD return sortList; } - public void handleGenericError(Set> bazaarService) throws BazaarException { - Set> violations = bazaarService; - if (violations.size() > 0) { + public void handleGenericError(Set> violations) throws BazaarException { + Set> violationSet = violations; + if (violationSet.size() > 0) { ExceptionHandler.getInstance().handleViolations(violations); } } @@ -80,8 +80,7 @@ public void checkViolations(PageInfo pageInfo) throws BazaarException { } } - public void checkAuthorization(boolean internalUserId, String key) throws BazaarException { - boolean authorized = internalUserId; + public void checkAuthorization(boolean authorized, String key) throws BazaarException { if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString(key)); } @@ -110,4 +109,16 @@ public Response handleException(Exception ex, String key, L2pLogger logger) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } + public Response handleBazaarException(BazaarException bex, String key, L2pLogger logger) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, key); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } + } \ No newline at end of file From a5014935a2a7444f3abe25d628f29d3b3b2842a2 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 11 Jan 2023 10:13:51 +0100 Subject: [PATCH 09/42] Refactor: reduce complexity of CategoryResource --- .../service/resources/CategoryResource.java | 187 ++++-------------- .../resources/RequirementsResource.java | 12 +- .../resources/helpers/ResourceHelper.java | 8 + 3 files changed, 51 insertions(+), 156 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java index f6aa6260..b6bd2629 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java @@ -1,7 +1,6 @@ package de.rwth.dbis.acis.bazaar.service.resources; import com.fasterxml.jackson.core.JsonProcessingException; -import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; @@ -17,16 +16,13 @@ import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; -import i5.las2peer.api.security.Agent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; import org.jetbrains.annotations.NotNull; -import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.text.MessageFormat; @@ -59,7 +55,7 @@ public class CategoryResource { private final L2pLogger logger = L2pLogger.getInstance(CategoryResource.class.getName()); private final BazaarService bazaarService; - private ResourceHelper resourceHelper; + private final ResourceHelper resourceHelper; public CategoryResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); @@ -95,17 +91,10 @@ public Response getCategoriesForProject(int projectId, int page, int perPage, St return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get categories for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get categories for project ", logger); + } catch (Exception ex) { - return resourceHelper.handleException(ex,"Get categories for project ",logger); + return resourceHelper.handleException(ex, "Get categories for project ", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -165,20 +154,10 @@ public Response getCategory(@PathParam("categoryId") int categoryId) { } return Response.ok(categoryToReturn.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get projects"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get projects ", logger); + } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get projects"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get projects ", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -215,18 +194,9 @@ public Response createCategory(@ApiParam(value = "Category entity", required = t createdCategory.getId(), Activity.DataType.CATEGORY, internalUserId); return Response.status(Response.Status.CREATED).entity(createdCategory.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create category"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Create category ", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create category"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Create category ", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -253,9 +223,7 @@ public Response updateCategory(@ApiParam(value = "Category entity", required = t DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); resourceHelper.handleGenericError(bazaarService.validate(categoryToUpdate)); dalFacade = bazaarService.getDBConnection(); @@ -270,20 +238,10 @@ public Response updateCategory(@ApiParam(value = "Category entity", required = t updatedCategory.getId(), Activity.DataType.CATEGORY, internalUserId); return Response.ok(updatedCategory.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update category " + categoryToUpdate.getId()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Update category " + categoryToUpdate.getId(), logger); + } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update category " + categoryToUpdate.getId()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Update category " + categoryToUpdate.getId(), logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -314,38 +272,32 @@ public Response deleteCategory(@PathParam("categoryId") int categoryId) { Category categoryToDelete = dalFacade.getCategoryById(categoryId, internalUserId); Project project = dalFacade.getProjectById(categoryToDelete.getProjectId(), internalUserId); resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_CATEGORY, project.getId(), dalFacade), "error.authorization.category.modify"); - if (project.getDefaultCategoryId() != null && project.getDefaultCategoryId() == categoryId) { - ExceptionHandler.getInstance().convertAndThrowException( - new Exception(), - ExceptionLocation.BAZAARSERVICE, - ErrorCode.CANNOTDELETE, - MessageFormat.format(Localization.getInstance().getResourceBundle().getString("error.authorization.category.delete"), categoryId) - ); - } + isDefaultCategory(categoryId, project); Category deletedCategory = dalFacade.deleteCategoryById(categoryId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(deletedCategory.getLastUpdatedDate(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_18, deletedCategory.getId(), Activity.DataType.CATEGORY, internalUserId); return Response.ok(deletedCategory.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Delete category " + categoryId, logger); + } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Delete category " + categoryId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + private static void isDefaultCategory(int categoryId, Project project) throws BazaarException { + if (project.getDefaultCategoryId() != null && project.getDefaultCategoryId() == categoryId) { + ExceptionHandler.getInstance().convertAndThrowException( + new Exception(), + ExceptionLocation.BAZAARSERVICE, + ErrorCode.CANNOTDELETE, + MessageFormat.format(Localization.getInstance().getResourceBundle().getString("error.authorization.category.delete"), categoryId) + ); + } + } + /** * This method add the current user to the followers list of a given category. * @@ -375,20 +327,9 @@ public Response followCategory(@PathParam("categoryId") int categoryId) { category.getId(), Activity.DataType.CATEGORY, internalUserId); return Response.status(Response.Status.CREATED).entity(category.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Follow category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Follow category " + categoryId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Follow category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Follow category " + categoryId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -423,20 +364,9 @@ public Response unfollowCategory(@PathParam("categoryId") int categoryId) { category.getId(), Activity.DataType.CATEGORY, internalUserId); return Response.ok(category.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unfollow category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Unfollow category " + categoryId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unfollow category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Unfollow category " + categoryId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -464,10 +394,8 @@ public Response getStatisticsForCategory( @ApiParam(value = "Since timestamp, ISO-8601 e.g. 2017-12-30 or 2017-12-30T18:30:00Z", required = false) @QueryParam("since") String since) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); + String userId = resourceHelper.getUserId(); + Calendar sinceCal = resourceHelper.getSinceCal(since); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Statistic categoryStatistics = dalFacade.getStatisticsForCategory(internalUserId, categoryId, sinceCal); @@ -475,20 +403,9 @@ public Response getStatisticsForCategory( categoryId, Activity.DataType.CATEGORY, internalUserId); return Response.ok(categoryStatistics.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get statistics for category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get statistics for category " + categoryId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get statistics for category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get statistics for category " + categoryId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -521,20 +438,9 @@ public Response getContributorsForCategory(@PathParam("categoryId") int category categoryId, Activity.DataType.CATEGORY, internalUserId); return Response.ok(categoryContributors.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get contributors for category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get contributors for category " + categoryId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get contributors for category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get contributors for category " + categoryId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -572,7 +478,7 @@ public Response getFollowersForCategory(@PathParam("categoryId") int categoryId, PaginationResult categoryFollowers = dalFacade.listFollowersForCategory(categoryId, pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_23, categoryId, Activity.DataType.CATEGORY, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, null, null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(categoryFollowers.toJSON()); @@ -581,20 +487,9 @@ public Response getFollowersForCategory(@PathParam("categoryId") int categoryId, return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get followers for category " + categoryId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for category " + categoryId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get followers for category " + categoryId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index 7fa6cccd..8b31c769 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -22,12 +22,10 @@ import io.swagger.annotations.*; import lombok.Getter; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; import java.net.HttpURLConnection; import java.net.URI; import java.time.OffsetDateTime; @@ -57,8 +55,7 @@ public class RequirementsResource { private final L2pLogger logger = L2pLogger.getInstance(RequirementsResource.class.getName()); private final BazaarService bazaarService; - - private ResourceHelper resourceHelper; + private final ResourceHelper resourceHelper; public RequirementsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); @@ -947,7 +944,7 @@ public Response getStatisticsForRequirement( String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Calendar sinceCal = getSinceCal(since); + Calendar sinceCal = resourceHelper.getSinceCal(since); Statistic requirementStatistics = dalFacade.getStatisticsForRequirement(internalUserId, requirementId, sinceCal); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_39, requirementId, Activity.DataType.REQUIREMENT, internalUserId); @@ -961,11 +958,6 @@ public Response getStatisticsForRequirement( } } - @Nullable - private static Calendar getSinceCal(String since) { - return since == null ? null : DatatypeConverter.parseDateTime(since); - } - /** * This method returns the list of developers for a specific requirement. * diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java index e3bdcfe4..d0690509 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java @@ -14,9 +14,11 @@ import i5.las2peer.api.security.Agent; import i5.las2peer.logging.L2pLogger; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import javax.validation.ConstraintViolation; import javax.ws.rs.core.Response; +import javax.xml.bind.DatatypeConverter; import java.util.*; public class ResourceHelper { @@ -121,4 +123,10 @@ public Response handleBazaarException(BazaarException bex, String key, L2pLogger } } + @Nullable + public Calendar getSinceCal(String since) { + Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); + return sinceCal; + } + } \ No newline at end of file From ccfcd1f71235037c6906dfbbba85b32853820dee Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 11 Jan 2023 12:04:52 +0100 Subject: [PATCH 10/42] Refactor: reduce complexity of all Resources --- .../service/resources/AdminResource.java | 41 +- .../service/resources/CommentsResource.java | 180 ++----- .../service/resources/FeedbackResource.java | 67 +-- .../PersonalisationDataResource.java | 74 +-- .../service/resources/ProjectsResource.java | 471 ++++-------------- .../service/resources/UsersResource.java | 157 ++---- .../service/resources/WebhookResource.java | 25 +- 7 files changed, 216 insertions(+), 799 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java index 41711266..53603b2f 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java @@ -1,22 +1,10 @@ package de.rwth.dbis.acis.bazaar.service.resources; -import java.net.HttpURLConnection; -import java.net.URI; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.SystemRole; @@ -28,13 +16,21 @@ import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import de.rwth.dbis.acis.bazaar.service.twitter.WeeklyNewProjectsTweetTask; import i5.las2peer.api.Context; -import i5.las2peer.api.logging.MonitoringEvent; import i5.las2peer.api.security.Agent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; import lombok.Builder; import lombok.Getter; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.net.HttpURLConnection; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + /** * Parent endpoint for global, administrative operations and queries */ @@ -60,10 +56,10 @@ @Path("/admin") public class AdminResource { - private L2pLogger logger = L2pLogger.getInstance(AdminResource.class.getName()); - private BazaarService bazaarService; + private final L2pLogger logger = L2pLogger.getInstance(AdminResource.class.getName()); + private final BazaarService bazaarService; - private ResourceHelper resourceHelper; + private final ResourceHelper resourceHelper; @javax.ws.rs.core.Context UriInfo uriInfo; @@ -237,17 +233,10 @@ private Response handleAuthenticatedRequest( return handler.handle(dalFacade, internalUserId); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, errorMessage); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, errorMessage, logger); + } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, errorMessage); - logger.warning(bex.getMessage()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, errorMessage, logger); } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java index 792daed9..a2ada824 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java @@ -1,6 +1,5 @@ package de.rwth.dbis.acis.bazaar.service.resources; -import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; @@ -21,13 +20,14 @@ import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; -import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.HttpURLConnection; import java.time.OffsetDateTime; -import java.util.*; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Api(value = "comments", description = "Comments resource") @@ -55,7 +55,7 @@ public class CommentsResource { private final L2pLogger logger = L2pLogger.getInstance(CommentsResource.class.getName()); private final BazaarService bazaarService; - private ResourceHelper resourceHelper; + private final ResourceHelper resourceHelper; public CommentsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); @@ -92,14 +92,9 @@ public Response getAllComments( DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - List sortList = new ArrayList<>(); - for (String sortOption : sort) { - Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); - sortList.add(sortField); - } + String userId = resourceHelper.getUserId(); + List sortList = resourceHelper.getSortFieldList(sort, sortDirection); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -109,12 +104,7 @@ public Response getAllComments( filterMap.put(filterOption, internalUserId.toString()); } PageInfo pageInfo = new PageInfo(page, perPage, filterMap, sortList, search, null, embedParents); - - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); PaginationResult commentResult = null; @@ -129,7 +119,7 @@ public Response getAllComments( //bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, // 0, Activity.DataType.COMMENT, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, search, sort); parameter.put("embedParents", embedParents); parameter.put("sort", sort); parameter.put("filters", filters); @@ -141,20 +131,9 @@ public Response getAllComments( return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get all comments"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get all comments", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get all comments"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get all comments", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -179,17 +158,7 @@ public Response getCommentsForRequirement(int requirementId) { Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); Project project = dalFacade.getProjectById(requirement.getProjectId(), internalUserId); - if (dalFacade.isRequirementPublic(requirementId)) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, project.getId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_COMMENT, project.getId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); - } - } + checkIsPublic(dalFacade.isRequirementPublic(requirementId), internalUserId, project.getId(), dalFacade); List commentsResult = dalFacade.listCommentsByRequirementId(requirementId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_43, requirementId, Activity.DataType.REQUIREMENT, internalUserId); @@ -199,25 +168,22 @@ public Response getCommentsForRequirement(int requirementId) { return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get comments for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get comments for requirement " + requirementId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get comments for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get comments for requirement " + requirementId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + private void checkIsPublic(boolean dalFacade, Integer internalUserId, int project, DALFacade dalFacade1) throws BazaarException { + if (dalFacade) { + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, project, dalFacade1), "error.authorization.anonymous"); + } else { + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_COMMENT, project, dalFacade1), "error.authorization.comment.read"); + } + } + /** * This method allows to retrieve a certain comment. * @@ -237,42 +203,19 @@ public Response getCommentsForRequirement(int requirementId) { public Response getComment(@PathParam("commentId") int commentId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Comment comment = dalFacade.getCommentById(commentId); Requirement requirement = dalFacade.getRequirementById(comment.getRequirementId(), internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_45, commentId, Activity.DataType.COMMENT, internalUserId); - if (dalFacade.isProjectPublic(requirement.getProjectId())) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_COMMENT, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); - } - } + checkIsPublic(dalFacade.isProjectPublic(requirement.getProjectId()), internalUserId, requirement.getProjectId(), dalFacade); return Response.ok(comment.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get comment " + commentId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get comment " + commentId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get comment " + commentId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get comment " + commentId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -306,16 +249,9 @@ public Response createComment(@ApiParam(value = "Comment entity", required = tru dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(commentToCreate.getRequirementId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_COMMENT, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_COMMENT, requirement.getProjectId(), dalFacade), "error.authorization.comment.create"); commentToCreate.setCreator(dalFacade.getUserById(internalUserId)); - // Take Object for generic error handling - Set> violations = bazaarService.validateCreate(commentToCreate); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validateCreate(commentToCreate)); dalFacade.followRequirement(internalUserId, requirement.getId()); Comment createdComment = dalFacade.createComment(commentToCreate); @@ -323,18 +259,9 @@ public Response createComment(@ApiParam(value = "Comment entity", required = tru createdComment.getId(), Activity.DataType.COMMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(createdComment.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create comment"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Create comment", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create comment"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Create comment", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -358,19 +285,13 @@ public Response createComment(@ApiParam(value = "Comment entity", required = tru public Response updateComment(@ApiParam(value = "Comment entity", required = true) Comment commentToUpdate) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Comment internalComment = dalFacade.getCommentById(commentToUpdate.getId()); Requirement requirement = dalFacade.getRequirementById(internalComment.getRequirementId(), internalUserId); - - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade); - if (!authorized && !internalComment.isOwner(internalUserId)) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.modify")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade), "error.authorization.comment.modify"); internalComment.setMessage(commentToUpdate.getMessage()); @@ -380,20 +301,9 @@ public Response updateComment(@ApiParam(value = "Comment entity", required = tru internalComment.getId(), Activity.DataType.COMMENT, internalUserId); return Response.ok(updatedComment.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete comment " + commentToUpdate.getId()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Delete comment", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete comment " + commentToUpdate.getId()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Delete comment", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -419,38 +329,22 @@ public Response deleteComment(@PathParam("commentId") int commentId) { DALFacade dalFacade = null; try { // TODO: check if the user may delete this requirement. - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Comment commentToDelete = dalFacade.getCommentById(commentId); Requirement requirement = dalFacade.getRequirementById(commentToDelete.getRequirementId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.modify")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade), "error.authorization.comment.modify"); Comment deletedComment = dalFacade.deleteCommentById(commentId); bazaarService.getNotificationDispatcher().dispatchNotification(deletedComment.getCreationDate(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_48, deletedComment.getId(), Activity.DataType.COMMENT, internalUserId); return Response.ok(deletedComment.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete comment " + commentId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Delete comment " + commentId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete comment " + commentId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Delete comment " + commentId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java index 9b33f158..8ce1c390 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java @@ -1,6 +1,5 @@ package de.rwth.dbis.acis.bazaar.service.resources; -import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.Activity; @@ -10,19 +9,13 @@ import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; -import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; -import i5.las2peer.api.security.Agent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; -import javax.validation.ConstraintViolation; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; @@ -31,7 +24,8 @@ import javax.ws.rs.core.Response; import java.net.HttpURLConnection; import java.time.OffsetDateTime; -import java.util.*; +import java.util.List; +import java.util.Map; @Api(value = "feedback") @SwaggerDefinition( @@ -58,7 +52,7 @@ public class FeedbackResource { private final L2pLogger logger = L2pLogger.getInstance(CommentsResource.class.getName()); private final BazaarService bazaarService; - private ResourceHelper resourceHelper; + private final ResourceHelper resourceHelper; public FeedbackResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); @@ -76,15 +70,9 @@ public FeedbackResource() throws Exception { public Response getFeedbackForProject(int projectId, int page, int perPage) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); PageInfo pageInfo = new PageInfo(page, perPage); - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); //Todo use requirement's projectId for security context, not the one sent from client @@ -92,15 +80,12 @@ public Response getFeedbackForProject(int projectId, int page, int perPage) { Project project = dalFacade.getProjectById(projectId, internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_FEEDBACK, project.getId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.feedback.read")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_FEEDBACK, project.getId(), dalFacade), "error.authorization.feedback.read"); PaginationResult feedbackResult = dalFacade.getFeedbackByProject(projectId, pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_43, projectId, Activity.DataType.FEEDBACK, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, null, null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(feedbackResult.toJSON()); @@ -109,20 +94,9 @@ public Response getFeedbackForProject(int projectId, int page, int perPage) { return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get feedback for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get feedback for project " + projectId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get feedback for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get feedback for project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -147,30 +121,15 @@ public Response getFeedbackForProject(int projectId, int page, int perPage) { public Response sendFeedback(@ApiParam(value = "Feedback entity", required = true) Feedback givenFeedback) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); - Set> violations = bazaarService.validateCreate(givenFeedback); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } - + resourceHelper.handleGenericError(bazaarService.validateCreate(givenFeedback)); Feedback createdFeedback = dalFacade.createFeedback(givenFeedback); return Response.status(Response.Status.CREATED).entity(createdFeedback.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create feedback"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Create feedback", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create feedback"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Create feedback", logger); } finally { bazaarService.closeDBConnection(dalFacade); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java index 0fde6013..4cc8d2f3 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java @@ -1,30 +1,20 @@ package de.rwth.dbis.acis.bazaar.service.resources; -import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.PersonalisationData; import de.rwth.dbis.acis.bazaar.service.dal.entities.PrivilegeEnum; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; -import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; -import i5.las2peer.api.logging.MonitoringEvent; -import i5.las2peer.api.security.Agent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; -import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.HttpURLConnection; -import java.util.EnumSet; -import java.util.Set; @Api(value = "personalisation", description = "Personalisation Data resource") @@ -50,9 +40,9 @@ public class PersonalisationDataResource { private final L2pLogger logger = L2pLogger.getInstance(PersonalisationDataResource.class.getName()); - private BazaarService bazaarService; + private final BazaarService bazaarService; - private ResourceHelper resourceHelper; + private final ResourceHelper resourceHelper; public PersonalisationDataResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); @@ -60,11 +50,10 @@ public PersonalisationDataResource() throws Exception { } - /** * This method allows to retrieve a certain stored personalisationData value. * - * @param key The plugins identifier + * @param key The plugins identifier * @param version The plugins identifier * @return Response with attachment as a JSON object. */ @@ -81,33 +70,17 @@ public PersonalisationDataResource() throws Exception { public Response getPersonalisationData(@PathParam("key") String key, @PathParam("version") int version) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PERSONALISATION_DATA, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.personalisationData.read")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PERSONALISATION_DATA, dalFacade), "error.authorization.personalisationData.read"); PersonalisationData data = dalFacade.getPersonalisationData(internalUserId, key, version); return Response.ok(data.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NO_CONTENT).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get personalisationData " + key+" version:"+version ); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get personalisationData " + key + " version:" + version, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get personalisationData " + key+" version:"+version ); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get personalisationData " + key + " version:" + version, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -133,42 +106,19 @@ public Response getPersonalisationData(@PathParam("key") String key, @PathParam( public Response setPersonalisationData(@PathParam("key") String key, @PathParam("version") int version, @ApiParam(value = "PersonalisationData as JSON", required = true) PersonalisationData data) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - - resourceHelper.checkRegistrarErrors(); - + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - - - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PERSONALISATION_DATA, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.create")); - } - + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PERSONALISATION_DATA, dalFacade), "error.authorization.comment.create"); PersonalisationData fullData = PersonalisationData.builder().key(key).userId(internalUserId).version(version).value(data.getValue()).build(); - - // Take Object for generic error handling - Set> violations = bazaarService.validateCreate(fullData); - if (violations.size() > 0) ExceptionHandler.getInstance().handleViolations(violations); - + resourceHelper.handleGenericError(bazaarService.validateCreate(fullData)); dalFacade.setPersonalisationData(fullData); return Response.ok(fullData.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Set personalisationData"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Set personalisationData", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Set personalisationData"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Set personalisationData", logger); } finally { bazaarService.closeDBConnection(dalFacade); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java index 3e2c2e6d..a2e8ef0c 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java @@ -1,6 +1,5 @@ package de.rwth.dbis.acis.bazaar.service.resources; -import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.Tag; @@ -21,15 +20,17 @@ import i5.las2peer.api.security.AnonymousAgent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; +import org.jetbrains.annotations.NotNull; -import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; import java.net.HttpURLConnection; import java.time.OffsetDateTime; -import java.util.*; +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @Api(value = "projects", description = "Projects resource") @@ -57,7 +58,7 @@ public class ProjectsResource { private final L2pLogger logger = L2pLogger.getInstance(ProjectsResource.class.getName()); private final BazaarService bazaarService; - private ResourceHelper resourceHelper; + private final ResourceHelper resourceHelper; public ProjectsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); @@ -93,14 +94,9 @@ public Response getProjects( @ApiParam(value = "Also search in projects requirements", required = false) @DefaultValue("false") @QueryParam("recursive") boolean recursive) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - List sortList = new ArrayList<>(); - for (String sortOption : sort) { - Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); - sortList.add(sortField); - } + String userId = resourceHelper.getUserId(); + List sortList = resourceHelper.getSortFieldList(sort, sortDirection); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -114,12 +110,7 @@ public Response getProjects( options.put("recursive", recursive); PageInfo pageInfo = new PageInfo(page, perPage, filterMap, sortList, search, ids, null, options); - - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); PaginationResult projectsResult; if (agent instanceof AnonymousAgent) { @@ -132,7 +123,7 @@ public Response getProjects( bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, 0, Activity.DataType.PROJECT, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,sort); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, search, sort); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(projectsResult.toJSON()); @@ -145,10 +136,7 @@ public Response getProjects( Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get projects failed"); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get projects failed"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get projects failed", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -173,53 +161,44 @@ public Response getProjects( public Response getProject(@PathParam("projectId") int projectId) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - - Project projectToReturn = dalFacade.getProjectById(projectId, internalUserId); - - if (projectToReturn == null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "project")); - } - - if (projectToReturn.getVisibility()) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PROJECT, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.read")); - } - } + Project projectToReturn = getProjectToReturn(projectId, dalFacade, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_4, projectId, Activity.DataType.PROJECT, internalUserId); return Response.ok(projectToReturn.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get project " + projectId + " failed"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get project " + projectId + " failed", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get project " + projectId + " failed"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get project " + projectId + " failed", logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + @NotNull + private static Project getProjectToReturn(int projectId, DALFacade dalFacade, Integer internalUserId) throws Exception { + Project projectToReturn = dalFacade.getProjectById(projectId, internalUserId); + + if (projectToReturn == null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "project")); + } + + if (projectToReturn.getVisibility()) { + boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, projectId, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PROJECT, projectId, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.read")); + } + } + return projectToReturn; + } + /** * This method allows to create a new project. * @@ -242,37 +221,19 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - - // Validate input - Set> violations = bazaarService.validateCreate(projectToCreate); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } - + resourceHelper.handleGenericError(bazaarService.validateCreate(projectToCreate)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PROJECT, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PROJECT, dalFacade), "error.authorization.project.create"); projectToCreate.setLeader(dalFacade.getUserById(internalUserId)); Project createdProject = dalFacade.createProject(projectToCreate, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_5, createdProject.getId(), Activity.DataType.PROJECT, internalUserId); return Response.status(Response.Status.CREATED).entity(createdProject.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Create project", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Create project", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -298,42 +259,21 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru public Response updateProject(@ApiParam(value = "Project entity", required = true) Project projectToUpdate) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - - // Take Object for generic error handling - Set> violations = bazaarService.validate(projectToUpdate); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + String userId = resourceHelper.getUserId(); + resourceHelper.handleGenericError(bazaarService.validate(projectToUpdate)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_PROJECT, projectToUpdate.getId(), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_PROJECT, projectToUpdate.getId(), dalFacade), "error.authorization.project.modify"); Project updatedProject = dalFacade.modifyProject(projectToUpdate); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_6, updatedProject.getId(), Activity.DataType.PROJECT, internalUserId); return Response.ok(updatedProject.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Update project", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Update project", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -358,9 +298,7 @@ public Response updateProject(@ApiParam(value = "Project entity", required = tru public Response deleteProject(@PathParam("projectId") int projectId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -374,20 +312,9 @@ public Response deleteProject(@PathParam("projectId") int projectId) { projectId, Activity.DataType.PROJECT, internalUserId); return Response.noContent().build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Delete project " + projectId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete project " + projectId); - logger.warning(bex.getMessage()); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Delete project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -412,35 +339,19 @@ public Response deleteProject(@PathParam("projectId") int projectId) { public Response followProject(@PathParam("projectId") int projectId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade), "error.authorization.follow.create"); dalFacade.followProject(internalUserId, projectId); Project project = dalFacade.getProjectById(projectId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_8, projectId, Activity.DataType.PROJECT, internalUserId); return Response.status(Response.Status.CREATED).entity(project.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Follow project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Follow project " + projectId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Follow project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Follow project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -465,35 +376,19 @@ public Response followProject(@PathParam("projectId") int projectId) { public Response unfollowProject(@PathParam("projectId") int projectId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.follow.delete")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade), "error.authorization.follow.delete"); dalFacade.unFollowProject(internalUserId, projectId); Project project = dalFacade.getProjectById(projectId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_9, projectId, Activity.DataType.PROJECT, internalUserId); return Response.ok(project.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unfollow project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Unfollow project " + projectId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Unfollow project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Unfollow project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -521,31 +416,18 @@ public Response getStatisticsForProject( @ApiParam(value = "Since timestamp, ISO-8601 e.g. 2017-12-30 or 2017-12-30T18:30:00Z", required = false) @QueryParam("since") String since) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); + Calendar sinceCal = resourceHelper.getSinceCal(since); Statistic projectStatistics = dalFacade.getStatisticsForProject(internalUserId, projectId, sinceCal); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_10, projectId, Activity.DataType.PROJECT, internalUserId); return Response.ok(projectStatistics.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get statistics for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get statistics for project " + projectId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get statistics for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get statistics for project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -570,9 +452,7 @@ public Response getStatisticsForProject( public Response getContributorsForProject(@PathParam("projectId") int projectId) throws Exception { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); ProjectContributors projectContributors = dalFacade.listContributorsForProject(projectId); @@ -580,20 +460,9 @@ public Response getContributorsForProject(@PathParam("projectId") int projectId) projectId, Activity.DataType.PROJECT, internalUserId); return Response.ok(projectContributors.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get contributors for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get contributors for project " + projectId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get contributors for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get contributors for project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -627,11 +496,7 @@ public Response getFollowersForProject(@PathParam("projectId") int projectId, resourceHelper.checkRegistrarErrors(); PageInfo pageInfo = new PageInfo(page, perPage); - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -639,7 +504,7 @@ public Response getFollowersForProject(@PathParam("projectId") int projectId, bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_12, projectId, Activity.DataType.PROJECT, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,null,null); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, null, null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(projectFollowers.toJSON()); @@ -648,20 +513,9 @@ public Response getFollowersForProject(@PathParam("projectId") int projectId, return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get followers for project " + projectId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get followers for project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -780,31 +634,10 @@ public Response getTagsForProject( ) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); - + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - - Project project = dalFacade.getProjectById(projectId, internalUserId); - - if (project == null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "project")); - } - - if (project.getVisibility()) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PROJECT, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.read")); - } - } - + getProjectToReturn(projectId, dalFacade, internalUserId); List tags = dalFacade.getTagsByProjectId(projectId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_12, projectId, Activity.DataType.PROJECT, internalUserId); @@ -814,20 +647,9 @@ public Response getTagsForProject( return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get tags for project " + projectId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get tags for project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -855,17 +677,11 @@ public Response createTag(@PathParam("projectId") int projectId, @ApiParam(value = "New Tag Representation", required = true) Tag tag) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - // TODO: Discuss permission model - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_CATEGORY, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.create")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_CATEGORY, dalFacade), "error.authorization.category.create"); // Ensure no cross-injection happens tag.setProjectId(projectId); @@ -875,20 +691,9 @@ public Response createTag(@PathParam("projectId") int projectId, projectId, Activity.DataType.TAG, internalUserId); return Response.status(Response.Status.CREATED).entity(createdTag.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create tag in project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Follow project " + projectId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Follow project " + projectId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Follow project " + projectId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -897,7 +702,7 @@ public Response createTag(@PathParam("projectId") int projectId, /** * Add a member to the project * - * @param projectId id of the project to update + * @param projectId id of the project to update * @param projectMember The new project member * @return */ @@ -913,18 +718,11 @@ public Response createTag(@PathParam("projectId") int projectId, @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") }) public Response addMember(@PathParam("projectId") int projectId, - @ApiParam(value = "New project member", required = true) ProjectMember projectMember) { + @ApiParam(value = "New project member", required = true) ProjectMember projectMember) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - - // Take Object for generic error handling - Set> violations = bazaarService.validate(projectMember); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + String userId = resourceHelper.getUserId(); + resourceHelper.handleGenericError(bazaarService.validate(projectMember)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -935,11 +733,7 @@ public Response addMember(@PathParam("projectId") int projectId, if (projectMember.getRole() == ProjectRole.ProjectAdmin) { privilege = PrivilegeEnum.Modify_ADMIN_MEMBERS; } - - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade), "error.authorization.project.modify"); // ensure the given user exists dalFacade.getUserById(projectMember.getUserId()); @@ -956,20 +750,9 @@ public Response addMember(@PathParam("projectId") int projectId, // TODO Return 'location' header to conform to HTTP specification return Response.status(Response.Status.CREATED).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Update project", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Update project", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -994,18 +777,11 @@ public Response addMember(@PathParam("projectId") int projectId, @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") }) public Response updateMember(@PathParam("projectId") int projectId, - @ApiParam(value = "New or updated project member", required = true) List projectMembers) { + @ApiParam(value = "New or updated project member", required = true) List projectMembers) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - - // Take Object for generic error handling - Set> violations = bazaarService.validate(projectMembers); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + String userId = resourceHelper.getUserId(); + resourceHelper.handleGenericError(bazaarService.validate(projectMembers)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -1019,10 +795,7 @@ public Response updateMember(@PathParam("projectId") int projectId, } }); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege.get(), projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege.get(), projectId, dalFacade), "error.authorization.project.modify"); for (ProjectMember projectMember : projectMembers) { // ensure the given user exists @@ -1034,20 +807,9 @@ public Response updateMember(@PathParam("projectId") int projectId, } return Response.noContent().build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Update member", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Update member", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1075,17 +837,12 @@ public Response getMembers(@PathParam("projectId") int projectId, DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); PageInfo pageInfo = new PageInfo(page, perPage); // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -1096,10 +853,7 @@ public Response getMembers(@PathParam("projectId") int projectId, privilege = PrivilegeEnum.Read_PROJECT; } - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade), "error.authorization.project.modify"); PaginationResult members = dalFacade.getProjectMembers(projectId, pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_12, @@ -1111,20 +865,9 @@ public Response getMembers(@PathParam("projectId") int projectId, return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get member", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get member", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -1145,9 +888,7 @@ public Response removeMember( @ApiParam(value = "User ID of the member to remove") @PathParam("memberUserId") int memberUserId) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -1161,31 +902,15 @@ public Response removeMember( if (modifiedMemberRoles.stream().anyMatch(role -> role.getName().equals(ProjectRole.ProjectAdmin.name()))) { privilege = PrivilegeEnum.Modify_ADMIN_MEMBERS; } - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); - } - + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade), "error.authorization.project.modify"); dalFacade.removeUserFromProject(memberUserId, projectId); - bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_6, projectId, Activity.DataType.PROJECT, internalUserId); return Response.noContent().build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Remove member", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Remove member", logger); } finally { bazaarService.closeDBConnection(dalFacade); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java index 9f1b5342..bc7b8bc1 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java @@ -1,6 +1,5 @@ package de.rwth.dbis.acis.bazaar.service.resources; -import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; @@ -11,7 +10,6 @@ import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; -import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; @@ -20,13 +18,15 @@ import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; -import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.HttpURLConnection; import java.time.OffsetDateTime; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Api(value = "users", description = "Users resource") @@ -54,7 +54,7 @@ public class UsersResource { private final L2pLogger logger = L2pLogger.getInstance(UsersResource.class.getName()); private final BazaarService bazaarService; - private ResourceHelper resourceHelper; + private final ResourceHelper resourceHelper; public UsersResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); @@ -80,31 +80,20 @@ public Response searchUser(@ApiParam(value = "Search filter", required = false) @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_USERS, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_USERS, dalFacade), "error.authorization.anonymous"); PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), new ArrayList<>(), search); - - // Take Object for generic error handling - Set> violations = bazaarService.validate(pageInfo); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } + resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); PaginationResult users = dalFacade.searchUsers(pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_53, internalUserId, Activity.DataType.USER, internalUserId); - Map> parameter = resourceHelper.getSortResponseMap(page,perPage,search,null); + Map> parameter = resourceHelper.getSortResponseMap(page, perPage, search, null); Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(users.toJSON()); @@ -113,20 +102,9 @@ public Response searchUser(@ApiParam(value = "Search filter", required = false) return responseBuilder.build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Search users"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Search users", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Search users"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Search users", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -160,20 +138,9 @@ public Response getUser(@PathParam("userId") int userId) { return Response.ok(user.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get user " + userId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get user " + userId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get user " + userId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get user " + userId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -197,14 +164,10 @@ public Response getUser(@PathParam("userId") int userId) { public Response getActiveUser() { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); // Block anonymous user - if (userId.equals("anonymous")) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.user.read")); - } + resourceHelper.checkAuthorization(!userId.equals("anonymous"), "error.authorization.user.read"); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -214,20 +177,9 @@ public Response getActiveUser() { return Response.ok(user.toPrivateJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get active user", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get active user", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -250,14 +202,10 @@ public Response getActiveUser() { public Response getUserDashboard() { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); // Block anonymous user - if (userId.equals("anonymous")) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.user.read")); - } + resourceHelper.checkAuthorization(!userId.equals("anonymous"), "error.authorization.user.read"); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -268,18 +216,9 @@ public Response getUserDashboard() { return Response.ok(data.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Get active user", logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get active user", logger); } finally { bazaarService.closeDBConnection(dalFacade); } @@ -309,43 +248,30 @@ public Response updateUser(@PathParam("userId") int userId, try { resourceHelper.checkRegistrarErrors(); Agent agent = Context.getCurrent().getMainAgent(); - - // Take Object for generic error handling - Set> violations = bazaarService.validate(userToUpdate); - if (violations.size() > 0) { - ExceptionHandler.getInstance().handleViolations(violations); - } - + resourceHelper.handleGenericError(bazaarService.validate(userToUpdate)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(agent.getIdentifier()); - if (!internalUserId.equals(userId)) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, - "UserId is not identical with user sending this request."); - } + isUserIdMatching(userId, internalUserId); User updatedUser = dalFacade.modifyUser(userToUpdate); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_56, userId, Activity.DataType.USER, internalUserId); return Response.ok(updatedUser.toJSON()).build(); } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update user " + userId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } + return resourceHelper.handleBazaarException(bex, "Update user " + userId, logger); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update user " + userId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Update user " + userId, logger); } finally { bazaarService.closeDBConnection(dalFacade); } } + private static void isUserIdMatching(int userId, Integer internalUserId) throws BazaarException { + if (!internalUserId.equals(userId)) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, + "UserId is not identical with user sending this request."); + } + } + /** * This method returns an entityOverview for the logged in user * @@ -374,31 +300,21 @@ public Response getEntityOverview( //Possibly allow filtertype "all"? DALFacade dalFacade = null; try { - resourceHelper.checkRegistrarErrors(); - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - List sortList = new ArrayList<>(); - for (String sortOption : sort) { - Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); - sortList.add(sortField); - } - + String userId = resourceHelper.getUserId(); + List sortList = resourceHelper.getSortFieldList(sort, sortDirection); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - HashMap filterMap = new HashMap<>(); for (String filterOption : filters) { filterMap.put(filterOption, internalUserId.toString()); } PageInfo pageInfo = new PageInfo(0, 0, filterMap, sortList, search); - EntityOverview result = dalFacade.getEntitiesForUser(include, pageInfo, internalUserId); // Wrong SERVICE_CUSTOM_MESSAGE_3 ? bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, 0, Activity.DataType.USER, internalUserId); - Response.ResponseBuilder responseBuilder = Response.ok(); responseBuilder = responseBuilder.entity(result.toJSON()); @@ -408,10 +324,7 @@ public Response getEntityOverview( Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get entityOverview failed"); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get entityOverview failed"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + return resourceHelper.handleException(ex, "Get entityOverview failed", logger); } finally { bazaarService.closeDBConnection(dalFacade); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/WebhookResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/WebhookResource.java index f02e6e46..758f796b 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/WebhookResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/WebhookResource.java @@ -3,25 +3,17 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; -import de.rwth.dbis.acis.bazaar.service.BazaarFunction; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; -import de.rwth.dbis.acis.bazaar.service.dal.entities.Activity; import de.rwth.dbis.acis.bazaar.service.dal.entities.Project; import de.rwth.dbis.acis.bazaar.service.dal.entities.Requirement; -import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import i5.las2peer.api.Context; -import i5.las2peer.api.logging.MonitoringEvent; import i5.las2peer.api.security.Agent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; import net.minidev.json.JSONObject; import net.minidev.json.parser.JSONParser; -import net.minidev.json.parser.ParseException; import org.apache.http.HttpStatus; import javax.crypto.Mac; @@ -30,9 +22,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.HttpURLConnection; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.util.EnumSet; @Api(value = "webhook") @SwaggerDefinition( @@ -56,10 +45,10 @@ @Path("/webhook/{projectId}/github") public class WebhookResource { - private L2pLogger logger = L2pLogger.getInstance(WebhookResource.class.getName()); - private BazaarService bazaarService; + private final L2pLogger logger = L2pLogger.getInstance(WebhookResource.class.getName()); + private final BazaarService bazaarService; - private ResourceHelper resourceHelper; + private final ResourceHelper resourceHelper; private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' @@ -213,8 +202,6 @@ public Response handleWebhook(@PathParam("projectId") int projectId, String requ } } - } catch (ParseException | BazaarException e) { - e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } @@ -232,9 +219,9 @@ private static char[] encode(byte[] bytes) { char[] result = new char[2 * amount]; int j = 0; - for (int i = 0; i < amount; i++) { - result[j++] = HEX[(0xF0 & bytes[i]) >>> 4]; - result[j++] = HEX[(0x0F & bytes[i])]; + for (byte aByte : bytes) { + result[j++] = HEX[(0xF0 & aByte) >>> 4]; + result[j++] = HEX[(0x0F & aByte)]; } return result; } From 2213157898f64ef2d748ca1d96628fe850c2648d Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 11 Jan 2023 12:13:52 +0100 Subject: [PATCH 11/42] fix: authorization in comment --- .../dbis/acis/bazaar/service/resources/CommentsResource.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java index a2ada824..e4d0e23d 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java @@ -291,8 +291,11 @@ public Response updateComment(@ApiParam(value = "Comment entity", required = tru Comment internalComment = dalFacade.getCommentById(commentToUpdate.getId()); Requirement requirement = dalFacade.getRequirementById(internalComment.getRequirementId(), internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade), "error.authorization.comment.modify"); + boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade); + if (!authorized && !internalComment.isOwner(internalUserId)) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.modify")); + } internalComment.setMessage(commentToUpdate.getMessage()); Comment updatedComment = dalFacade.updateComment(internalComment); From 9c5ee0c6273acf6ed950bbd29dea30bcd766ca78 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 17 Jan 2023 12:36:13 +0100 Subject: [PATCH 12/42] refactor: further remove duplications and reduce complexity --- .../service/resources/AdminResource.java | 9 +-- .../service/resources/CategoryResource.java | 23 +++--- .../service/resources/CommentsResource.java | 21 +++--- .../service/resources/FeedbackResource.java | 2 +- .../PersonalisationDataResource.java | 4 +- .../service/resources/ProjectsResource.java | 72 +++++++++---------- .../resources/RequirementsResource.java | 29 ++++---- .../service/resources/UsersResource.java | 6 +- .../resources/helpers/ResourceHelper.java | 6 +- 9 files changed, 82 insertions(+), 90 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java index 53603b2f..cd1441a3 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/AdminResource.java @@ -9,9 +9,6 @@ import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.SystemRole; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import de.rwth.dbis.acis.bazaar.service.resources.helpers.ResourceHelper; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import de.rwth.dbis.acis.bazaar.service.twitter.WeeklyNewProjectsTweetTask; @@ -223,11 +220,7 @@ private Response handleAuthenticatedRequest( resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, dalFacade.getRoleByName(requiredRole), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, authorizationErrorMessage); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, dalFacade.getRoleByName(requiredRole), dalFacade), authorizationErrorMessage, true); //// actual operation -start return handler.handle(dalFacade, internalUserId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java index b6bd2629..499f0f5d 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java @@ -27,7 +27,10 @@ import java.net.URISyntaxException; import java.text.MessageFormat; import java.time.OffsetDateTime; -import java.util.*; +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @Api(value = "categories", description = "Categories resource") @@ -115,9 +118,9 @@ public Integer getInternalUserId(int projectId, DALFacade dalFacade, String user ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "category")); } if (dalFacade.isProjectPublic(projectId)) { - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, projectId, dalFacade), "error.authorization.anonymous"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, projectId, dalFacade), ResourceHelper.ERROR_ANONYMUS, true); } else { - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, projectId, dalFacade), "error.authorization.category.read"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, projectId, dalFacade), "error.authorization.category.read", true); } return internalUserId; } @@ -148,9 +151,9 @@ public Response getCategory(@PathParam("categoryId") int categoryId) { bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_15, categoryId, Activity.DataType.CATEGORY, internalUserId); if (dalFacade.isCategoryPublic(categoryId)) { - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, categoryToReturn.getProjectId(), dalFacade), "error.authorization.anonymous"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, categoryToReturn.getProjectId(), dalFacade), ResourceHelper.ERROR_ANONYMUS, true); } else { - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, categoryToReturn.getProjectId(), dalFacade), "error.authorization.category.read"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_CATEGORY, categoryToReturn.getProjectId(), dalFacade), "error.authorization.category.read", true); } return Response.ok(categoryToReturn.toJSON()).build(); } catch (BazaarException bex) { @@ -187,7 +190,7 @@ public Response createCategory(@ApiParam(value = "Category entity", required = t dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_CATEGORY, categoryToCreate.getProjectId(), dalFacade), "error.authorization.category.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_CATEGORY, categoryToCreate.getProjectId(), dalFacade), "error.authorization.category.create", true); categoryToCreate.setCreator(dalFacade.getUserById(internalUserId)); Category createdCategory = dalFacade.createCategory(categoryToCreate, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(createdCategory.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_16, @@ -231,7 +234,7 @@ public Response updateCategory(@ApiParam(value = "Category entity", required = t // Prevent forget project ids Category internalCategory = dalFacade.getCategoryById(categoryToUpdate.getId(), internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_CATEGORY, internalCategory.getProjectId(), dalFacade), "error.authorization.category.modify"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_CATEGORY, internalCategory.getProjectId(), dalFacade), "error.authorization.category.modify", true); Category updatedCategory = dalFacade.modifyCategory(categoryToUpdate); bazaarService.getNotificationDispatcher().dispatchNotification(updatedCategory.getLastUpdatedDate(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_17, @@ -271,7 +274,7 @@ public Response deleteCategory(@PathParam("categoryId") int categoryId) { Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category categoryToDelete = dalFacade.getCategoryById(categoryId, internalUserId); Project project = dalFacade.getProjectById(categoryToDelete.getProjectId(), internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_CATEGORY, project.getId(), dalFacade), "error.authorization.category.modify"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_CATEGORY, project.getId(), dalFacade), "error.authorization.category.modify", true); isDefaultCategory(categoryId, project); Category deletedCategory = dalFacade.deleteCategoryById(categoryId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(deletedCategory.getLastUpdatedDate(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_18, @@ -320,7 +323,7 @@ public Response followCategory(@PathParam("categoryId") int categoryId) { String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade), "error.authorization.follow.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade), "error.authorization.follow.create", true); dalFacade.followCategory(internalUserId, categoryId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_19, @@ -357,7 +360,7 @@ public Response unfollowCategory(@PathParam("categoryId") int categoryId) { String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade), "error.authorization.follow.delete"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade), "error.authorization.follow.delete", true); dalFacade.unFollowCategory(internalUserId, categoryId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_20, diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java index e4d0e23d..7a09808b 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java @@ -149,9 +149,7 @@ public Response getAllComments( public Response getCommentsForRequirement(int requirementId) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); //Todo use requirement's projectId for security context, not the one sent from client @@ -178,9 +176,9 @@ public Response getCommentsForRequirement(int requirementId) { private void checkIsPublic(boolean dalFacade, Integer internalUserId, int project, DALFacade dalFacade1) throws BazaarException { if (dalFacade) { - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, project, dalFacade1), "error.authorization.anonymous"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, project, dalFacade1), ResourceHelper.ERROR_ANONYMUS, true); } else { - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_COMMENT, project, dalFacade1), "error.authorization.comment.read"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_COMMENT, project, dalFacade1), "error.authorization.comment.read", true); } } @@ -241,15 +239,14 @@ public Response getComment(@PathParam("commentId") int commentId) { public Response createComment(@ApiParam(value = "Comment entity", required = true) Comment commentToCreate) { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); + String userId = resourceHelper.getUserId(); // TODO: check whether the current user may create a new requirement // TODO: check whether all required parameters are entered resourceHelper.checkRegistrarErrors(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(commentToCreate.getRequirementId(), internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_COMMENT, requirement.getProjectId(), dalFacade), "error.authorization.comment.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_COMMENT, requirement.getProjectId(), dalFacade), "error.authorization.comment.create", true); commentToCreate.setCreator(dalFacade.getUserById(internalUserId)); resourceHelper.handleGenericError(bazaarService.validateCreate(commentToCreate)); @@ -292,10 +289,8 @@ public Response updateComment(@ApiParam(value = "Comment entity", required = tru Comment internalComment = dalFacade.getCommentById(commentToUpdate.getId()); Requirement requirement = dalFacade.getRequirementById(internalComment.getRequirementId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade); - if (!authorized && !internalComment.isOwner(internalUserId)) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.modify")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade), "error.authorization.comment.modify", !internalComment.isOwner(internalUserId)); + internalComment.setMessage(commentToUpdate.getMessage()); Comment updatedComment = dalFacade.updateComment(internalComment); @@ -339,7 +334,7 @@ public Response deleteComment(@PathParam("commentId") int commentId) { Comment commentToDelete = dalFacade.getCommentById(commentId); Requirement requirement = dalFacade.getRequirementById(commentToDelete.getRequirementId(), internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade), "error.authorization.comment.modify"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade), "error.authorization.comment.modify", true); Comment deletedComment = dalFacade.deleteCommentById(commentId); bazaarService.getNotificationDispatcher().dispatchNotification(deletedComment.getCreationDate(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_48, deletedComment.getId(), Activity.DataType.COMMENT, internalUserId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java index 8ce1c390..d1fe384c 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java @@ -80,7 +80,7 @@ public Response getFeedbackForProject(int projectId, int page, int perPage) { Project project = dalFacade.getProjectById(projectId, internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_FEEDBACK, project.getId(), dalFacade), "error.authorization.feedback.read"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_FEEDBACK, project.getId(), dalFacade), "error.authorization.feedback.read", true); PaginationResult feedbackResult = dalFacade.getFeedbackByProject(projectId, pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_43, diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java index 4cc8d2f3..111a488c 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java @@ -74,7 +74,7 @@ public Response getPersonalisationData(@PathParam("key") String key, @PathParam( dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PERSONALISATION_DATA, dalFacade), "error.authorization.personalisationData.read"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PERSONALISATION_DATA, dalFacade), "error.authorization.personalisationData.read", true); PersonalisationData data = dalFacade.getPersonalisationData(internalUserId, key, version); return Response.ok(data.toJSON()).build(); } catch (BazaarException bex) { @@ -109,7 +109,7 @@ public Response setPersonalisationData(@PathParam("key") String key, @PathParam( String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PERSONALISATION_DATA, dalFacade), "error.authorization.comment.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PERSONALISATION_DATA, dalFacade), "error.authorization.comment.create", true); PersonalisationData fullData = PersonalisationData.builder().key(key).userId(internalUserId).version(version).value(data.getValue()).build(); resourceHelper.handleGenericError(bazaarService.validateCreate(fullData)); dalFacade.setPersonalisationData(fullData); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java index a2e8ef0c..0c706a91 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java @@ -178,7 +178,7 @@ public Response getProject(@PathParam("projectId") int projectId) { } @NotNull - private static Project getProjectToReturn(int projectId, DALFacade dalFacade, Integer internalUserId) throws Exception { + private Project getProjectToReturn(int projectId, DALFacade dalFacade, Integer internalUserId) throws Exception { Project projectToReturn = dalFacade.getProjectById(projectId, internalUserId); if (projectToReturn == null) { @@ -186,15 +186,9 @@ private static Project getProjectToReturn(int projectId, DALFacade dalFacade, In } if (projectToReturn.getVisibility()) { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, projectId, dalFacade), ResourceHelper.ERROR_ANONYMUS, true); } else { - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PROJECT, projectId, dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.read")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Read_PROJECT, projectId, dalFacade), "error.authorization.project.read", true); } return projectToReturn; } @@ -224,7 +218,7 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru resourceHelper.handleGenericError(bazaarService.validateCreate(projectToCreate)); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PROJECT, dalFacade), "error.authorization.project.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PROJECT, dalFacade), "error.authorization.project.create", true); projectToCreate.setLeader(dalFacade.getUserById(internalUserId)); Project createdProject = dalFacade.createProject(projectToCreate, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_5, @@ -264,7 +258,7 @@ public Response updateProject(@ApiParam(value = "Project entity", required = tru dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_PROJECT, projectToUpdate.getId(), dalFacade), "error.authorization.project.modify"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Modify_PROJECT, projectToUpdate.getId(), dalFacade), "error.authorization.project.modify", true); Project updatedProject = dalFacade.modifyProject(projectToUpdate); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_6, @@ -303,10 +297,7 @@ public Response deleteProject(@PathParam("projectId") int projectId) { Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Project projectToDelete = dalFacade.getProjectById(projectId, internalUserId); - boolean authorized = new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Delete_PROJECT, projectId, dalFacade); - if (!authorized && !projectToDelete.isOwner(internalUserId)) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.delete")); - } + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Delete_PROJECT, projectId, dalFacade), "error.authorization.project.delete", !projectToDelete.isOwner(internalUserId)); dalFacade.deleteProjectById(projectId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_28, projectId, Activity.DataType.PROJECT, internalUserId); @@ -342,7 +333,7 @@ public Response followProject(@PathParam("projectId") int projectId) { String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade), "error.authorization.follow.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade), "error.authorization.follow.create", true); dalFacade.followProject(internalUserId, projectId); Project project = dalFacade.getProjectById(projectId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_8, @@ -379,7 +370,7 @@ public Response unfollowProject(@PathParam("projectId") int projectId) { String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade), "error.authorization.follow.delete"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade), "error.authorization.follow.delete", true); dalFacade.unFollowProject(internalUserId, projectId); Project project = dalFacade.getProjectById(projectId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_9, @@ -491,9 +482,7 @@ public Response getFollowersForProject(@PathParam("projectId") int projectId, @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) throws Exception { DALFacade dalFacade = null; try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - resourceHelper.checkRegistrarErrors(); + String userId = resourceHelper.getUserId(); PageInfo pageInfo = new PageInfo(page, perPage); resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); @@ -681,7 +670,7 @@ public Response createTag(@PathParam("projectId") int projectId, dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_CATEGORY, dalFacade), "error.authorization.category.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_CATEGORY, dalFacade), "error.authorization.category.create", true); // Ensure no cross-injection happens tag.setProjectId(projectId); @@ -730,10 +719,8 @@ public Response addMember(@PathParam("projectId") int projectId, PrivilegeEnum privilege = PrivilegeEnum.Modify_MEMBERS; // Only Admins should be able to create new admins. // Differentiate here - if (projectMember.getRole() == ProjectRole.ProjectAdmin) { - privilege = PrivilegeEnum.Modify_ADMIN_MEMBERS; - } - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade), "error.authorization.project.modify"); + privilege = getPrivilege(projectMember, privilege); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade), "error.authorization.project.modify", true); // ensure the given user exists dalFacade.getUserById(projectMember.getUserId()); @@ -758,6 +745,13 @@ public Response addMember(@PathParam("projectId") int projectId, } } + private static PrivilegeEnum getPrivilege(ProjectMember projectMember, PrivilegeEnum privilege) { + if (projectMember.getRole() == ProjectRole.ProjectAdmin) { + privilege = PrivilegeEnum.Modify_ADMIN_MEMBERS; + } + return privilege; + } + /** * Allows to update a certain project. * @@ -786,16 +780,9 @@ public Response updateMember(@PathParam("projectId") int projectId, dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - AtomicReference privilege = new AtomicReference<>(PrivilegeEnum.Modify_MEMBERS); - projectMembers.forEach(projectMember -> { - // Only Admins should be able to create new admins. - // Differentiate here - if (projectMember.getRole() == ProjectRole.ProjectAdmin) { - privilege.set(PrivilegeEnum.Modify_ADMIN_MEMBERS); - } - }); + AtomicReference privilege = setPrivileges(projectMembers); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege.get(), projectId, dalFacade), "error.authorization.project.modify"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege.get(), projectId, dalFacade), "error.authorization.project.modify", true); for (ProjectMember projectMember : projectMembers) { // ensure the given user exists @@ -815,6 +802,19 @@ public Response updateMember(@PathParam("projectId") int projectId, } } + @NotNull + private static AtomicReference setPrivileges(List projectMembers) { + AtomicReference privilege = new AtomicReference<>(PrivilegeEnum.Modify_MEMBERS); + projectMembers.forEach(projectMember -> { + // Only Admins should be able to create new admins. + // Differentiate here + if (projectMember.getRole() == ProjectRole.ProjectAdmin) { + privilege.set(PrivilegeEnum.Modify_ADMIN_MEMBERS); + } + }); + return privilege; + } + /** * Allows to update a certain project. * @@ -853,7 +853,7 @@ public Response getMembers(@PathParam("projectId") int projectId, privilege = PrivilegeEnum.Read_PROJECT; } - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade), "error.authorization.project.modify"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade), "error.authorization.project.modify", true); PaginationResult members = dalFacade.getProjectMembers(projectId, pageInfo); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_12, @@ -902,7 +902,7 @@ public Response removeMember( if (modifiedMemberRoles.stream().anyMatch(role -> role.getName().equals(ProjectRole.ProjectAdmin.name()))) { privilege = PrivilegeEnum.Modify_ADMIN_MEMBERS; } - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade), "error.authorization.project.modify"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, privilege, projectId, dalFacade), "error.authorization.project.modify", true); dalFacade.removeUserFromProject(memberUserId, projectId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_6, projectId, Activity.DataType.PROJECT, internalUserId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index 8b31c769..290019ef 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -305,7 +305,7 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); resourceHelper.checkRegistrarErrors(); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_REQUIREMENT, requirementToCreate.getProjectId(), dalFacade), "error.authorization.requirement.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_REQUIREMENT, requirementToCreate.getProjectId(), dalFacade), "error.authorization.requirement.create", true); // TODO Refactor this! Such logic should be moved to the constructor requirementToCreate.setCreator(dalFacade.getUserById(internalUserId)); @@ -433,7 +433,7 @@ public Response deleteRequirement(@PathParam("requirementId") int requirementId) Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirementToDelete = dalFacade.getRequirementById(requirementId, internalUserId); Project project = dalFacade.getProjectById(requirementToDelete.getProjectId(), internalUserId); - resourceHelper.checkAuthorization(isUserAuthorizedToDeleteRequirement(dalFacade, internalUserId, project, requirementToDelete), "error.authorization.requirement.delete"); + resourceHelper.checkAuthorization(isUserAuthorizedToDeleteRequirement(dalFacade, internalUserId, project, requirementToDelete), "error.authorization.requirement.delete", true); Requirement deletedRequirement = dalFacade.deleteRequirementById(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_28, requirementId, Activity.DataType.REQUIREMENT, internalUserId); @@ -489,7 +489,7 @@ public Response leaddevelopRequirement(@PathParam("requirementId") int requireme String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade), "error.authorization.vote.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade), "error.authorization.vote.create", true); Requirement requirement = dalFacade.setUserAsLeadDeveloper(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.LEADDEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_29, requirementId, Activity.DataType.REQUIREMENT, internalUserId); @@ -525,7 +525,7 @@ public Response unleaddevelopRequirement(@PathParam("requirementId") int require String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade), "error.authorization.vote.delete"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade), "error.authorization.vote.delete", true); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); ensureCatIsInProject(requirement.getLeadDeveloper().getId() != internalUserId, ErrorCode.AUTHORIZATION, "You are not lead developer."); requirement = dalFacade.deleteUserAsLeadDeveloper(requirementId, internalUserId); @@ -564,7 +564,7 @@ public Response developRequirement(@PathParam("requirementId") int requirementId dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_DEVELOP, requirement.getProjectId(), dalFacade), "error.authorization.develop.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Create_DEVELOP, requirement.getProjectId(), dalFacade), "error.authorization.develop.create", true); dalFacade.wantToDevelop(internalUserId, requirementId); dalFacade.followRequirement(internalUserId, requirementId); @@ -605,7 +605,7 @@ public Response undevelopRequirement(@PathParam("requirementId") int requirement dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Delete_DEVELOP, requirement.getProjectId(), dalFacade), "error.authorization.develop.delete"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Delete_DEVELOP, requirement.getProjectId(), dalFacade), "error.authorization.develop.delete", true); dalFacade.notWantToDevelop(internalUserId, requirementId); // refresh requirement object @@ -711,7 +711,7 @@ public Response followRequirement(@PathParam("requirementId") int requirementId) String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade), "error.authorization.follow.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_FOLLOW, dalFacade), "error.authorization.follow.create", true); dalFacade.followRequirement(internalUserId, requirementId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_33, @@ -748,7 +748,7 @@ public Response unfollowRequirement(@PathParam("requirementId") int requirementI String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade), "error.authorization.follow.delete"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_FOLLOW, dalFacade), "error.authorization.follow.delete", true); dalFacade.unFollowRequirement(internalUserId, requirementId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_34, @@ -785,10 +785,9 @@ public Response vote(@PathParam("requirementId") int requirementId, DALFacade dalFacade = null; try { String userId = resourceHelper.getUserId(); - dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_VOTE, dalFacade), "error.authorization.vote.create"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_VOTE, dalFacade), "error.authorization.vote.create", true); dalFacade.vote(internalUserId, requirementId, direction.isUpVote()); followUpvote(requirementId, direction, dalFacade, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.VOTE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_35, @@ -831,7 +830,7 @@ public Response unvote(@PathParam("requirementId") int requirementId) { String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_VOTE, dalFacade), "error.authorization.vote.delete"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_VOTE, dalFacade), "error.authorization.vote.delete", true); dalFacade.unVote(internalUserId, requirementId); return Response.noContent().build(); } catch (BazaarException bex) { @@ -866,7 +865,7 @@ public Response realize(@PathParam("requirementId") int requirementId) { dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade), "error.authorization.requirement.realize"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade), "error.authorization.requirement.realize", true); requirement = dalFacade.setRequirementToRealized(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.REALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_37, requirementId, Activity.DataType.REQUIREMENT, internalUserId); @@ -904,7 +903,7 @@ public Response unrealize(@PathParam("requirementId") int requirementId) { Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade), "error.authorization.requirement.realize"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade), "error.authorization.requirement.realize", true); requirement = dalFacade.setRequirementToUnRealized(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNREALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_38, @@ -1169,9 +1168,9 @@ public Response getAttachmentsForRequirement(@PathParam("requirementId") int req private void isPublicCheck(boolean dalFacade, Integer internalUserId, PrivilegeEnum read_PUBLIC_COMMENT, int project, DALFacade dalFacade1, PrivilegeEnum read_COMMENT, String key) throws BazaarException { if (dalFacade) { - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, read_PUBLIC_COMMENT, project, dalFacade1), "error.authorization.anonymous"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, read_PUBLIC_COMMENT, project, dalFacade1), ResourceHelper.ERROR_ANONYMUS, true); } else { - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, read_COMMENT, project, dalFacade1), key); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, read_COMMENT, project, dalFacade1), key, true); } } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java index bc7b8bc1..3bafd298 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java @@ -83,7 +83,7 @@ public Response searchUser(@ApiParam(value = "Search filter", required = false) String userId = resourceHelper.getUserId(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_USERS, dalFacade), "error.authorization.anonymous"); + resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_USERS, dalFacade), ResourceHelper.ERROR_ANONYMUS, true); PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), new ArrayList<>(), search); resourceHelper.handleGenericError(bazaarService.validate(pageInfo)); @@ -167,7 +167,7 @@ public Response getActiveUser() { String userId = resourceHelper.getUserId(); // Block anonymous user - resourceHelper.checkAuthorization(!userId.equals("anonymous"), "error.authorization.user.read"); + resourceHelper.checkAuthorization(!userId.equals("anonymous"), "error.authorization.user.read", true); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); @@ -205,7 +205,7 @@ public Response getUserDashboard() { String userId = resourceHelper.getUserId(); // Block anonymous user - resourceHelper.checkAuthorization(!userId.equals("anonymous"), "error.authorization.user.read"); + resourceHelper.checkAuthorization(!userId.equals("anonymous"), "error.authorization.user.read", true); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java index d0690509..e9eba089 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/helpers/ResourceHelper.java @@ -24,6 +24,8 @@ public class ResourceHelper { private final BazaarService bazaarService; + public static final String ERROR_ANONYMUS = "error.authorization.anonymous"; + public ResourceHelper(BazaarService service) { this.bazaarService = service; } @@ -82,8 +84,8 @@ public void checkViolations(PageInfo pageInfo) throws BazaarException { } } - public void checkAuthorization(boolean authorized, String key) throws BazaarException { - if (!authorized) { + public void checkAuthorization(boolean authorized, String key, boolean additionalCheck) throws BazaarException { + if (!authorized && additionalCheck) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString(key)); } } From 99d807b1bb77db8a76e05b29348ee012fec2b475 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 18 Jan 2023 09:57:05 +0100 Subject: [PATCH 13/42] fix: add missing resource bundle which causes an error moving requirements --- reqbaz/src/main/resources/i18n/Translation_de.properties | 1 + reqbaz/src/main/resources/i18n/Translation_en.properties | 1 + 2 files changed, 2 insertions(+) diff --git a/reqbaz/src/main/resources/i18n/Translation_de.properties b/reqbaz/src/main/resources/i18n/Translation_de.properties index 48dcbb89..e74df99f 100644 --- a/reqbaz/src/main/resources/i18n/Translation_de.properties +++ b/reqbaz/src/main/resources/i18n/Translation_de.properties @@ -30,6 +30,7 @@ error.authorization.category.delete=Die Projektkomoponente mit id {0} kann nicht error.authorization.requirements.read=Nur eingeloggte Mitglieder können Requirements lesen. error.authorization.requirement.create=Nur Projektmitglieder könnnen Anforderungen erstellen. error.authorization.requirement.delete=Nur der Ersteller einer Anforderung kann eine Anforderung löschen. +error.authorization.requirement.move=Nur Projektmitglieder könnnen Anforderungen verschieben. error.authorization.develop.create=Nur Projektmitglieder können sich als Entwickler eintragen. error.authorization.develop.delete=Nur Projektmitglieder können sich als Entwickler austragen. error.authorization.follow.create=Nur Projekmitglieder können ein Projekt folgen. diff --git a/reqbaz/src/main/resources/i18n/Translation_en.properties b/reqbaz/src/main/resources/i18n/Translation_en.properties index 5cf5f335..336498f5 100644 --- a/reqbaz/src/main/resources/i18n/Translation_en.properties +++ b/reqbaz/src/main/resources/i18n/Translation_en.properties @@ -31,6 +31,7 @@ error.authorization.requirements.read=Only logged in users can read requirements error.authorization.requirement.create=Only project members can create requirements. error.authorization.requirement.delete=Only the creator can delete requirements. error.authorization.requirement.realize=Only project members can set requirements as realized. +error.authorization.requirement.move=Only project members can move requirements. error.authorization.develop.create=Only project members can register to develop a requirement. error.authorization.develop.delete=Only project members can deregister from developing a requirement. error.authorization.follow.create=Only project members can register to follow a requirement. From 0c7ea8ecb1be139e07c21ae9026723bb3630839f Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 18 Jan 2023 10:05:17 +0100 Subject: [PATCH 14/42] refactor: reduce complexity in DALFacadeImpl --- .../bazaar/service/dal/DALFacadeImpl.java | 136 ++++++++++-------- 1 file changed, 78 insertions(+), 58 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java index ca1944a7..5da97308 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java @@ -232,7 +232,7 @@ public Project createProject(Project project, int userId) throws Exception { // TODO: concurrency transaction -> https://www.jooq.org/doc/3.9/manual/sql-execution/transaction-management/ addUserToRole(userId, "ProjectAdmin", newProject.getId()); - // This is stupid, but the return value of update is inclomplete (dependent objects won't be resolved, since only the top level get by id method is called. + // This is stupid, but the return value of update is incomplete (dependent objects won't be resolved, since only the top level get by id method is called). // Call repository get separately projectRepository.update(newProject); return projectRepository.findById(newProject.getId(), userId); @@ -343,92 +343,112 @@ public Requirement modifyRequirement(Requirement modifiedRequirement, int userId if (modifiedRequirement.getCategories() != null) { List oldCategories = listCategoriesByRequirementId(modifiedRequirement.getId(), userId); + handleOldCategory(modifiedRequirement, oldCategories); + handleNewCategory(modifiedRequirement, oldCategories); + } + synchronizeTags(modifiedRequirement, oldRequirement); + synchronizeAttachments(modifiedRequirement, userId, oldRequirement); + + return getRequirementById(modifiedRequirement.getId(), userId); + } + + private void handleNewCategory(Requirement modifiedRequirement, List oldCategories) throws BazaarException { + for (Integer newCategory : modifiedRequirement.getCategories()) { + boolean containCategory = false; for (Category oldCategory : oldCategories) { - boolean containCategory = false; - for (Integer newCategory : modifiedRequirement.getCategories()) { - if (oldCategory.getId() == newCategory) { - containCategory = true; - break; - } - } - if (!containCategory) { - deleteCategoryTag(modifiedRequirement.getId(), oldCategory.getId()); + if (oldCategory.getId() == newCategory) { + containCategory = true; + break; } } + if (!containCategory) { + addCategoryTag(modifiedRequirement.getId(), newCategory); + } + } + } + + private void handleOldCategory(Requirement modifiedRequirement, List oldCategories) throws BazaarException { + for (Category oldCategory : oldCategories) { + boolean containCategory = false; for (Integer newCategory : modifiedRequirement.getCategories()) { - boolean containCategory = false; - for (Category oldCategory : oldCategories) { - if (oldCategory.getId() == newCategory) { - containCategory = true; - break; - } - } - if (!containCategory) { - addCategoryTag(modifiedRequirement.getId(), newCategory); + if (oldCategory.getId() == newCategory) { + containCategory = true; + break; } } + if (!containCategory) { + deleteCategoryTag(modifiedRequirement.getId(), oldCategory.getId()); + } } + } - // Synchronize tags - if (modifiedRequirement.getTags() != null) { + private void synchronizeAttachments(Requirement modifiedRequirement, int userId, Requirement oldRequirement) { + if (modifiedRequirement.getAttachments() != null) { // Check if tags have changed - for (Tag tag : modifiedRequirement.getTags()) { - try { - Tag internalTag = getTagById(tag.getId()); - - // Check if tag exists (in project) - if (internalTag == null || modifiedRequirement.getProjectId() != internalTag.getProjectId()) { - tag.setProjectId(modifiedRequirement.getProjectId()); - tag = createTag(tag); - } - tagRequirement(tag.getId(), modifiedRequirement.getId()); - } catch (Exception e) { - e.printStackTrace(); - } - } + checkTagChangesAttachments(modifiedRequirement, userId); // Remove tags no longer present - oldRequirement.getTags().stream().filter(tag -> modifiedRequirement.getTags().contains(tag)).forEach(tag -> { + oldRequirement.getAttachments().stream().filter(attachment -> modifiedRequirement.getAttachments().contains(attachment)).forEach(attachment -> { try { - untagRequirement(tag.getId(), oldRequirement.getId()); + deleteAttachmentById(attachment.getId()); } catch (Exception e) { e.printStackTrace(); } }); } + } - // Synchronize attachments - if (modifiedRequirement.getAttachments() != null) { - // Check if tags have changed - for (Attachment attachment : modifiedRequirement.getAttachments()) { - try { - Attachment internalAttachment = null; - if (attachment.getId() != 0) { - internalAttachment = getAttachmentById(attachment.getId()); - } - - // Check if attachment exists, otherwise create - if (internalAttachment == null) { - attachment.setRequirementId(modifiedRequirement.getId()); - attachment.setCreator(getUserById(userId)); - createAttachment(attachment); - } - } catch (Exception e) { - e.printStackTrace(); + private void checkTagChangesAttachments(Requirement modifiedRequirement, int userId) { + for (Attachment attachment : modifiedRequirement.getAttachments()) { + try { + Attachment internalAttachment = null; + if (attachment.getId() != 0) { + internalAttachment = getAttachmentById(attachment.getId()); } + + // Check if attachment exists, otherwise create + if (internalAttachment == null) { + attachment.setRequirementId(modifiedRequirement.getId()); + attachment.setCreator(getUserById(userId)); + createAttachment(attachment); + } + } catch (Exception e) { + e.printStackTrace(); } + } + } + + private void synchronizeTags(Requirement modifiedRequirement, Requirement oldRequirement) { + if (modifiedRequirement.getTags() != null) { + // Check if tags have changed + checkTagChanges(modifiedRequirement); // Remove tags no longer present - oldRequirement.getAttachments().stream().filter(attachment -> modifiedRequirement.getAttachments().contains(attachment)).forEach(attachment -> { + oldRequirement.getTags().stream().filter(tag -> modifiedRequirement.getTags().contains(tag)).forEach(tag -> { try { - deleteAttachmentById(attachment.getId()); + untagRequirement(tag.getId(), oldRequirement.getId()); } catch (Exception e) { e.printStackTrace(); } }); } + } - return getRequirementById(modifiedRequirement.getId(), userId); + private void checkTagChanges(Requirement modifiedRequirement) { + for (Tag tag : modifiedRequirement.getTags()) { + try { + Tag internalTag = getTagById(tag.getId()); + + // Check if tag exists (in project) + if (internalTag == null || modifiedRequirement.getProjectId() != internalTag.getProjectId()) { + tag.setProjectId(modifiedRequirement.getProjectId()); + tag = createTag(tag); + } + tagRequirement(tag.getId(), modifiedRequirement.getId()); + } catch (Exception e) { + e.printStackTrace(); + } + } } @Override From d758be2b4a66bd943665c097eee963c65a7dc68e Mon Sep 17 00:00:00 2001 From: Felix Jordan Date: Wed, 12 Oct 2022 12:00:37 +0200 Subject: [PATCH 15/42] WIP: Add gamification basics using Gamification Framework --- ...is.bazaar.service.BazaarService.properties | 5 + .../acis/bazaar/service/BazaarService.java | 18 ++- .../service/dal/entities/EntityBase.java | 17 +++ .../service/gamification/GFNotification.java | 11 ++ .../GamificationFrameworkClient.java | 105 ++++++++++++++++++ .../gamification/GamificationManager.java | 89 +++++++++++++++ .../resources/RequirementsResource.java | 6 + 7 files changed, 250 insertions(+), 1 deletion(-) create mode 100644 reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GFNotification.java create mode 100644 reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java create mode 100644 reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java diff --git a/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties b/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties index 7ce0879a..f265e440 100644 --- a/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties +++ b/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties @@ -15,3 +15,8 @@ twitterApiKey= twitterApiKeySecret= twitterClientId= twitterClientSecret= +gfGameServiceUrl= +gfVisualizationServiceUrl= +gfUsername= +gfPassword= +gfGameId= \ No newline at end of file diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java index 3bf33997..15e86498 100755 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -32,6 +32,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import de.rwth.dbis.acis.bazaar.service.gamification.GamificationManager; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import de.rwth.dbis.acis.bazaar.service.notification.ActivityDispatcher; import de.rwth.dbis.acis.bazaar.service.notification.EmailDispatcher; @@ -53,6 +54,7 @@ import i5.las2peer.restMapper.annotations.ServicePath; import io.swagger.annotations.*; import lombok.Getter; +import okhttp3.HttpUrl; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.http.client.utils.URIBuilder; import org.jooq.SQLDialect; @@ -91,6 +93,7 @@ public class BazaarService extends RESTService { private final List functionRegistrar; private final NotificationDispatcher notificationDispatcher; private final TweetDispatcher tweetDispatcher; + private final GamificationManager gamificationManager; private final DataSource dataSource; //CONFIG PROPERTIES @@ -111,6 +114,12 @@ public class BazaarService extends RESTService { protected String twitterClientId; protected String twitterClientSecret; + protected String gfGameServiceUrl; + protected String gfVisualizationServiceUrl; + protected String gfUsername; + protected String gfPassword; + protected String gfGameId; + public BazaarService() throws Exception { setFieldValues(); Locale locale = new Locale(lang, country); @@ -166,9 +175,10 @@ public BazaarService() throws Exception { } tweetDispatcher = new TweetDispatcher(this, twitterApiKey, twitterApiKeySecret, twitterClientId, twitterClientSecret); - new WeeklyNewProjectsTweetTask(this).schedule(timer); + gamificationManager = new GamificationManager(gfGameServiceUrl, gfVisualizationServiceUrl, gfUsername, gfPassword, gfGameId); + notificationDispatcher.setBazaarService(this); } @@ -236,6 +246,10 @@ public TweetDispatcher getTweetDispatcher() { return tweetDispatcher; } + public GamificationManager getGamificationManager() { + return gamificationManager; + } + private void registerUserAtFirstLogin() throws Exception { Agent agent = Context.getCurrent().getMainAgent(); @@ -274,6 +288,8 @@ private void registerUserAtFirstLogin() throws Exception { int userId = user.getId(); // this.getNotificationDispatcher().dispatchNotification(user.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_55, userId, Activity.DataType.USER, userId); dalFacade.addUserToRole(userId, "LoggedInUser", null); + + gamificationManager.initializeUser(userId); } else { // update lastLoginDate dalFacade.updateLastLoginDate(userIdByLAS2PeerId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java index df72d589..3fb4a4a4 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java @@ -20,17 +20,25 @@ package de.rwth.dbis.acis.bazaar.service.dal.entities; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import de.rwth.dbis.acis.bazaar.service.dal.helpers.SerializerViews; +import de.rwth.dbis.acis.bazaar.service.gamification.GFNotification; +import org.apache.commons.lang3.Validate; /** * @since 9/16/2014 */ public abstract class EntityBase implements IdentifiedById { + private List gamificationNotifications = new ArrayList<>(); + public String toJSON() throws JsonProcessingException { return new ObjectMapper().registerModule(new JavaTimeModule()) .setSerializationInclusion(JsonInclude.Include.NON_NULL) @@ -45,4 +53,13 @@ public String toPrivateJSON() throws JsonProcessingException { .writerWithView(SerializerViews.Private.class) .writeValueAsString(this); } + + public void setGamificationNotifications(List gamificationNotifications) { + Validate.notNull(gamificationNotifications); + gamificationNotifications = gamificationNotifications; + } + + public List getGamificationNotifications() { + return gamificationNotifications; + } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GFNotification.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GFNotification.java new file mode 100644 index 00000000..cb80ff3d --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GFNotification.java @@ -0,0 +1,11 @@ +package de.rwth.dbis.acis.bazaar.service.gamification; + +import java.util.Map; + +import lombok.Value; + +@Value +public class GFNotification { + + private Map data; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java new file mode 100644 index 00000000..e12feac3 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -0,0 +1,105 @@ +package de.rwth.dbis.acis.bazaar.service.gamification; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.MapType; +import i5.las2peer.logging.L2pLogger; +import okhttp3.*; +import org.apache.commons.lang3.Validate; + +public class GamificationFrameworkClient { + + private final L2pLogger logger = L2pLogger.getInstance(GamificationFrameworkClient.class.getName()); + + private final HttpUrl gfGameServiceUrl; + private final HttpUrl gfVisualizationServiceUrl; + + private final OkHttpClient httpClient; + private final ObjectMapper objectMapper = new ObjectMapper(); + + public GamificationFrameworkClient(String gfGameServiceUrl, String gfVisualizationServiceUrl, String gfUsername, String gfPassword) { + this.gfGameServiceUrl = HttpUrl.parse(gfGameServiceUrl); + this.gfVisualizationServiceUrl = HttpUrl.parse(gfVisualizationServiceUrl); + + httpClient = new OkHttpClient.Builder() + .authenticator((route, response) -> { + if (response.request().header("Authorization") != null) { + return null; + } + String credential = Credentials.basic(gfUsername, gfPassword); + return response.request().newBuilder() + .header("Authorization", credential) + .build(); + }) + .build(); + } + + public void addMemberToGame(String gameId, String memberUsername) throws IOException { + Validate.notBlank(gameId); + Validate.notBlank(memberUsername); + + Request request = new Request.Builder() + .url(gfGameServiceUrl.newBuilder() + .addPathSegment("data") + .addPathSegment(gameId) + .addPathSegment(memberUsername) + .build() + ) + .method("POST", null) + .build(); + + try (Response response = httpClient.newCall(request).execute()) { + if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + + logger.info("Added member " + memberUsername + " to game " + gameId + " (response: " + response.body().string() + ")"); + } + } + + public List triggerAction(String gameId, String actionId, String username) throws IOException { + Validate.notBlank(gameId); + Validate.notBlank(actionId); + Validate.notBlank(username); + + Request request = new Request.Builder() + .url(gfVisualizationServiceUrl.newBuilder() + .addPathSegment("actions") + .addPathSegment(gameId) + .addPathSegment(actionId) + .addPathSegment(username) + .build() + ) + .method("POST", null) + .build(); + + try (Response response = httpClient.newCall(request).execute()) { + if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + + String rawResponse = response.body().string(); + logger.info("Triggered action " + actionId + " on game " + gameId + " for user " + username + " (response: " + rawResponse + ")"); + + final MapType mapType = objectMapper.getTypeFactory().constructMapType( + Map.class, String.class, Object.class); + Map responseJson = objectMapper.readValue(rawResponse, mapType); + + // process notifications + List notifications = new ArrayList<>(); + if (responseJson.containsKey("notification")) { + Object notificationRoot = responseJson.get("notification"); + if (notificationRoot instanceof List) { + ((List) notificationRoot).forEach(notificationJson -> { + notifications.add(new GFNotification((Map) notificationJson)); + }); + } else if (notificationRoot instanceof Map) { + notifications.add(new GFNotification((Map) notificationRoot)); + } else { + logger.warning("Unexpected value of 'notification' object: " + notificationRoot); + } + } + return notifications; + } + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java new file mode 100644 index 00000000..b4ccfee8 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -0,0 +1,89 @@ +package de.rwth.dbis.acis.bazaar.service.gamification; + +import java.io.IOException; +import java.util.*; + +import i5.las2peer.logging.L2pLogger; +import org.apache.commons.lang3.StringUtils; + +public class GamificationManager { + + private final L2pLogger logger = L2pLogger.getInstance(GamificationManager.class.getName()); + + private final GamificationFrameworkClient gfClient; + private final String gfGameId; + + /** + * Notifications returned by the framework during request processing. + * + * Can be returned to the client by querying + */ + private Map> notificationCache = new HashMap<>(); + + public GamificationManager(String gfGameServiceUrl, String gfVisualizationServiceUrl, String gfUsername, String gfPassword, String gfGameId) { + this.gfGameId = gfGameId; + + if (StringUtils.isAnyBlank(gfGameServiceUrl, gfVisualizationServiceUrl, gfUsername, gfPassword, gfGameId)) { + logger.warning("Gamification functionality cannot be used without GamificationFramework credentials!"); + gfClient = null; + } else { + gfClient = new GamificationFrameworkClient(gfGameServiceUrl, gfVisualizationServiceUrl, gfUsername, gfPassword); + } + } + + public void initializeUser(Integer userId) { + if (!isAvailable()) { + logger.warning("Cannot add user to Gamification Framework. Gamification is not configured"); + return; + } + + try { + gfClient.addMemberToGame(gfGameId, userId.toString()); + } catch (IOException e) { + logger.warning("Failed to add user to gamification framework: " + e.getMessage()); + e.printStackTrace(); + } + } + + public void triggerCreateRequirementAction(Integer userId) { + triggerActionIfGamificationAvailable(Actions.CREATE_REQUIREMENT, userId); + } + + private void triggerActionIfGamificationAvailable(String actionId, Integer userId) { + if (!isAvailable()) { + logger.warning("Cannot trigger action " + actionId + ". Gamification is not configured"); + return; + } + + try { + List notifications = gfClient.triggerAction(gfGameId, actionId, userId.toString()); + storeUserNotifications(userId, notifications); + } catch (IOException e) { + logger.warning("Failed to trigger action " + actionId + " for user " + userId); + e.printStackTrace(); + } + } + + public List getUserNotifications(Integer userId) { + if (notificationCache.containsKey(userId)) { + return Collections.unmodifiableList(notificationCache.get(userId)); + } + return Collections.emptyList(); + } + + private void storeUserNotifications(Integer userId, List notifications) { + if (notificationCache.containsKey(userId)) { + notificationCache.get(userId).addAll(notifications); + } else { + notificationCache.put(userId, new ArrayList<>(notifications)); + } + } + + private boolean isAvailable() { + return gfClient != null; + } + + private static class Actions { + private static final String CREATE_REQUIREMENT = "create_req"; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index 290019ef..394ad764 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -323,6 +323,12 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir createdRequirement = dalFacade.getRequirementById(createdRequirement.getId(), internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_26, createdRequirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); + + // trigger Gamification Framework + bazaarService.getGamificationManager().triggerCreateRequirementAction(internalUserId); + // add notifications to response + createdRequirement.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); + return Response.status(Response.Status.CREATED).entity(createdRequirement.toJSON()).build(); } catch (BazaarException bex) { return resourceHelper.handleBazaarException(bex, "Create requirement", logger); From 23c1ed2945df0e45a2a4664b790092cac1e66f63 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 24 Jan 2023 10:20:02 +0100 Subject: [PATCH 16/42] fix: resolve errors in BazaarTest caused by gamification field --- .../dbis/acis/bazaar/service/BazaarTest.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/BazaarTest.java b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/BazaarTest.java index f13c7c46..1441a89b 100644 --- a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/BazaarTest.java +++ b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/BazaarTest.java @@ -252,6 +252,14 @@ public void testRequirements() { assertTrue(isValidISO8601(createdRequirement.get("creationDate").toString().replace("\"", ""))); assertTrue(isValidISO8601(createdRequirement.get("lastActivity").toString().replace("\"", ""))); + // remove gamification notification fields + createdRequirement.remove("gamificationNotifications"); + createdRequirement.getAsJsonObject("creator").remove("gamificationNotifications"); + createdRequirement.getAsJsonObject("lastUpdatingUser").remove("gamificationNotifications"); + createdRequirement.getAsJsonObject("lastActivityUser").remove("gamificationNotifications"); + createdRequirement.getAsJsonObject("userContext").remove("gamificationNotifications"); + createdRequirement.getAsJsonArray("tags").get(0).getAsJsonObject().remove("gamificationNotifications"); + // Test update createdRequirement.addProperty("description", "Updated Description"); createdRequirement.add("attachments", JsonParser.parseString("[{ \"name\": \"wine.jpg\", \"mimeType\": \"image/jpeg\", \"identifier\": \"06e42de9-fc36-4d31-b341-09f01d012d9c\", \"fileUrl\": \"http://localhost/files/06e42de9-fc36-4d31-b341-09f01d012d9c\"}]")); @@ -501,6 +509,9 @@ public void testComments() { // Test update response.addProperty("message", "Updated message"); + // remove gamificationNotifications field for request + response.remove("gamificationNotifications"); + response.getAsJsonObject("creator").remove("gamificationNotifications"); result = client.sendRequest("PUT", mainPath + "comments", response.toString(), MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); assertEquals(200, result.getHttpCode()); @@ -544,11 +555,17 @@ public void testTags() { JsonElement resp = JsonParser.parseString(result.getResponse()); JsonObject requirement = resp.getAsJsonObject(); + // remove gamification notification fields + requirement.remove("gamificationNotifications"); + requirement.getAsJsonObject("creator").remove("gamificationNotifications"); + requirement.getAsJsonObject("lastUpdatingUser").remove("gamificationNotifications"); + requirement.getAsJsonObject("lastActivityUser").remove("gamificationNotifications"); + requirement.getAsJsonObject("userContext").remove("gamificationNotifications"); + // Create Tag array and add it to the JsonObject JsonArray newTags = JsonParser.parseString(String.format("[{\"id\": %s, \"name\": \"Feature\", \"colour\": \"#00FF00\"}, {\"name\": \"Test\", \"colour\": \"#0000FF\"}]", tagId)).getAsJsonArray(); requirement.add("tags", newTags); - result = adminClient.sendRequest("PUT", mainPath + "requirements", requirement.toString(), MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); System.out.println(result.getResponse()); From ae57611d1bd924630774da53f136e578f62af6de Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 1 Feb 2023 11:57:31 +0100 Subject: [PATCH 17/42] register new users in gamification framework --- .../acis/bazaar/service/BazaarService.java | 4 +- .../GamificationFrameworkClient.java | 40 +++++++++++++++---- .../gamification/GamificationManager.java | 11 ++--- 3 files changed, 40 insertions(+), 15 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java index 15e86498..daf14da3 100755 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -53,8 +53,6 @@ import i5.las2peer.restMapper.RESTService; import i5.las2peer.restMapper.annotations.ServicePath; import io.swagger.annotations.*; -import lombok.Getter; -import okhttp3.HttpUrl; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.http.client.utils.URIBuilder; import org.jooq.SQLDialect; @@ -289,7 +287,7 @@ private void registerUserAtFirstLogin() throws Exception { // this.getNotificationDispatcher().dispatchNotification(user.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_55, userId, Activity.DataType.USER, userId); dalFacade.addUserToRole(userId, "LoggedInUser", null); - gamificationManager.initializeUser(userId); + gamificationManager.initializeUser(userId, email); } else { // update lastLoginDate dalFacade.updateLastLoginDate(userIdByLAS2PeerId); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java index e12feac3..8131dbcf 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -1,16 +1,16 @@ package de.rwth.dbis.acis.bazaar.service.gamification; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.MapType; import i5.las2peer.logging.L2pLogger; import okhttp3.*; import org.apache.commons.lang3.Validate; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + public class GamificationFrameworkClient { private final L2pLogger logger = L2pLogger.getInstance(GamificationFrameworkClient.class.getName()); @@ -49,7 +49,7 @@ public void addMemberToGame(String gameId, String memberUsername) throws IOExcep .addPathSegment(memberUsername) .build() ) - .method("POST", null) + .method("POST", RequestBody.create("", null)) .build(); try (Response response = httpClient.newCall(request).execute()) { @@ -59,6 +59,32 @@ public void addMemberToGame(String gameId, String memberUsername) throws IOExcep } } + public void registerUser(String gameId, String memberUsername, String email) throws IOException { + Validate.notBlank(gameId); + Validate.notBlank(memberUsername); + Validate.notBlank(email); + + RequestBody requestBody = new MultipartBody.Builder() + .setType(MultipartBody.FORM) + .addFormDataPart("memberId", memberUsername) + .addFormDataPart("email", email) + .build(); + + Request request = new Request.Builder() + .url(gfGameServiceUrl.newBuilder() + .addPathSegment("register") + .build() + ) + .post(requestBody) + .build(); + + try (Response response = httpClient.newCall(request).execute()) { + if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + + logger.info("Added member " + memberUsername + " to gamification." + " (response: " + response.body().string() + ")"); + } + } + public List triggerAction(String gameId, String actionId, String username) throws IOException { Validate.notBlank(gameId); Validate.notBlank(actionId); @@ -72,7 +98,7 @@ public List triggerAction(String gameId, String actionId, String .addPathSegment(username) .build() ) - .method("POST", null) + .method("POST", RequestBody.create("", null)) .build(); try (Response response = httpClient.newCall(request).execute()) { diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index b4ccfee8..2fb8966a 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -1,11 +1,11 @@ package de.rwth.dbis.acis.bazaar.service.gamification; -import java.io.IOException; -import java.util.*; - import i5.las2peer.logging.L2pLogger; import org.apache.commons.lang3.StringUtils; +import java.io.IOException; +import java.util.*; + public class GamificationManager { private final L2pLogger logger = L2pLogger.getInstance(GamificationManager.class.getName()); @@ -31,13 +31,14 @@ public GamificationManager(String gfGameServiceUrl, String gfVisualizationServic } } - public void initializeUser(Integer userId) { + public void initializeUser(Integer userId, String userEmail) { if (!isAvailable()) { logger.warning("Cannot add user to Gamification Framework. Gamification is not configured"); return; } try { + gfClient.registerUser(gfGameId, userId.toString(), userEmail); gfClient.addMemberToGame(gfGameId, userId.toString()); } catch (IOException e) { logger.warning("Failed to add user to gamification framework: " + e.getMessage()); @@ -66,7 +67,7 @@ private void triggerActionIfGamificationAvailable(String actionId, Integer userI public List getUserNotifications(Integer userId) { if (notificationCache.containsKey(userId)) { - return Collections.unmodifiableList(notificationCache.get(userId)); + return Collections.unmodifiableList(notificationCache.remove(userId)); } return Collections.emptyList(); } From 495a6b745c55074bf4cf7f68f45ca3397a752846 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 1 Feb 2023 11:58:00 +0100 Subject: [PATCH 18/42] fix: save notification in entity --- .../acis/bazaar/service/dal/entities/EntityBase.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java index 3fb4a4a4..df74e56c 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java @@ -20,10 +20,6 @@ package de.rwth.dbis.acis.bazaar.service.dal.entities; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -32,6 +28,9 @@ import de.rwth.dbis.acis.bazaar.service.gamification.GFNotification; import org.apache.commons.lang3.Validate; +import java.util.ArrayList; +import java.util.List; + /** * @since 9/16/2014 */ @@ -56,7 +55,7 @@ public String toPrivateJSON() throws JsonProcessingException { public void setGamificationNotifications(List gamificationNotifications) { Validate.notNull(gamificationNotifications); - gamificationNotifications = gamificationNotifications; + this.gamificationNotifications = gamificationNotifications; } public List getGamificationNotifications() { From 503c5aa554b403204cfafcce05e9095a43f58122 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Mon, 6 Feb 2023 12:00:42 +0100 Subject: [PATCH 19/42] changed notification array --- .../acis/bazaar/service/dal/entities/EntityBase.java | 8 ++++---- .../gamification/GamificationFrameworkClient.java | 10 ++++------ .../service/gamification/GamificationManager.java | 10 +++++----- 3 files changed, 13 insertions(+), 15 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java index df74e56c..267251f2 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java @@ -25,18 +25,18 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import de.rwth.dbis.acis.bazaar.service.dal.helpers.SerializerViews; -import de.rwth.dbis.acis.bazaar.service.gamification.GFNotification; import org.apache.commons.lang3.Validate; import java.util.ArrayList; import java.util.List; +import java.util.Map; /** * @since 9/16/2014 */ public abstract class EntityBase implements IdentifiedById { - private List gamificationNotifications = new ArrayList<>(); + private List> gamificationNotifications = new ArrayList<>(); public String toJSON() throws JsonProcessingException { return new ObjectMapper().registerModule(new JavaTimeModule()) @@ -53,12 +53,12 @@ public String toPrivateJSON() throws JsonProcessingException { .writeValueAsString(this); } - public void setGamificationNotifications(List gamificationNotifications) { + public void setGamificationNotifications(List> gamificationNotifications) { Validate.notNull(gamificationNotifications); this.gamificationNotifications = gamificationNotifications; } - public List getGamificationNotifications() { + public List> getGamificationNotifications() { return gamificationNotifications; } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java index 8131dbcf..262c95f1 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -85,7 +85,7 @@ public void registerUser(String gameId, String memberUsername, String email) thr } } - public List triggerAction(String gameId, String actionId, String username) throws IOException { + public List> triggerAction(String gameId, String actionId, String username) throws IOException { Validate.notBlank(gameId); Validate.notBlank(actionId); Validate.notBlank(username); @@ -112,15 +112,13 @@ public List triggerAction(String gameId, String actionId, String Map responseJson = objectMapper.readValue(rawResponse, mapType); // process notifications - List notifications = new ArrayList<>(); + List> notifications = new ArrayList<>(); if (responseJson.containsKey("notification")) { Object notificationRoot = responseJson.get("notification"); if (notificationRoot instanceof List) { - ((List) notificationRoot).forEach(notificationJson -> { - notifications.add(new GFNotification((Map) notificationJson)); - }); + ((List) notificationRoot).forEach(notificationJson -> notifications.add((Map) notificationJson)); } else if (notificationRoot instanceof Map) { - notifications.add(new GFNotification((Map) notificationRoot)); + notifications.add((Map) notificationRoot); } else { logger.warning("Unexpected value of 'notification' object: " + notificationRoot); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index 2fb8966a..b329e4da 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -15,10 +15,10 @@ public class GamificationManager { /** * Notifications returned by the framework during request processing. - * + *

* Can be returned to the client by querying */ - private Map> notificationCache = new HashMap<>(); + private Map>> notificationCache = new HashMap<>(); public GamificationManager(String gfGameServiceUrl, String gfVisualizationServiceUrl, String gfUsername, String gfPassword, String gfGameId) { this.gfGameId = gfGameId; @@ -57,7 +57,7 @@ private void triggerActionIfGamificationAvailable(String actionId, Integer userI } try { - List notifications = gfClient.triggerAction(gfGameId, actionId, userId.toString()); + List> notifications = gfClient.triggerAction(gfGameId, actionId, userId.toString()); storeUserNotifications(userId, notifications); } catch (IOException e) { logger.warning("Failed to trigger action " + actionId + " for user " + userId); @@ -65,14 +65,14 @@ private void triggerActionIfGamificationAvailable(String actionId, Integer userI } } - public List getUserNotifications(Integer userId) { + public List> getUserNotifications(Integer userId) { if (notificationCache.containsKey(userId)) { return Collections.unmodifiableList(notificationCache.remove(userId)); } return Collections.emptyList(); } - private void storeUserNotifications(Integer userId, List notifications) { + private void storeUserNotifications(Integer userId, List> notifications) { if (notificationCache.containsKey(userId)) { notificationCache.get(userId).addAll(notifications); } else { From de62ef67d9141195d064ed5cd5653edf1f335203 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 7 Feb 2023 08:51:10 +0100 Subject: [PATCH 20/42] only send notification field if not empty --- .../dbis/acis/bazaar/service/dal/entities/EntityBase.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java index 267251f2..7a5aa8ff 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java @@ -27,7 +27,6 @@ import de.rwth.dbis.acis.bazaar.service.dal.helpers.SerializerViews; import org.apache.commons.lang3.Validate; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -36,7 +35,7 @@ */ public abstract class EntityBase implements IdentifiedById { - private List> gamificationNotifications = new ArrayList<>(); + private List> gamificationNotifications; public String toJSON() throws JsonProcessingException { return new ObjectMapper().registerModule(new JavaTimeModule()) @@ -55,7 +54,8 @@ public String toPrivateJSON() throws JsonProcessingException { public void setGamificationNotifications(List> gamificationNotifications) { Validate.notNull(gamificationNotifications); - this.gamificationNotifications = gamificationNotifications; + // prevent field to be sent if its empty + this.gamificationNotifications = gamificationNotifications.size() == 0 ? null : gamificationNotifications; } public List> getGamificationNotifications() { From 4e07ecc863009ac3905837cd15a470d6a5622e54 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 7 Feb 2023 11:22:05 +0100 Subject: [PATCH 21/42] get badges of a user --- .../service/dal/entities/Dashboard.java | 5 ++-- .../GamificationFrameworkClient.java | 26 +++++++++++++++++++ .../gamification/GamificationManager.java | 13 +++++++++- .../service/resources/UsersResource.java | 20 ++++++++++++-- 4 files changed, 59 insertions(+), 5 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java index 40ba5361..17498a65 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java @@ -1,8 +1,6 @@ package de.rwth.dbis.acis.bazaar.service.dal.entities; import com.fasterxml.jackson.annotation.JsonIgnore; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.UserVote; -import io.swagger.annotations.ApiModelProperty; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; @@ -10,6 +8,7 @@ import javax.validation.constraints.NotNull; import java.util.List; +import java.util.Map; @EqualsAndHashCode(callSuper = true) @Data @@ -26,6 +25,8 @@ public class Dashboard extends EntityBase { @NotNull private List requirements; + private List> badges; + @JsonIgnore @Override public int getId() { diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java index 262c95f1..e5cab5ba 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -1,6 +1,7 @@ package de.rwth.dbis.acis.bazaar.service.gamification; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.CollectionType; import com.fasterxml.jackson.databind.type.MapType; import i5.las2peer.logging.L2pLogger; import okhttp3.*; @@ -126,4 +127,29 @@ public List> triggerAction(String gameId, String actionId, S return notifications; } } + + public List> getEarnedBadges(String gameId, String userId) throws IOException { + + Request request = new Request.Builder() + .url(gfVisualizationServiceUrl.newBuilder() + .addPathSegment("badges") + .addPathSegment(gameId) + .addPathSegment(userId) + .build() + ) + .get() + .build(); + + try (Response response = httpClient.newCall(request).execute()) { + if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + + String rawResponse = response.body().string(); + logger.info("Triggered getBadges " + gameId + " for user " + userId + " (response: " + rawResponse + ")"); + + final CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class); + List> badges = objectMapper.readValue(rawResponse, collectionType); + + return badges; + } + } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index b329e4da..e95784dd 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -80,7 +80,18 @@ private void storeUserNotifications(Integer userId, List> no } } - private boolean isAvailable() { + public List> getUserBadges(Integer userId) { + try { + List> badges = gfClient.getEarnedBadges(gfGameId, userId.toString()); + return badges; + } catch (IOException e) { + logger.warning("Failed to get badges for user " + userId); + e.printStackTrace(); + return Collections.emptyList(); + } + } + + public boolean isAvailable() { return gfClient != null; } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java index 3bafd298..d7ce1fbd 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java @@ -1,5 +1,7 @@ package de.rwth.dbis.acis.bazaar.service.resources; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; @@ -211,10 +213,14 @@ public Response getUserDashboard() { Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_54, internalUserId, Activity.DataType.USER, internalUserId); - + boolean isGamified = bazaarService.getGamificationManager().isAvailable(); Dashboard data = dalFacade.getDashboardData(internalUserId, 10); + if (isGamified) { + data.setBadges(bazaarService.getGamificationManager().getUserBadges(internalUserId)); + } + String dashboardResponse = getDashboardResponse(isGamified, data); - return Response.ok(data.toJSON()).build(); + return Response.ok(dashboardResponse).build(); } catch (BazaarException bex) { return resourceHelper.handleBazaarException(bex, "Get active user", logger); } catch (Exception ex) { @@ -224,6 +230,16 @@ public Response getUserDashboard() { } } + private static String getDashboardResponse(boolean isGamified, Dashboard data) throws JsonProcessingException { + String dashboardResponse = data.toJSON(); + + ObjectMapper mapper = new ObjectMapper(); + Map map = (Map) mapper.readValue(dashboardResponse, Map.class); + map.put("isGamified", String.valueOf(isGamified)); + dashboardResponse = mapper.writeValueAsString(map); + return dashboardResponse; + } + /** * Allows to update a certain user. * From 17b78ceff35dda0b517b5271be1883b2bedc2e26 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 14 Feb 2023 10:13:20 +0100 Subject: [PATCH 22/42] get badges imgs --- .../acis/bazaar/service/BazaarService.java | 5 +- .../GamificationFrameworkClient.java | 50 +++++++++++++++---- .../gamification/GamificationManager.java | 6 +-- 3 files changed, 45 insertions(+), 16 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java index daf14da3..802778a7 100755 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -112,8 +112,7 @@ public class BazaarService extends RESTService { protected String twitterClientId; protected String twitterClientSecret; - protected String gfGameServiceUrl; - protected String gfVisualizationServiceUrl; + protected String gfBaseUrl; protected String gfUsername; protected String gfPassword; protected String gfGameId; @@ -175,7 +174,7 @@ public BazaarService() throws Exception { tweetDispatcher = new TweetDispatcher(this, twitterApiKey, twitterApiKeySecret, twitterClientId, twitterClientSecret); new WeeklyNewProjectsTweetTask(this).schedule(timer); - gamificationManager = new GamificationManager(gfGameServiceUrl, gfVisualizationServiceUrl, gfUsername, gfPassword, gfGameId); + gamificationManager = new GamificationManager(gfBaseUrl, gfUsername, gfPassword, gfGameId); notificationDispatcher.setBazaarService(this); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java index e5cab5ba..978c7a24 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -16,15 +16,12 @@ public class GamificationFrameworkClient { private final L2pLogger logger = L2pLogger.getInstance(GamificationFrameworkClient.class.getName()); - private final HttpUrl gfGameServiceUrl; - private final HttpUrl gfVisualizationServiceUrl; - + private final HttpUrl gfBaseUrl; private final OkHttpClient httpClient; private final ObjectMapper objectMapper = new ObjectMapper(); - public GamificationFrameworkClient(String gfGameServiceUrl, String gfVisualizationServiceUrl, String gfUsername, String gfPassword) { - this.gfGameServiceUrl = HttpUrl.parse(gfGameServiceUrl); - this.gfVisualizationServiceUrl = HttpUrl.parse(gfVisualizationServiceUrl); + public GamificationFrameworkClient(String gfBaseUrl, String gfUsername, String gfPassword) { + this.gfBaseUrl = HttpUrl.parse(gfBaseUrl); httpClient = new OkHttpClient.Builder() .authenticator((route, response) -> { @@ -44,7 +41,8 @@ public void addMemberToGame(String gameId, String memberUsername) throws IOExcep Validate.notBlank(memberUsername); Request request = new Request.Builder() - .url(gfGameServiceUrl.newBuilder() + .url(gfBaseUrl.newBuilder() + .addPathSegment("games") .addPathSegment("data") .addPathSegment(gameId) .addPathSegment(memberUsername) @@ -72,7 +70,8 @@ public void registerUser(String gameId, String memberUsername, String email) thr .build(); Request request = new Request.Builder() - .url(gfGameServiceUrl.newBuilder() + .url(gfBaseUrl.newBuilder() + .addPathSegment("games") .addPathSegment("register") .build() ) @@ -92,7 +91,8 @@ public List> triggerAction(String gameId, String actionId, S Validate.notBlank(username); Request request = new Request.Builder() - .url(gfVisualizationServiceUrl.newBuilder() + .url(gfBaseUrl.newBuilder() + .addPathSegment("visualization") .addPathSegment("actions") .addPathSegment(gameId) .addPathSegment(actionId) @@ -131,7 +131,8 @@ public List> triggerAction(String gameId, String actionId, S public List> getEarnedBadges(String gameId, String userId) throws IOException { Request request = new Request.Builder() - .url(gfVisualizationServiceUrl.newBuilder() + .url(gfBaseUrl.newBuilder() + .addPathSegment("visualization") .addPathSegment("badges") .addPathSegment(gameId) .addPathSegment(userId) @@ -148,8 +149,37 @@ public List> getEarnedBadges(String gameId, String userId) t final CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class); List> badges = objectMapper.readValue(rawResponse, collectionType); + badges = getBadgeImgs(gameId, badges); return badges; } } + + public List> getBadgeImgs(String gameId, List> badges) throws IOException { + + for (Map badge : badges) { + if (badge.containsKey("id")) { + Request request = new Request.Builder() + .url(gfBaseUrl.newBuilder() + .addPathSegment("badges") + .addPathSegment(gameId) + .addPathSegment(badge.get("id").toString()) + .addPathSegment("img") + .build() + ) + .get() + .build(); + + try (Response response = httpClient.newCall(request).execute()) { + if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + byte[] img = response.body().bytes(); + logger.info("Triggered getBadgeImgs " + gameId); + badge.put("img", img); + } + } + + } + return badges; + } + } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index e95784dd..e41ab3c6 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -20,14 +20,14 @@ public class GamificationManager { */ private Map>> notificationCache = new HashMap<>(); - public GamificationManager(String gfGameServiceUrl, String gfVisualizationServiceUrl, String gfUsername, String gfPassword, String gfGameId) { + public GamificationManager(String gfBaseUrl, String gfUsername, String gfPassword, String gfGameId) { this.gfGameId = gfGameId; - if (StringUtils.isAnyBlank(gfGameServiceUrl, gfVisualizationServiceUrl, gfUsername, gfPassword, gfGameId)) { + if (StringUtils.isAnyBlank(gfBaseUrl, gfUsername, gfPassword, gfGameId)) { logger.warning("Gamification functionality cannot be used without GamificationFramework credentials!"); gfClient = null; } else { - gfClient = new GamificationFrameworkClient(gfGameServiceUrl, gfVisualizationServiceUrl, gfUsername, gfPassword); + gfClient = new GamificationFrameworkClient(gfBaseUrl, gfUsername, gfPassword); } } From 7f5a2c8c570fc3a9e9f5060e5af89b903bcec5a6 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 14 Feb 2023 10:51:46 +0100 Subject: [PATCH 23/42] refactor: reduce complexity in Gamification --- .../GamificationFrameworkClient.java | 81 ++++++++++--------- .../gamification/GamificationManager.java | 4 +- 2 files changed, 45 insertions(+), 40 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java index 978c7a24..d2696ba9 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Objects; public class GamificationFrameworkClient { @@ -52,8 +53,7 @@ public void addMemberToGame(String gameId, String memberUsername) throws IOExcep .build(); try (Response response = httpClient.newCall(request).execute()) { - if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); - + checkSuccess(response); logger.info("Added member " + memberUsername + " to game " + gameId + " (response: " + response.body().string() + ")"); } } @@ -79,8 +79,7 @@ public void registerUser(String gameId, String memberUsername, String email) thr .build(); try (Response response = httpClient.newCall(request).execute()) { - if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); - + checkSuccess(response); logger.info("Added member " + memberUsername + " to gamification." + " (response: " + response.body().string() + ")"); } } @@ -103,7 +102,7 @@ public List> triggerAction(String gameId, String actionId, S .build(); try (Response response = httpClient.newCall(request).execute()) { - if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + checkSuccess(response); String rawResponse = response.body().string(); logger.info("Triggered action " + actionId + " on game " + gameId + " for user " + username + " (response: " + rawResponse + ")"); @@ -112,23 +111,28 @@ public List> triggerAction(String gameId, String actionId, S Map.class, String.class, Object.class); Map responseJson = objectMapper.readValue(rawResponse, mapType); - // process notifications - List> notifications = new ArrayList<>(); - if (responseJson.containsKey("notification")) { - Object notificationRoot = responseJson.get("notification"); - if (notificationRoot instanceof List) { - ((List) notificationRoot).forEach(notificationJson -> notifications.add((Map) notificationJson)); - } else if (notificationRoot instanceof Map) { - notifications.add((Map) notificationRoot); - } else { - logger.warning("Unexpected value of 'notification' object: " + notificationRoot); - } + return getNotifications(responseJson); + } + } + + private List> getNotifications(Map responseJson) { + List> notifications = new ArrayList<>(); + if (responseJson.containsKey("notification")) { + Object notificationRoot = responseJson.get("notification"); + if (notificationRoot instanceof List) { + ((List) notificationRoot).forEach(notificationJson -> notifications.add((Map) notificationJson)); + } else if (notificationRoot instanceof Map) { + notifications.add((Map) notificationRoot); + } else { + logger.warning("Unexpected value of 'notification' object: " + notificationRoot); } - return notifications; } + return notifications; } public List> getEarnedBadges(String gameId, String userId) throws IOException { + Validate.notBlank(gameId); + Validate.notBlank(userId); Request request = new Request.Builder() .url(gfBaseUrl.newBuilder() @@ -142,9 +146,9 @@ public List> getEarnedBadges(String gameId, String userId) t .build(); try (Response response = httpClient.newCall(request).execute()) { - if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + checkSuccess(response); - String rawResponse = response.body().string(); + String rawResponse = Objects.requireNonNull(response.body()).string(); logger.info("Triggered getBadges " + gameId + " for user " + userId + " (response: " + rawResponse + ")"); final CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class); @@ -158,28 +162,31 @@ public List> getEarnedBadges(String gameId, String userId) t public List> getBadgeImgs(String gameId, List> badges) throws IOException { for (Map badge : badges) { - if (badge.containsKey("id")) { - Request request = new Request.Builder() - .url(gfBaseUrl.newBuilder() - .addPathSegment("badges") - .addPathSegment(gameId) - .addPathSegment(badge.get("id").toString()) - .addPathSegment("img") - .build() - ) - .get() - .build(); - - try (Response response = httpClient.newCall(request).execute()) { - if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); - byte[] img = response.body().bytes(); - logger.info("Triggered getBadgeImgs " + gameId); - badge.put("img", img); - } + Request request = new Request.Builder() + .url(gfBaseUrl.newBuilder() + .addPathSegment("badges") + .addPathSegment(gameId) + .addPathSegment(badge.get("id").toString()) + .addPathSegment("img") + .build() + ) + .get() + .build(); + + try (Response response = httpClient.newCall(request).execute()) { + checkSuccess(response); + byte[] img = response.body().bytes(); + logger.info("Triggered getBadgeImgs " + gameId); + badge.put("img", img); } + } return badges; } + private static void checkSuccess(Response response) throws IOException { + if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + } + } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index e41ab3c6..c47ae2c9 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -55,7 +55,6 @@ private void triggerActionIfGamificationAvailable(String actionId, Integer userI logger.warning("Cannot trigger action " + actionId + ". Gamification is not configured"); return; } - try { List> notifications = gfClient.triggerAction(gfGameId, actionId, userId.toString()); storeUserNotifications(userId, notifications); @@ -82,8 +81,7 @@ private void storeUserNotifications(Integer userId, List> no public List> getUserBadges(Integer userId) { try { - List> badges = gfClient.getEarnedBadges(gfGameId, userId.toString()); - return badges; + return gfClient.getEarnedBadges(gfGameId, userId.toString()); } catch (IOException e) { logger.warning("Failed to get badges for user " + userId); e.printStackTrace(); From 55cc704e0534bb531769fe6f19926e882cfa8a5a Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 22 Feb 2023 11:32:09 +0100 Subject: [PATCH 24/42] added user status to dashboard --- .../service/dal/entities/Dashboard.java | 2 ++ .../GamificationFrameworkClient.java | 26 +++++++++++++++++++ .../gamification/GamificationManager.java | 11 ++++++++ .../service/resources/UsersResource.java | 1 + 4 files changed, 40 insertions(+) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java index 17498a65..4a31a5f1 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java @@ -27,6 +27,8 @@ public class Dashboard extends EntityBase { private List> badges; + private Map status; + @JsonIgnore @Override public int getId() { diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java index 978c7a24..723fe127 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -182,4 +182,30 @@ public List> getBadgeImgs(String gameId, List getMemberStatus(String gameId, String userId) throws IOException { + + Request request = new Request.Builder() + .url(gfBaseUrl.newBuilder() + .addPathSegment("visualization") + .addPathSegment("status") + .addPathSegment(gameId) + .addPathSegment(userId) + .build() + ) + .get() + .build(); + + try (Response response = httpClient.newCall(request).execute()) { + if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + + String rawResponse = response.body().string(); + logger.info("Triggered get status " + gameId + " for user " + userId + " (response: " + rawResponse + ")"); + + final MapType mapType = objectMapper.getTypeFactory().constructMapType( + Map.class, String.class, Object.class); + + return objectMapper.readValue(rawResponse, mapType); + } + } + } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index e41ab3c6..06a67c0d 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -91,6 +91,17 @@ public List> getUserBadges(Integer userId) { } } + public Map getUserStatus(Integer userId) { + try { + Map status = gfClient.getMemberStatus(gfGameId, userId.toString()); + return status; + } catch (IOException e) { + logger.warning("Failed to get status for user " + userId); + e.printStackTrace(); + return Collections.emptyMap(); + } + } + public boolean isAvailable() { return gfClient != null; } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java index d7ce1fbd..6009aff1 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java @@ -217,6 +217,7 @@ public Response getUserDashboard() { Dashboard data = dalFacade.getDashboardData(internalUserId, 10); if (isGamified) { data.setBadges(bazaarService.getGamificationManager().getUserBadges(internalUserId)); + data.setStatus(bazaarService.getGamificationManager().getUserStatus(internalUserId)); } String dashboardResponse = getDashboardResponse(isGamified, data); From ceb19c8b7b6cc8ffc35cebaf7f01716ec6b30c8c Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 22 Feb 2023 11:37:15 +0100 Subject: [PATCH 25/42] added checkSuccess method --- .../service/gamification/GamificationFrameworkClient.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java index 3a2dfc3e..0d68ad63 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -104,7 +104,7 @@ public List> triggerAction(String gameId, String actionId, S try (Response response = httpClient.newCall(request).execute()) { checkSuccess(response); - String rawResponse = response.body().string(); + String rawResponse = Objects.requireNonNull(response.body()).string(); logger.info("Triggered action " + actionId + " on game " + gameId + " for user " + username + " (response: " + rawResponse + ")"); final MapType mapType = objectMapper.getTypeFactory().constructMapType( @@ -175,7 +175,7 @@ public List> getBadgeImgs(String gameId, List getMemberStatus(String gameId, String userId) throws .build(); try (Response response = httpClient.newCall(request).execute()) { - if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); + checkSuccess(response); - String rawResponse = response.body().string(); + String rawResponse = Objects.requireNonNull(response.body()).string(); logger.info("Triggered get status " + gameId + " for user " + userId + " (response: " + rawResponse + ")"); final MapType mapType = objectMapper.getTypeFactory().constructMapType( From 34dd09eea05ecb5c07fcbc165cd0bc6a57958b5f Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 28 Feb 2023 11:13:30 +0100 Subject: [PATCH 26/42] added more actions --- .../gamification/GamificationManager.java | 22 +++++++++++++++++++ .../service/resources/CommentsResource.java | 4 ++++ .../service/resources/ProjectsResource.java | 4 ++++ .../resources/RequirementsResource.java | 8 +++++++ 4 files changed, 38 insertions(+) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index 2d4d75f7..9e699f96 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -50,6 +50,23 @@ public void triggerCreateRequirementAction(Integer userId) { triggerActionIfGamificationAvailable(Actions.CREATE_REQUIREMENT, userId); } + public void triggerComplete_RequirementAction(Integer userId) { + triggerActionIfGamificationAvailable(Actions.COMPLETE_REQUIREMENT, userId); + } + + public void triggerCreateProjectAction(Integer userId) { + triggerActionIfGamificationAvailable(Actions.CREATE_PROJECT, userId); + } + + public void triggerCreateCommentAction(Integer userId) { + triggerActionIfGamificationAvailable(Actions.CREATE_COMMENT, userId); + } + + public void triggerVoteAction(Integer userId) { + triggerActionIfGamificationAvailable(Actions.VOTE_REQUIREMENT, userId); + } + + private void triggerActionIfGamificationAvailable(String actionId, Integer userId) { if (!isAvailable()) { logger.warning("Cannot trigger action " + actionId + ". Gamification is not configured"); @@ -106,5 +123,10 @@ public boolean isAvailable() { private static class Actions { private static final String CREATE_REQUIREMENT = "create_req"; + private static final String COMPLETE_REQUIREMENT = "complete_req"; + private static final String VOTE_REQUIREMENT = "vote_req"; + private static final String CREATE_PROJECT = "create_proj"; + private static final String CREATE_COMMENT = "create_com"; + } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java index 7a09808b..0f77e68e 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java @@ -254,6 +254,10 @@ public Response createComment(@ApiParam(value = "Comment entity", required = tru Comment createdComment = dalFacade.createComment(commentToCreate); bazaarService.getNotificationDispatcher().dispatchNotification(createdComment.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_46, createdComment.getId(), Activity.DataType.COMMENT, internalUserId); + // trigger Gamification Framework + bazaarService.getGamificationManager().triggerCreateCommentAction(internalUserId); + // add notifications to response + createdComment.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); return Response.status(Response.Status.CREATED).entity(createdComment.toJSON()).build(); } catch (BazaarException bex) { return resourceHelper.handleBazaarException(bex, "Create comment", logger); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java index 0c706a91..d2f98ae9 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java @@ -223,6 +223,10 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru Project createdProject = dalFacade.createProject(projectToCreate, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_5, createdProject.getId(), Activity.DataType.PROJECT, internalUserId); + // trigger Gamification Framework + bazaarService.getGamificationManager().triggerCreateProjectAction(internalUserId); + // add notifications to response + createdProject.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); return Response.status(Response.Status.CREATED).entity(createdProject.toJSON()).build(); } catch (BazaarException bex) { return resourceHelper.handleBazaarException(bex, "Create project", logger); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index 394ad764..be561cd5 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -270,6 +270,8 @@ public Response getRequirement(@PathParam("requirementId") int requirementId) { bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_25, requirementId, Activity.DataType.REQUIREMENT, internalUserId); isPublicCheck(dalFacade.isRequirementPublic(requirementId), internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, requirement.getProjectId(), dalFacade, PrivilegeEnum.Read_REQUIREMENT, "error.authorization.category.read"); + // add notifications to requirement + requirement.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { return resourceHelper.handleBazaarException(bex, "Get requirement " + requirementId, logger); @@ -798,6 +800,8 @@ public Response vote(@PathParam("requirementId") int requirementId, followUpvote(requirementId, direction, dalFacade, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.VOTE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_35, requirementId, Activity.DataType.REQUIREMENT, internalUserId); + // trigger Gamification Framework + bazaarService.getGamificationManager().triggerVoteAction(internalUserId); return Response.status(Response.Status.SEE_OTHER).location(URI.create(bazaarService.getBaseURL() + "requirements/" + requirementId)).build(); } catch (BazaarException bex) { return resourceHelper.handleBazaarException(bex, "Unfollow requirement " + requirementId, logger); @@ -873,6 +877,10 @@ public Response realize(@PathParam("requirementId") int requirementId) { Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade), "error.authorization.requirement.realize", true); requirement = dalFacade.setRequirementToRealized(requirementId, internalUserId); + // trigger Gamification Framework + bazaarService.getGamificationManager().triggerComplete_RequirementAction(internalUserId); + // add notifications to response + requirement.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.REALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_37, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); From 354a5dcca30c322ac21572930d5e03ebaac19684 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 1 Mar 2023 09:27:18 +0100 Subject: [PATCH 27/42] vote returns ok instead redirect --- .../acis/bazaar/service/resources/RequirementsResource.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index be561cd5..3f7c6d4b 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -27,7 +27,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.HttpURLConnection; -import java.net.URI; import java.time.OffsetDateTime; import java.util.*; @@ -783,7 +782,7 @@ public Response unfollowRequirement(@PathParam("requirementId") int requirementI @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "This method creates a vote for the given requirement in the name of the current user.") @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_SEE_OTHER, message = "Path to parent requirement"), + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Ok"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") @@ -802,7 +801,7 @@ public Response vote(@PathParam("requirementId") int requirementId, requirementId, Activity.DataType.REQUIREMENT, internalUserId); // trigger Gamification Framework bazaarService.getGamificationManager().triggerVoteAction(internalUserId); - return Response.status(Response.Status.SEE_OTHER).location(URI.create(bazaarService.getBaseURL() + "requirements/" + requirementId)).build(); + return Response.ok().build(); } catch (BazaarException bex) { return resourceHelper.handleBazaarException(bex, "Unfollow requirement " + requirementId, logger); } catch (Exception ex) { From 2d2baf04ccb0f71c5b438b9b5cfe04d0f9b472bc Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Mon, 13 Mar 2023 08:49:18 +0100 Subject: [PATCH 28/42] add more actions --- .../service/gamification/GamificationManager.java | 11 ++++++++++- .../service/resources/RequirementsResource.java | 10 +++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index 9e699f96..c61e737b 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -50,7 +50,7 @@ public void triggerCreateRequirementAction(Integer userId) { triggerActionIfGamificationAvailable(Actions.CREATE_REQUIREMENT, userId); } - public void triggerComplete_RequirementAction(Integer userId) { + public void triggerCompleteRequirementAction(Integer userId) { triggerActionIfGamificationAvailable(Actions.COMPLETE_REQUIREMENT, userId); } @@ -66,6 +66,13 @@ public void triggerVoteAction(Integer userId) { triggerActionIfGamificationAvailable(Actions.VOTE_REQUIREMENT, userId); } + public void triggerDevelopAction(Integer userId) { + triggerActionIfGamificationAvailable(Actions.DEVELOP_REQUIREMENT, userId); + } + + public void triggerFollowAction(Integer userId) { + triggerActionIfGamificationAvailable(Actions.FOLLOW_REQUIREMENT, userId); + } private void triggerActionIfGamificationAvailable(String actionId, Integer userId) { if (!isAvailable()) { @@ -125,6 +132,8 @@ private static class Actions { private static final String CREATE_REQUIREMENT = "create_req"; private static final String COMPLETE_REQUIREMENT = "complete_req"; private static final String VOTE_REQUIREMENT = "vote_req"; + private static final String FOLLOW_REQUIREMENT = "follow_req"; + private static final String DEVELOP_REQUIREMENT = "develop_req"; private static final String CREATE_PROJECT = "create_proj"; private static final String CREATE_COMMENT = "create_com"; diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index 3f7c6d4b..111ac83d 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -579,6 +579,10 @@ public Response developRequirement(@PathParam("requirementId") int requirementId requirement = dalFacade.getRequirementById(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.DEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_31, requirementId, Activity.DataType.REQUIREMENT, internalUserId); + // trigger Gamification Framework + bazaarService.getGamificationManager().triggerDevelopAction(internalUserId); + // add notifications to response + requirement.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { return resourceHelper.handleBazaarException(bex, "Develop requirement " + requirementId, logger); @@ -723,6 +727,10 @@ public Response followRequirement(@PathParam("requirementId") int requirementId) Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_33, requirementId, Activity.DataType.REQUIREMENT, internalUserId); + // trigger Gamification Framework + bazaarService.getGamificationManager().triggerFollowAction(internalUserId); + // add notifications to response + requirement.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { return resourceHelper.handleBazaarException(bex, "Follow requirement " + requirementId, logger); @@ -877,7 +885,7 @@ public Response realize(@PathParam("requirementId") int requirementId) { resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorizedInContext(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade), "error.authorization.requirement.realize", true); requirement = dalFacade.setRequirementToRealized(requirementId, internalUserId); // trigger Gamification Framework - bazaarService.getGamificationManager().triggerComplete_RequirementAction(internalUserId); + bazaarService.getGamificationManager().triggerCompleteRequirementAction(internalUserId); // add notifications to response requirement.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.REALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_37, From 7a433e6e3bfb5c453e1bf2e5e8b74c84262ff70a Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Mon, 13 Mar 2023 09:38:53 +0100 Subject: [PATCH 29/42] make user mail anonymus for gf framework --- .../java/de/rwth/dbis/acis/bazaar/service/BazaarService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java index 802778a7..0af6159e 100755 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -286,7 +286,7 @@ private void registerUserAtFirstLogin() throws Exception { // this.getNotificationDispatcher().dispatchNotification(user.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_55, userId, Activity.DataType.USER, userId); dalFacade.addUserToRole(userId, "LoggedInUser", null); - gamificationManager.initializeUser(userId, email); + gamificationManager.initializeUser(userId, "NO.EMAIL@WARNING.COM"); } else { // update lastLoginDate dalFacade.updateLastLoginDate(userIdByLAS2PeerId); From 480b9f3d001e229e7ff7485e123a986d1ad8a9d1 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Sun, 19 Mar 2023 12:54:07 +0100 Subject: [PATCH 30/42] add first login action --- .../bazaar/service/gamification/GamificationManager.java | 6 ++++++ .../dbis/acis/bazaar/service/resources/UsersResource.java | 1 + 2 files changed, 7 insertions(+) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index c61e737b..43e0bc47 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -40,6 +40,7 @@ public void initializeUser(Integer userId, String userEmail) { try { gfClient.registerUser(gfGameId, userId.toString(), userEmail); gfClient.addMemberToGame(gfGameId, userId.toString()); + triggerFirstLoginAction((userId)); } catch (IOException e) { logger.warning("Failed to add user to gamification framework: " + e.getMessage()); e.printStackTrace(); @@ -74,6 +75,10 @@ public void triggerFollowAction(Integer userId) { triggerActionIfGamificationAvailable(Actions.FOLLOW_REQUIREMENT, userId); } + public void triggerFirstLoginAction(Integer userId) { + triggerActionIfGamificationAvailable(Actions.FIRST_LOGIN, userId); + } + private void triggerActionIfGamificationAvailable(String actionId, Integer userId) { if (!isAvailable()) { logger.warning("Cannot trigger action " + actionId + ". Gamification is not configured"); @@ -136,6 +141,7 @@ private static class Actions { private static final String DEVELOP_REQUIREMENT = "develop_req"; private static final String CREATE_PROJECT = "create_proj"; private static final String CREATE_COMMENT = "create_com"; + private static final String FIRST_LOGIN = "first_login"; } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java index 6009aff1..49ccfb62 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java @@ -218,6 +218,7 @@ public Response getUserDashboard() { if (isGamified) { data.setBadges(bazaarService.getGamificationManager().getUserBadges(internalUserId)); data.setStatus(bazaarService.getGamificationManager().getUserStatus(internalUserId)); + data.setGamificationNotifications(bazaarService.getGamificationManager().getUserNotifications(internalUserId)); } String dashboardResponse = getDashboardResponse(isGamified, data); From 7999f0a053f97b63377542eacb0d48787e46d13f Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 4 Apr 2023 18:22:51 +0200 Subject: [PATCH 31/42] fix test case --- .../de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java index 950ba6b7..5b1a746c 100644 --- a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java +++ b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java @@ -114,7 +114,7 @@ public void testCreateGetProject() throws Exception { assertEquals(projectById.getVisibility(), proj.getVisibility()); - jooq.delete(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT).where(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT.ID.equal(project.getId())).execute(); + jooq.delete(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT).where(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT.ID.equal(proj.getId())).execute(); } @Test From f4d78e65092a62619388b4a9d0d211604537d111 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 4 Apr 2023 18:23:14 +0200 Subject: [PATCH 32/42] create default tags with project --- .../service/resources/ProjectsResource.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java index d2f98ae9..d8e8575d 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java @@ -60,6 +60,10 @@ public class ProjectsResource { private final ResourceHelper resourceHelper; + public static final String[] TAG_NAMES = {"Must", "Should", "Could"}; + + public static final String[] TAG_COLORS = {"#991629", "#FFD966", "#72a16f"}; + public ProjectsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); resourceHelper = new ResourceHelper(bazaarService); @@ -221,6 +225,7 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru resourceHelper.checkAuthorization(new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PROJECT, dalFacade), "error.authorization.project.create", true); projectToCreate.setLeader(dalFacade.getUserById(internalUserId)); Project createdProject = dalFacade.createProject(projectToCreate, internalUserId); + createDefaultTags(createdProject, bazaarService, dalFacade, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_5, createdProject.getId(), Activity.DataType.PROJECT, internalUserId); // trigger Gamification Framework @@ -237,6 +242,20 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru } } + private static void createDefaultTags(Project createdProject, BazaarService bazaarService, DALFacade dalFacade, Integer internalUserId) throws BazaarException { + for (int i = 0; i < TAG_NAMES.length; i++) { + Tag tag = Tag.builder().build(); + tag.setColour(TAG_COLORS[i]); + tag.setName(TAG_NAMES[i]); + // Ensure no cross-injection happens + tag.setProjectId(createdProject.getId()); + dalFacade.createTag(tag); + } + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_8, + createdProject.getId(), Activity.DataType.TAG, internalUserId); + + } + /** * Allows to update a certain project. * From 03b67298f60e2880f92415768e76abb24120241e Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Tue, 4 Apr 2023 18:23:39 +0200 Subject: [PATCH 33/42] create custom changeset --- reqbaz/build.gradle | 6 +- .../customChangeSets/AddDefaultTags.java | 79 +++++++++++++++++++ 2 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets/AddDefaultTags.java diff --git a/reqbaz/build.gradle b/reqbaz/build.gradle index 2a0d35fd..5a33c573 100644 --- a/reqbaz/build.gradle +++ b/reqbaz/build.gradle @@ -39,8 +39,7 @@ application { } repositories { - // Use JCenter for resolving dependencies. - jcenter() + mavenCentral() // DBIS Archiva maven { @@ -50,6 +49,7 @@ repositories { dependencies { implementation 'org.jetbrains:annotations:20.1.0' + implementation 'org.liquibase:liquibase-core:4.20.0' // Use JUnit test framework. testImplementation 'junit:junit:4.13' @@ -205,7 +205,7 @@ liquibase { main { defaultSchemaName 'public' changeLogFile "changelog.yaml" - classpath "$projectDir/src/main/resources" + classpath "$projectDir/src/main/resources;$projectDir/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets" url "jdbc:postgresql://${project.property('db.hostname')}:${project.property('db.port')}/${project.property('db.name')}" username "${project.property('db.user')}" password "${project.property('db.password')}" diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets/AddDefaultTags.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets/AddDefaultTags.java new file mode 100644 index 00000000..63162a1b --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets/AddDefaultTags.java @@ -0,0 +1,79 @@ +package de.rwth.dbis.acis.bazaar.service.customChangeSets; + +import liquibase.Scope; +import liquibase.change.custom.CustomTaskChange; +import liquibase.database.Database; +import liquibase.exception.CustomChangeException; +import liquibase.exception.DatabaseException; +import liquibase.exception.SetupException; +import liquibase.exception.ValidationErrors; +import liquibase.executor.Executor; +import liquibase.executor.ExecutorService; +import liquibase.resource.ResourceAccessor; +import liquibase.statement.SqlStatement; +import liquibase.statement.core.InsertStatement; +import liquibase.statement.core.RawSqlStatement; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class AddDefaultTags implements CustomTaskChange { + @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) + private ResourceAccessor resourceAccessor; + + @Override + public void execute(Database database) throws CustomChangeException { + try { + Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database); + String sql = "SELECT * FROM project"; + SqlStatement sqlStatement = new RawSqlStatement(sql); + + List> results = executor.queryForList(sqlStatement); + List projectIds = new ArrayList<>(); + for (Map result : results) { + int projectId = ((Integer) result.get("id")); + projectIds.add(projectId); + } + + for (int id : projectIds) { + InsertStatement insertStatementMust = getInsertStatement(id, "Must", "#991629"); + InsertStatement insertStatementCould = getInsertStatement(id, "Could", "#72a16f"); + InsertStatement insertStatementShould = getInsertStatement(id, "Should", "#FFD966"); + executor.execute(insertStatementShould); + executor.execute(insertStatementMust); + executor.execute(insertStatementCould); + } + + } catch (DatabaseException e) { + throw new CustomChangeException(e); + } + } + + private static InsertStatement getInsertStatement(int id, String name, String colour) { + return new InsertStatement("reqbaz", "public", "tag") + .addColumnValue("project_id", id) + .addColumnValue("name", name) + .addColumnValue("colour", colour); + } + + @Override + public String getConfirmationMessage() { + return "Tags added"; + } + + @Override + public void setUp() throws SetupException { + ; + } + + @Override + public void setFileOpener(ResourceAccessor resourceAccessor) { + ; + } + + @Override + public ValidationErrors validate(Database database) { + return new ValidationErrors(); + } +} From bb1477e6dd9c7ee087b831694b304a4d26dd5c21 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Thu, 6 Apr 2023 13:19:34 +0200 Subject: [PATCH 34/42] fix build --- reqbaz/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reqbaz/build.gradle b/reqbaz/build.gradle index 5a33c573..bc59e18f 100644 --- a/reqbaz/build.gradle +++ b/reqbaz/build.gradle @@ -205,7 +205,7 @@ liquibase { main { defaultSchemaName 'public' changeLogFile "changelog.yaml" - classpath "$projectDir/src/main/resources;$projectDir/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets" + classpath "$projectDir/src/main/resources:$projectDir/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets" url "jdbc:postgresql://${project.property('db.hostname')}:${project.property('db.port')}/${project.property('db.name')}" username "${project.property('db.user')}" password "${project.property('db.password')}" From 018a50967850342324ad7ef44114d035979e9e5c Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Thu, 6 Apr 2023 13:20:00 +0200 Subject: [PATCH 35/42] dont ignore projectId in tag --- .../java/de/rwth/dbis/acis/bazaar/service/dal/entities/Tag.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Tag.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Tag.java index d1beabb2..3ee95f6c 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Tag.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Tag.java @@ -1,6 +1,5 @@ package de.rwth.dbis.acis.bazaar.service.dal.entities; -import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; @@ -22,6 +21,5 @@ public class Tag extends EntityBase { @NotNull private String colour; - @JsonIgnore private Integer projectId; } From a4136aa1a2f39a1f9be07498d31f8e21707db213 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Fri, 7 Apr 2023 09:14:28 +0200 Subject: [PATCH 36/42] delete unused tags on change --- .../de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java index 5da97308..e00a3e3d 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java @@ -424,7 +424,7 @@ private void synchronizeTags(Requirement modifiedRequirement, Requirement oldReq checkTagChanges(modifiedRequirement); // Remove tags no longer present - oldRequirement.getTags().stream().filter(tag -> modifiedRequirement.getTags().contains(tag)).forEach(tag -> { + oldRequirement.getTags().stream().filter(tag -> !modifiedRequirement.getTags().contains(tag)).forEach(tag -> { try { untagRequirement(tag.getId(), oldRequirement.getId()); } catch (Exception e) { From c767b43e50aad5344631ce6b4ede226eb6e4fdb7 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 26 Apr 2023 08:54:58 +0200 Subject: [PATCH 37/42] use sql statement instead of custom change --- reqbaz/build.gradle | 2 +- .../customChangeSets/AddDefaultTags.java | 79 ------------------- reqbaz/src/main/resources/changelog.yaml | 12 ++- 3 files changed, 12 insertions(+), 81 deletions(-) delete mode 100644 reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets/AddDefaultTags.java diff --git a/reqbaz/build.gradle b/reqbaz/build.gradle index bc59e18f..a628cd57 100644 --- a/reqbaz/build.gradle +++ b/reqbaz/build.gradle @@ -205,7 +205,7 @@ liquibase { main { defaultSchemaName 'public' changeLogFile "changelog.yaml" - classpath "$projectDir/src/main/resources:$projectDir/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets" + classpath "$projectDir/src/main/resources" url "jdbc:postgresql://${project.property('db.hostname')}:${project.property('db.port')}/${project.property('db.name')}" username "${project.property('db.user')}" password "${project.property('db.password')}" diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets/AddDefaultTags.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets/AddDefaultTags.java deleted file mode 100644 index 63162a1b..00000000 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/customChangeSets/AddDefaultTags.java +++ /dev/null @@ -1,79 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.customChangeSets; - -import liquibase.Scope; -import liquibase.change.custom.CustomTaskChange; -import liquibase.database.Database; -import liquibase.exception.CustomChangeException; -import liquibase.exception.DatabaseException; -import liquibase.exception.SetupException; -import liquibase.exception.ValidationErrors; -import liquibase.executor.Executor; -import liquibase.executor.ExecutorService; -import liquibase.resource.ResourceAccessor; -import liquibase.statement.SqlStatement; -import liquibase.statement.core.InsertStatement; -import liquibase.statement.core.RawSqlStatement; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class AddDefaultTags implements CustomTaskChange { - @SuppressWarnings({"UnusedDeclaration", "FieldCanBeLocal"}) - private ResourceAccessor resourceAccessor; - - @Override - public void execute(Database database) throws CustomChangeException { - try { - Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database); - String sql = "SELECT * FROM project"; - SqlStatement sqlStatement = new RawSqlStatement(sql); - - List> results = executor.queryForList(sqlStatement); - List projectIds = new ArrayList<>(); - for (Map result : results) { - int projectId = ((Integer) result.get("id")); - projectIds.add(projectId); - } - - for (int id : projectIds) { - InsertStatement insertStatementMust = getInsertStatement(id, "Must", "#991629"); - InsertStatement insertStatementCould = getInsertStatement(id, "Could", "#72a16f"); - InsertStatement insertStatementShould = getInsertStatement(id, "Should", "#FFD966"); - executor.execute(insertStatementShould); - executor.execute(insertStatementMust); - executor.execute(insertStatementCould); - } - - } catch (DatabaseException e) { - throw new CustomChangeException(e); - } - } - - private static InsertStatement getInsertStatement(int id, String name, String colour) { - return new InsertStatement("reqbaz", "public", "tag") - .addColumnValue("project_id", id) - .addColumnValue("name", name) - .addColumnValue("colour", colour); - } - - @Override - public String getConfirmationMessage() { - return "Tags added"; - } - - @Override - public void setUp() throws SetupException { - ; - } - - @Override - public void setFileOpener(ResourceAccessor resourceAccessor) { - ; - } - - @Override - public ValidationErrors validate(Database database) { - return new ValidationErrors(); - } -} diff --git a/reqbaz/src/main/resources/changelog.yaml b/reqbaz/src/main/resources/changelog.yaml index 184d9535..334d3e43 100644 --- a/reqbaz/src/main/resources/changelog.yaml +++ b/reqbaz/src/main/resources/changelog.yaml @@ -1737,4 +1737,14 @@ databaseChangeLog: type: INTEGER defaultValue: -1 # user is unknown (legacy data reasons) constraints: - nullable: false \ No newline at end of file + nullable: false + - changeSet: + id: 23-04-26-add-default-tags + author: tobasco99 + changes: + - sql: + sql: insert into tag (name, colour, project_id) select 'Must', '#991629', id from project + - sql: + sql: insert into tag (name, colour, project_id) select 'Should', '#FFD966', id from project + - sql: + sql: insert into tag (name, colour, project_id) select 'Could', '#72a16f', id from project \ No newline at end of file From 2823cd153a2bf0053259e3a7481bd47ddcdd6ec8 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 3 May 2023 10:21:04 +0200 Subject: [PATCH 38/42] adjust gamification to work with gamification on cluster --- .../acis/bazaar/service/BazaarService.java | 7 +++- .../GamificationFrameworkClient.java | 22 ++++------ .../gamification/GamificationManager.java | 40 ++++++++++--------- 3 files changed, 34 insertions(+), 35 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java index 0af6159e..fd88dfab 100755 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -285,11 +285,14 @@ private void registerUserAtFirstLogin() throws Exception { int userId = user.getId(); // this.getNotificationDispatcher().dispatchNotification(user.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_55, userId, Activity.DataType.USER, userId); dalFacade.addUserToRole(userId, "LoggedInUser", null); - - gamificationManager.initializeUser(userId, "NO.EMAIL@WARNING.COM"); + gamificationManager.initializeUser(userId, true); } else { // update lastLoginDate dalFacade.updateLastLoginDate(userIdByLAS2PeerId); + // make sure logged-in user is added to gamification + if (!(agent instanceof AnonymousAgent)) { + gamificationManager.initializeUser(userIdByLAS2PeerId, false); + } } } catch (Exception ex) { ExceptionHandler.getInstance().convertAndThrowException(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, Localization.getInstance().getResourceBundle().getString("error.first_login")); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java index 0d68ad63..13114a73 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -54,33 +54,27 @@ public void addMemberToGame(String gameId, String memberUsername) throws IOExcep try (Response response = httpClient.newCall(request).execute()) { checkSuccess(response); - logger.info("Added member " + memberUsername + " to game " + gameId + " (response: " + response.body().string() + ")"); + logger.info("Added member " + memberUsername + " to game " + gameId); } } - public void registerUser(String gameId, String memberUsername, String email) throws IOException { + public void registerUser(String gameId, String memberUsername) throws IOException { Validate.notBlank(gameId); Validate.notBlank(memberUsername); - Validate.notBlank(email); - - RequestBody requestBody = new MultipartBody.Builder() - .setType(MultipartBody.FORM) - .addFormDataPart("memberId", memberUsername) - .addFormDataPart("email", email) - .build(); Request request = new Request.Builder() .url(gfBaseUrl.newBuilder() .addPathSegment("games") - .addPathSegment("register") + .addPathSegment("validation") + .addPathSegment(memberUsername) .build() ) - .post(requestBody) + .method("POST", RequestBody.create("", null)) .build(); try (Response response = httpClient.newCall(request).execute()) { checkSuccess(response); - logger.info("Added member " + memberUsername + " to gamification." + " (response: " + response.body().string() + ")"); + logger.info("Added member " + memberUsername + " to gamification."); } } @@ -149,7 +143,7 @@ public List> getEarnedBadges(String gameId, String userId) t checkSuccess(response); String rawResponse = Objects.requireNonNull(response.body()).string(); - logger.info("Triggered getBadges " + gameId + " for user " + userId + " (response: " + rawResponse + ")"); + logger.info("Triggered getBadges " + gameId + " for user " + userId); final CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class); List> badges = objectMapper.readValue(rawResponse, collectionType); @@ -206,7 +200,7 @@ public Map getMemberStatus(String gameId, String userId) throws checkSuccess(response); String rawResponse = Objects.requireNonNull(response.body()).string(); - logger.info("Triggered get status " + gameId + " for user " + userId + " (response: " + rawResponse + ")"); + logger.info("Triggered get status " + gameId + " for user " + userId); final MapType mapType = objectMapper.getTypeFactory().constructMapType( Map.class, String.class, Object.class); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index 43e0bc47..dc5e4269 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -31,16 +31,18 @@ public GamificationManager(String gfBaseUrl, String gfUsername, String gfPasswor } } - public void initializeUser(Integer userId, String userEmail) { + public void initializeUser(Integer userId, boolean firstLogin) { if (!isAvailable()) { logger.warning("Cannot add user to Gamification Framework. Gamification is not configured"); return; } try { - gfClient.registerUser(gfGameId, userId.toString(), userEmail); - gfClient.addMemberToGame(gfGameId, userId.toString()); - triggerFirstLoginAction((userId)); + gfClient.registerUser(gfGameId, "reqbaz_" + userId); + gfClient.addMemberToGame(gfGameId, "reqbaz_" + userId); + if (firstLogin) { + triggerFirstLoginAction((userId)); + } } catch (IOException e) { logger.warning("Failed to add user to gamification framework: " + e.getMessage()); e.printStackTrace(); @@ -48,47 +50,47 @@ public void initializeUser(Integer userId, String userEmail) { } public void triggerCreateRequirementAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.CREATE_REQUIREMENT, userId); + triggerActionIfGamificationAvailable(Actions.CREATE_REQUIREMENT, userId, "reqbaz_" + userId); } public void triggerCompleteRequirementAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.COMPLETE_REQUIREMENT, userId); + triggerActionIfGamificationAvailable(Actions.COMPLETE_REQUIREMENT, userId, "reqbaz_" + userId); } public void triggerCreateProjectAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.CREATE_PROJECT, userId); + triggerActionIfGamificationAvailable(Actions.CREATE_PROJECT, userId, "reqbaz_" + userId); } public void triggerCreateCommentAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.CREATE_COMMENT, userId); + triggerActionIfGamificationAvailable(Actions.CREATE_COMMENT, userId, "reqbaz_" + userId); } public void triggerVoteAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.VOTE_REQUIREMENT, userId); + triggerActionIfGamificationAvailable(Actions.VOTE_REQUIREMENT, userId, "reqbaz_" + userId); } public void triggerDevelopAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.DEVELOP_REQUIREMENT, userId); + triggerActionIfGamificationAvailable(Actions.DEVELOP_REQUIREMENT, userId, "reqbaz_" + userId); } public void triggerFollowAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.FOLLOW_REQUIREMENT, userId); + triggerActionIfGamificationAvailable(Actions.FOLLOW_REQUIREMENT, userId, "reqbaz_" + userId); } public void triggerFirstLoginAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.FIRST_LOGIN, userId); + triggerActionIfGamificationAvailable(Actions.FIRST_LOGIN, userId, "reqbaz_" + userId); } - private void triggerActionIfGamificationAvailable(String actionId, Integer userId) { + private void triggerActionIfGamificationAvailable(String actionId, Integer userId, String gamificationUser) { if (!isAvailable()) { logger.warning("Cannot trigger action " + actionId + ". Gamification is not configured"); return; } try { - List> notifications = gfClient.triggerAction(gfGameId, actionId, userId.toString()); + List> notifications = gfClient.triggerAction(gfGameId, actionId, gamificationUser); storeUserNotifications(userId, notifications); } catch (IOException e) { - logger.warning("Failed to trigger action " + actionId + " for user " + userId); + logger.warning("Failed to trigger action " + actionId + " for user " + gamificationUser); e.printStackTrace(); } } @@ -110,9 +112,9 @@ private void storeUserNotifications(Integer userId, List> no public List> getUserBadges(Integer userId) { try { - return gfClient.getEarnedBadges(gfGameId, userId.toString()); + return gfClient.getEarnedBadges(gfGameId, "reqbaz_" + userId); } catch (IOException e) { - logger.warning("Failed to get badges for user " + userId); + logger.warning("Failed to get badges for user " + "reqbaz_" + userId); e.printStackTrace(); return Collections.emptyList(); } @@ -120,10 +122,10 @@ public List> getUserBadges(Integer userId) { public Map getUserStatus(Integer userId) { try { - Map status = gfClient.getMemberStatus(gfGameId, userId.toString()); + Map status = gfClient.getMemberStatus(gfGameId, "reqbaz_" + userId); return status; } catch (IOException e) { - logger.warning("Failed to get status for user " + userId); + logger.warning("Failed to get status for user " + "reqbaz_" + userId); e.printStackTrace(); return Collections.emptyMap(); } From 55022cf1cb97b7254fcfb1b986c27b92447ed360 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 3 May 2023 11:55:53 +0200 Subject: [PATCH 39/42] add namespace to gamifiction ids --- .../acis/bazaar/service/BazaarService.java | 3 +- .../gamification/GamificationManager.java | 35 ++++++++++--------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java index fd88dfab..179141c3 100755 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -116,6 +116,7 @@ public class BazaarService extends RESTService { protected String gfUsername; protected String gfPassword; protected String gfGameId; + protected String gfNamespace; public BazaarService() throws Exception { setFieldValues(); @@ -174,7 +175,7 @@ public BazaarService() throws Exception { tweetDispatcher = new TweetDispatcher(this, twitterApiKey, twitterApiKeySecret, twitterClientId, twitterClientSecret); new WeeklyNewProjectsTweetTask(this).schedule(timer); - gamificationManager = new GamificationManager(gfBaseUrl, gfUsername, gfPassword, gfGameId); + gamificationManager = new GamificationManager(gfBaseUrl, gfUsername, gfPassword, gfGameId, gfNamespace); notificationDispatcher.setBazaarService(this); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index dc5e4269..88137eaa 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -12,6 +12,8 @@ public class GamificationManager { private final GamificationFrameworkClient gfClient; private final String gfGameId; + private final String gfNamespace; + /** * Notifications returned by the framework during request processing. @@ -20,10 +22,11 @@ public class GamificationManager { */ private Map>> notificationCache = new HashMap<>(); - public GamificationManager(String gfBaseUrl, String gfUsername, String gfPassword, String gfGameId) { + public GamificationManager(String gfBaseUrl, String gfUsername, String gfPassword, String gfGameId, String gfNamespace) { this.gfGameId = gfGameId; + this.gfNamespace = gfNamespace; - if (StringUtils.isAnyBlank(gfBaseUrl, gfUsername, gfPassword, gfGameId)) { + if (StringUtils.isAnyBlank(gfBaseUrl, gfUsername, gfPassword, gfGameId, gfNamespace)) { logger.warning("Gamification functionality cannot be used without GamificationFramework credentials!"); gfClient = null; } else { @@ -38,8 +41,8 @@ public void initializeUser(Integer userId, boolean firstLogin) { } try { - gfClient.registerUser(gfGameId, "reqbaz_" + userId); - gfClient.addMemberToGame(gfGameId, "reqbaz_" + userId); + gfClient.registerUser(gfGameId, gfNamespace + userId); + gfClient.addMemberToGame(gfGameId, gfNamespace + userId); if (firstLogin) { triggerFirstLoginAction((userId)); } @@ -50,35 +53,35 @@ public void initializeUser(Integer userId, boolean firstLogin) { } public void triggerCreateRequirementAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.CREATE_REQUIREMENT, userId, "reqbaz_" + userId); + triggerActionIfGamificationAvailable(Actions.CREATE_REQUIREMENT, userId, gfNamespace + userId); } public void triggerCompleteRequirementAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.COMPLETE_REQUIREMENT, userId, "reqbaz_" + userId); + triggerActionIfGamificationAvailable(Actions.COMPLETE_REQUIREMENT, userId, gfNamespace + userId); } public void triggerCreateProjectAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.CREATE_PROJECT, userId, "reqbaz_" + userId); + triggerActionIfGamificationAvailable(Actions.CREATE_PROJECT, userId, gfNamespace + userId); } public void triggerCreateCommentAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.CREATE_COMMENT, userId, "reqbaz_" + userId); + triggerActionIfGamificationAvailable(Actions.CREATE_COMMENT, userId, gfNamespace + userId); } public void triggerVoteAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.VOTE_REQUIREMENT, userId, "reqbaz_" + userId); + triggerActionIfGamificationAvailable(Actions.VOTE_REQUIREMENT, userId, gfNamespace + userId); } public void triggerDevelopAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.DEVELOP_REQUIREMENT, userId, "reqbaz_" + userId); + triggerActionIfGamificationAvailable(Actions.DEVELOP_REQUIREMENT, userId, gfNamespace + userId); } public void triggerFollowAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.FOLLOW_REQUIREMENT, userId, "reqbaz_" + userId); + triggerActionIfGamificationAvailable(Actions.FOLLOW_REQUIREMENT, userId, gfNamespace + userId); } public void triggerFirstLoginAction(Integer userId) { - triggerActionIfGamificationAvailable(Actions.FIRST_LOGIN, userId, "reqbaz_" + userId); + triggerActionIfGamificationAvailable(Actions.FIRST_LOGIN, userId, gfNamespace + userId); } private void triggerActionIfGamificationAvailable(String actionId, Integer userId, String gamificationUser) { @@ -112,9 +115,9 @@ private void storeUserNotifications(Integer userId, List> no public List> getUserBadges(Integer userId) { try { - return gfClient.getEarnedBadges(gfGameId, "reqbaz_" + userId); + return gfClient.getEarnedBadges(gfGameId, gfNamespace + userId); } catch (IOException e) { - logger.warning("Failed to get badges for user " + "reqbaz_" + userId); + logger.warning("Failed to get badges for user " + gfNamespace + userId); e.printStackTrace(); return Collections.emptyList(); } @@ -122,10 +125,10 @@ public List> getUserBadges(Integer userId) { public Map getUserStatus(Integer userId) { try { - Map status = gfClient.getMemberStatus(gfGameId, "reqbaz_" + userId); + Map status = gfClient.getMemberStatus(gfGameId, gfNamespace + userId); return status; } catch (IOException e) { - logger.warning("Failed to get status for user " + "reqbaz_" + userId); + logger.warning("Failed to get status for user " + gfNamespace + userId); e.printStackTrace(); return Collections.emptyMap(); } From 32632276e209937b46feed378a30b2eea0938172 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 3 May 2023 12:27:25 +0200 Subject: [PATCH 40/42] add new property fields --- ....rwth.dbis.acis.bazaar.service.BazaarService.properties | 5 +++++ ....rwth.dbis.acis.bazaar.service.BazaarService.properties | 7 +------ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties b/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties index 082404f1..2fec3f1a 100644 --- a/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties +++ b/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties @@ -11,3 +11,8 @@ smtpServer= emailFromAddress= emailSummaryTimePeriodInMinutes= monitor= +gfBaseUrl= +gfUsername= +gfPassword= +gfGameId= +gfNamespace= \ No newline at end of file diff --git a/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties b/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties index f265e440..3ebdd300 100644 --- a/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties +++ b/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties @@ -14,9 +14,4 @@ monitor='' twitterApiKey= twitterApiKeySecret= twitterClientId= -twitterClientSecret= -gfGameServiceUrl= -gfVisualizationServiceUrl= -gfUsername= -gfPassword= -gfGameId= \ No newline at end of file +twitterClientSecret= \ No newline at end of file From 1f099314fe725b72f4a912e86e367b227ca796d8 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 10 May 2023 09:13:54 +0200 Subject: [PATCH 41/42] reduce amount of requests to gf framework --- .../rwth/dbis/acis/bazaar/service/BazaarService.java | 7 ++----- .../gamification/GamificationFrameworkClient.java | 6 +++++- .../service/gamification/GamificationManager.java | 4 ++-- .../acis/bazaar/service/resources/UsersResource.java | 11 +++++++---- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java index 179141c3..9c18c026 100755 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -286,14 +286,11 @@ private void registerUserAtFirstLogin() throws Exception { int userId = user.getId(); // this.getNotificationDispatcher().dispatchNotification(user.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_55, userId, Activity.DataType.USER, userId); dalFacade.addUserToRole(userId, "LoggedInUser", null); - gamificationManager.initializeUser(userId, true); + // add new user to gamification and game + gamificationManager.initializeUser(userId); } else { // update lastLoginDate dalFacade.updateLastLoginDate(userIdByLAS2PeerId); - // make sure logged-in user is added to gamification - if (!(agent instanceof AnonymousAgent)) { - gamificationManager.initializeUser(userIdByLAS2PeerId, false); - } } } catch (Exception ex) { ExceptionHandler.getInstance().convertAndThrowException(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, Localization.getInstance().getResourceBundle().getString("error.first_login")); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java index 13114a73..df9a1c5e 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationFrameworkClient.java @@ -20,6 +20,7 @@ public class GamificationFrameworkClient { private final HttpUrl gfBaseUrl; private final OkHttpClient httpClient; private final ObjectMapper objectMapper = new ObjectMapper(); + private static final String FIRST_LOGIN = "first_login"; public GamificationFrameworkClient(String gfBaseUrl, String gfUsername, String gfPassword) { this.gfBaseUrl = HttpUrl.parse(gfBaseUrl); @@ -37,7 +38,7 @@ public GamificationFrameworkClient(String gfBaseUrl, String gfUsername, String g .build(); } - public void addMemberToGame(String gameId, String memberUsername) throws IOException { + public boolean addMemberToGame(String gameId, String memberUsername) throws IOException { Validate.notBlank(gameId); Validate.notBlank(memberUsername); @@ -54,7 +55,10 @@ public void addMemberToGame(String gameId, String memberUsername) throws IOExcep try (Response response = httpClient.newCall(request).execute()) { checkSuccess(response); + String rawResponse = Objects.requireNonNull(response.body()).string(); logger.info("Added member " + memberUsername + " to game " + gameId); + // returns true if user is newly added to the game + return !rawResponse.equalsIgnoreCase("{}"); } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java index 88137eaa..539ee710 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/gamification/GamificationManager.java @@ -34,7 +34,7 @@ public GamificationManager(String gfBaseUrl, String gfUsername, String gfPasswor } } - public void initializeUser(Integer userId, boolean firstLogin) { + public void initializeUser(Integer userId) { if (!isAvailable()) { logger.warning("Cannot add user to Gamification Framework. Gamification is not configured"); return; @@ -42,7 +42,7 @@ public void initializeUser(Integer userId, boolean firstLogin) { try { gfClient.registerUser(gfGameId, gfNamespace + userId); - gfClient.addMemberToGame(gfGameId, gfNamespace + userId); + boolean firstLogin = gfClient.addMemberToGame(gfGameId, gfNamespace + userId); if (firstLogin) { triggerFirstLoginAction((userId)); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java index 49ccfb62..f5bb3b33 100644 --- a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java @@ -205,15 +205,18 @@ public Response getUserDashboard() { DALFacade dalFacade = null; try { String userId = resourceHelper.getUserId(); + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + boolean isGamified = bazaarService.getGamificationManager().isAvailable(); // Block anonymous user resourceHelper.checkAuthorization(!userId.equals("anonymous"), "error.authorization.user.read", true); - - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + // make sure logged-in user is added to gamification if not anonymous + if (!userId.equals("anonymous") && isGamified) { + bazaarService.getGamificationManager().initializeUser(internalUserId); + } bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_54, internalUserId, Activity.DataType.USER, internalUserId); - boolean isGamified = bazaarService.getGamificationManager().isAvailable(); Dashboard data = dalFacade.getDashboardData(internalUserId, 10); if (isGamified) { data.setBadges(bazaarService.getGamificationManager().getUserBadges(internalUserId)); From f6901bc995683591291273e37c042c81c3e14c31 Mon Sep 17 00:00:00 2001 From: Tobasco99 Date: Wed, 10 May 2023 09:41:57 +0200 Subject: [PATCH 42/42] docs:update changelog --- CHANGELOG.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6199808c..1b79473e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,15 +10,24 @@ the [GitHub Release Page](https://github.com/rwth-acis/RequirementsBazaar/releas ## [Unreleased] +## [0.17.0] - 2023-05-10 + +### Added + +- Added gamification + [d758be2b4a66bd943665c097eee963c65a7dc68e](https://github.com/rwth-acis/RequirementsBazaar/commit/d758be2b4a66bd943665c097eee963c65a7dc68e) +- Added priority labels + [#179](https://github.com/rwth-acis/RequirementsBazaar/pull/179) + ## [0.16.0] - 2022-10-05 ### Changed + - Upgraded to las2peer 1.2.3 and Java 17 [#175](https://github.com/rwth-acis/RequirementsBazaar/pull/175) - Fixed bug which caused new users being unable to login [#173](https://github.com/rwth-acis/RequirementsBazaar/issues/173) - ## [0.15.0] - 2022-08-07 ### Added