diff --git a/app/actors/ActivityActor.java b/app/actors/ActivityActor.java index bbdc187c..ced634ef 100644 --- a/app/actors/ActivityActor.java +++ b/app/actors/ActivityActor.java @@ -2,7 +2,7 @@ import actors.ActivityProtocol.Activities; import actors.ActivityProtocol.Activity; -import akka.actor.UntypedActor; +import akka.actor.AbstractActor; import dto.Dto; import models.LogEntry; import org.slf4j.LoggerFactory; @@ -13,7 +13,7 @@ import java.util.stream.Collectors; @Singleton -public class ActivityActor extends UntypedActor { +public class ActivityActor extends AbstractActor { public static final String NAME = "activity-actor"; @@ -24,26 +24,24 @@ public ActivityActor(LogEntryRepository logEntryRepository) { this.logEntryRepository = logEntryRepository; } - @SuppressWarnings("unchecked") - @Override - public void onReceive(Object msg) throws Throwable { - if (msg instanceof Activity) { - Activity t = (Activity) msg; - - LoggerFactory.getLogger(ActivityActor.class).debug("onReceive({})", t); - - logEntryRepository.create(ActivityActor.fromActivity(t)); - } else if (msg instanceof Activities) { - Activities t = (Activities) msg; - - LoggerFactory.getLogger(ActivityActor.class).debug("onReceive({})", t.activities); - - logEntryRepository.save(t.activities.stream().map(ActivityActor::fromActivity).collect( - Collectors.toList())); - } - } - private static LogEntry fromActivity(Activity t) { return LogEntry.from(t.type, t.user, t.project, t.dtoClass, t.before, t.after); } + + @Override + public Receive createReceive() { + return receiveBuilder() + .match(Activity.class, t -> { + LoggerFactory.getLogger(ActivityActor.class).debug("onReceive({})", t); + + logEntryRepository.create(ActivityActor.fromActivity(t)); + }) + .match(Activities.class, (t) -> { + LoggerFactory.getLogger(ActivityActor.class).debug("onReceive({})", t.activities); + + logEntryRepository.save(((Activities)t).activities.stream().map(ActivityActor::fromActivity).collect( + Collectors.toList())); + }) + .build(); + } } diff --git a/app/actors/KeyWordCountActor.java b/app/actors/KeyWordCountActor.java index 4ba932e3..1c51750c 100644 --- a/app/actors/KeyWordCountActor.java +++ b/app/actors/KeyWordCountActor.java @@ -1,7 +1,7 @@ package actors; import actors.WordCountProtocol.ChangeWordCount; -import akka.actor.UntypedActor; +import akka.actor.AbstractActor; import services.KeyService; import javax.inject.Inject; @@ -12,7 +12,7 @@ * @version 6 Jun 2017 */ @Singleton -public class KeyWordCountActor extends UntypedActor { +public class KeyWordCountActor extends AbstractActor { public static final String NAME = "key-word-count-actor"; private final KeyService keyService; @@ -22,14 +22,11 @@ public KeyWordCountActor(KeyService keyService) { this.keyService = keyService; } - /** - * {@inheritDoc} - */ @Override - public void onReceive(Object msg) throws Throwable { - if (msg instanceof ChangeWordCount) { - ChangeWordCount wordCount = (ChangeWordCount) msg; - keyService.increaseWordCountBy(wordCount.id, wordCount.wordCountDiff); - } + public Receive createReceive() { + return receiveBuilder() + .match(ChangeWordCount.class, + wordCount -> keyService.increaseWordCountBy(wordCount.id, wordCount.wordCountDiff, null /* FIXME */)) + .build(); } } diff --git a/app/actors/LocaleWordCountActor.java b/app/actors/LocaleWordCountActor.java index bff61e6b..069972f4 100644 --- a/app/actors/LocaleWordCountActor.java +++ b/app/actors/LocaleWordCountActor.java @@ -1,7 +1,7 @@ package actors; import actors.WordCountProtocol.ChangeWordCount; -import akka.actor.UntypedActor; +import akka.actor.AbstractActor; import services.LocaleService; import javax.inject.Inject; @@ -12,7 +12,7 @@ * @version 6 Jun 2017 */ @Singleton -public class LocaleWordCountActor extends UntypedActor { +public class LocaleWordCountActor extends AbstractActor { public static final String NAME = "locale-word-count-actor"; private final LocaleService localeService; @@ -22,14 +22,11 @@ public LocaleWordCountActor(LocaleService localeService) { this.localeService = localeService; } - /** - * {@inheritDoc} - */ @Override - public void onReceive(Object msg) throws Throwable { - if (msg instanceof ChangeWordCount) { - ChangeWordCount wordCount = (ChangeWordCount) msg; - localeService.increaseWordCountBy(wordCount.id, wordCount.wordCountDiff); - } + public Receive createReceive() { + return receiveBuilder() + .match(ChangeWordCount.class, + wordCount -> localeService.increaseWordCountBy(wordCount.id, wordCount.wordCountDiff, null /* FIXME */)) + .build(); } } diff --git a/app/actors/MessageWordCountActor.java b/app/actors/MessageWordCountActor.java index f416856d..09bfc629 100644 --- a/app/actors/MessageWordCountActor.java +++ b/app/actors/MessageWordCountActor.java @@ -2,8 +2,8 @@ import actors.WordCountProtocol.ChangeMessageWordCount; import actors.WordCountProtocol.ChangeWordCount; +import akka.actor.AbstractActor; import akka.actor.ActorRef; -import akka.actor.UntypedActor; import javax.inject.Inject; import javax.inject.Named; @@ -18,7 +18,7 @@ * @version 6 Jun 2017 */ @Singleton -public class MessageWordCountActor extends UntypedActor { +public class MessageWordCountActor extends AbstractActor { public static final String NAME = "message-word-count-actor"; private final ActorRef localeWordCountActor; @@ -36,41 +36,38 @@ public MessageWordCountActor(@Named(LocaleWordCountActor.NAME) ActorRef localeWo this.projectWordCountActor = projectWordCountActor; } - /** - * {@inheritDoc} - */ @Override - public void onReceive(Object msg) throws Throwable { - if (msg instanceof ChangeMessageWordCount) { - ChangeMessageWordCount wordCount = (ChangeMessageWordCount) msg; + public Receive createReceive() { + return receiveBuilder() + .match(ChangeMessageWordCount.class, wordCount -> { + if (wordCount.projectId != null) + projectWordCountActor.tell( + new ChangeWordCount(wordCount.projectId, wordCount.wordCount, wordCount.wordCountDiff), + self()); + if (wordCount.localeId != null) + localeWordCountActor.tell( + new ChangeWordCount(wordCount.localeId, wordCount.wordCount, wordCount.wordCountDiff), + self()); + if (wordCount.keyId != null) + keyWordCountActor.tell( + new ChangeWordCount(wordCount.keyId, wordCount.wordCount, wordCount.wordCountDiff), + self()); + }) + .match(Collection.class, t -> { + Collection wordCounts = (Collection) t; - if (wordCount.projectId != null) - projectWordCountActor.tell( - new ChangeWordCount(wordCount.projectId, wordCount.wordCount, wordCount.wordCountDiff), - self()); - if (wordCount.localeId != null) - localeWordCountActor.tell( - new ChangeWordCount(wordCount.localeId, wordCount.wordCount, wordCount.wordCountDiff), - self()); - if (wordCount.keyId != null) - keyWordCountActor.tell( - new ChangeWordCount(wordCount.keyId, wordCount.wordCount, wordCount.wordCountDiff), - self()); - } else if (msg instanceof Collection) { - @SuppressWarnings("unchecked") - Collection wordCounts = (Collection) msg; - - wordCounts.stream() - .map(wc -> new ChangeWordCount(wc.projectId, wc.wordCount, wc.wordCountDiff)) - .collect(groupingBy(wc -> wc.id, reducing(ChangeWordCount::merge))) - .forEach((projectId, wc) -> projectWordCountActor.tell(wc.get(), null)); - wordCounts.stream() - .map(wc -> new ChangeWordCount(wc.localeId, wc.wordCount, wc.wordCountDiff)) - .collect(groupingBy(wc -> wc.id, reducing(ChangeWordCount::merge))) - .forEach((localeId, wc) -> localeWordCountActor.tell(wc.get(), null)); - wordCounts.stream().map(wc -> new ChangeWordCount(wc.keyId, wc.wordCount, wc.wordCountDiff)) - .collect(groupingBy(wc -> wc.id, reducing(ChangeWordCount::merge))) - .forEach((keyId, wc) -> keyWordCountActor.tell(wc.get(), null)); - } + wordCounts.stream() + .map(wc -> new ChangeWordCount(wc.projectId, wc.wordCount, wc.wordCountDiff)) + .collect(groupingBy(wc -> wc.id, reducing(ChangeWordCount::merge))) + .forEach((projectId, wc) -> projectWordCountActor.tell(wc.get(), null)); + wordCounts.stream() + .map(wc -> new ChangeWordCount(wc.localeId, wc.wordCount, wc.wordCountDiff)) + .collect(groupingBy(wc -> wc.id, reducing(ChangeWordCount::merge))) + .forEach((localeId, wc) -> localeWordCountActor.tell(wc.get(), null)); + wordCounts.stream().map(wc -> new ChangeWordCount(wc.keyId, wc.wordCount, wc.wordCountDiff)) + .collect(groupingBy(wc -> wc.id, reducing(ChangeWordCount::merge))) + .forEach((keyId, wc) -> keyWordCountActor.tell(wc.get(), null)); + }) + .build(); } } diff --git a/app/actors/NotificationActor.java b/app/actors/NotificationActor.java index 7547a0a1..7959c833 100644 --- a/app/actors/NotificationActor.java +++ b/app/actors/NotificationActor.java @@ -2,14 +2,14 @@ import actors.NotificationProtocol.FollowNotification; import actors.NotificationProtocol.PublishNotification; -import akka.actor.UntypedActor; +import akka.actor.AbstractActor; import services.NotificationService; import javax.inject.Inject; import javax.inject.Singleton; @Singleton -public class NotificationActor extends UntypedActor { +public class NotificationActor extends AbstractActor { public static final String NAME = "notification-actor"; @@ -21,15 +21,12 @@ public NotificationActor(NotificationService notificationService) { } @Override - public void onReceive(Object msg) throws Throwable { - if (msg instanceof PublishNotification) { - PublishNotification t = (PublishNotification) msg; - - notificationService.publish(t.id, t.type, t.name, t.contentId, t.userId, t.projectId); - } else if (msg instanceof FollowNotification) { - FollowNotification t = (FollowNotification) msg; - - notificationService.follow(t.userId, t.projectId); - } + public Receive createReceive() { + return receiveBuilder() + .match(PublishNotification.class, + t -> notificationService.publish(t.id, t.type, t.name, t.contentId, t.userId, t.projectId)) + .match(FollowNotification.class, + t -> notificationService.follow(t.userId, t.projectId)) + .build(); } } diff --git a/app/actors/ProjectWordCountActor.java b/app/actors/ProjectWordCountActor.java index c425a767..00ef4768 100644 --- a/app/actors/ProjectWordCountActor.java +++ b/app/actors/ProjectWordCountActor.java @@ -1,7 +1,7 @@ package actors; import actors.WordCountProtocol.ChangeWordCount; -import akka.actor.UntypedActor; +import akka.actor.AbstractActor; import services.ProjectService; import javax.inject.Inject; @@ -12,7 +12,7 @@ * @version 6 Jun 2017 */ @Singleton -public class ProjectWordCountActor extends UntypedActor { +public class ProjectWordCountActor extends AbstractActor { public static final String NAME = "project-word-count-actor"; private final ProjectService projectService; @@ -22,14 +22,11 @@ public ProjectWordCountActor(ProjectService projectService) { this.projectService = projectService; } - /** - * {@inheritDoc} - */ @Override - public void onReceive(Object msg) throws Throwable { - if (msg instanceof ChangeWordCount) { - ChangeWordCount wordCount = (ChangeWordCount) msg; - projectService.increaseWordCountBy(wordCount.id, wordCount.wordCountDiff); - } + public Receive createReceive() { + return receiveBuilder() + .match(ChangeWordCount.class, + wordCount -> projectService.increaseWordCountBy(wordCount.id, wordCount.wordCountDiff, null /* FIXME */)) + .build(); } } diff --git a/app/auth/AccessTokenAuthenticator.java b/app/auth/AccessTokenAuthenticator.java index d8e0b07a..da97d2d0 100644 --- a/app/auth/AccessTokenAuthenticator.java +++ b/app/auth/AccessTokenAuthenticator.java @@ -26,7 +26,7 @@ public AccessTokenAuthenticator(Injector injector, String clientName) { public void validate(TokenCredentials credentials, WebContext context) { init(); - AccessToken accessToken = accessTokenService.byKey(credentials.getToken()); + AccessToken accessToken = accessTokenService.byKey(credentials.getToken(), null) /* FIXME */; if (accessToken == null) { throw new CredentialsException("Could not validate access token"); diff --git a/app/auth/CustomCallbackLogic.java b/app/auth/CustomCallbackLogic.java index d93f0cfe..274637ce 100644 --- a/app/auth/CustomCallbackLogic.java +++ b/app/auth/CustomCallbackLogic.java @@ -29,8 +29,9 @@ public R perform(C context, Config config, HttpActionAdapter httpActionAda R result = delegate.perform(context, config, httpActionAdapter, defaultUrl, saveInSession, multiProfile, renewSession, client); try { + // INFO: providing null for request in this context is okay authProvider.loggedInProfile(context) - .ifPresent(profile -> authProvider.updateUser(profile)); + .ifPresent(profile -> authProvider.updateUser(profile, null)); } catch (UserUnregisteredException e) { return httpActionAdapter.adapt(new SeeOtherAction(routes.Application.indexUi().url() + "/register"), context); } diff --git a/app/com/gettextresourcebundle/GettextResourceBundle.java b/app/com/gettextresourcebundle/GettextResourceBundle.java index ee98622b..52e603ae 100644 --- a/app/com/gettextresourcebundle/GettextResourceBundle.java +++ b/app/com/gettextresourcebundle/GettextResourceBundle.java @@ -3,7 +3,7 @@ */ package com.gettextresourcebundle; -import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.text.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -16,7 +16,7 @@ /** * @author Tom Schaible - * + * * A resource bundle that is created from a gettext PO file */ public class GettextResourceBundle extends ResourceBundle { @@ -32,9 +32,9 @@ public GettextResourceBundle(Reader reader) { /** * initialize the ResourceBundle from a PO file - * + * * if - * + * * @param reader the reader to read the contents of the PO file from */ private void init(LineNumberReader reader) { @@ -106,7 +106,7 @@ private void init(LineNumberReader reader) { /* * (non-Javadoc) - * + * * @see java.util.ResourceBundle#getKeys() */ @Override @@ -116,7 +116,7 @@ public Enumeration getKeys() { /* * (non-Javadoc) - * + * * @see java.util.ResourceBundle#handleGetObject(java.lang.String) */ @Override diff --git a/app/controllers/AccessTokensApi.java b/app/controllers/AccessTokensApi.java index 1327756f..78d759b2 100644 --- a/app/controllers/AccessTokensApi.java +++ b/app/controllers/AccessTokensApi.java @@ -2,18 +2,7 @@ import criterias.AccessTokenCriteria; import dto.AccessToken; -import dto.errors.ConstraintViolationError; -import dto.errors.GenericError; -import dto.errors.NotFoundError; -import dto.errors.PermissionError; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import io.swagger.v3.oas.annotations.Parameter; import play.inject.Injector; import play.mvc.Http; import play.mvc.Result; @@ -23,7 +12,7 @@ import javax.inject.Inject; import java.util.concurrent.CompletionStage; -@io.swagger.annotations.Api(value = "Access Tokens", produces = "application/json") +////@io.swagger.annotations.Api(value = "Access Tokens", produces = "application/json") public class AccessTokensApi extends AbstractApi { private static final String TYPE = "User"; @@ -49,83 +38,83 @@ public AccessTokensApi(Injector injector, AuthProvider authProvider, AccessToken super(injector, authProvider, accessTokenApiService); } - @ApiOperation(value = FIND, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.UsersPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) +// @ApiOperation(value = FIND, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.UsersPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) public CompletionStage find(Http.Request request) { return toJsons(() -> api.find(AccessTokenCriteria.from(request))); } - @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage get(Http.Request request, @ApiParam(value = ACCESS_TOKEN_ID) long id) { +// @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage get(Http.Request request, @Parameter(name = ACCESS_TOKEN_ID) long id) { return toJson(() -> api.get(request, id)); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = CREATE, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.User.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = CREATE, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) public CompletionStage create(Http.Request request) { return toJson(() -> api.create(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = UPDATE, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.User.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = UPDATE, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) public CompletionStage update(Http.Request request) { return toJson(() -> api.update(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = DELETE, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.User.class), - @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage delete(Http.Request request, @ApiParam(value = PROJECT_ID) long id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = DELETE, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage delete(Http.Request request, @Parameter(name = PROJECT_ID) long id) { return toJson(() -> api.delete(request, id)); } } diff --git a/app/controllers/ActivitiesApi.java b/app/controllers/ActivitiesApi.java index c79976df..f90ca73a 100644 --- a/app/controllers/ActivitiesApi.java +++ b/app/controllers/ActivitiesApi.java @@ -2,15 +2,8 @@ import criterias.LogEntryCriteria; import dto.Activity; -import dto.errors.GenericError; -import dto.errors.PermissionError; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.info.Info; import play.inject.Injector; import play.mvc.Http; import play.mvc.Result; @@ -21,7 +14,7 @@ import java.util.UUID; import java.util.concurrent.CompletionStage; -@io.swagger.annotations.Api(value = "Activities", produces = "application/json") +@OpenAPIDefinition(info = @Info(title = "Activities", version = "1.0")) public class ActivitiesApi extends AbstractApi { private static final String FIND = "Find activites"; private static final String FIND_RESPONSE = "Found activities"; @@ -39,20 +32,30 @@ protected ActivitiesApi(Injector injector, AuthProvider authProvider, super(injector, authProvider, activityApiService); } - @ApiOperation(value = FIND, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.ActivitiesPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_TYPES, value = TYPES, dataType = "string", - paramType = "query")}) +// @Operation(summary = FIND,parameters = { +// @Parameter(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_TYPES, value = TYPES, dataType = "string", +// paramType = "query") +// } +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.ActivitiesPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_TYPES, value = TYPES, dataType = "string", +// paramType = "query")}) public CompletionStage find(Http.Request request) { return toJsons(() -> api.find(LogEntryCriteria.from(request))); } @@ -60,13 +63,13 @@ public CompletionStage find(Http.Request request) { /** * {@inheritDoc} */ - @ApiOperation(value = ACTIVITY, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = ACTIVITY_RESPONSE, response = dto.AggregatesPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) +// @ApiOperation(value = ACTIVITY, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = ACTIVITY_RESPONSE, response = dto.AggregatesPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) public CompletionStage activity(Http.Request request) { return toJsons(() -> api.getAggregates(LogEntryCriteria.from(request))); } diff --git a/app/controllers/AuthClientsApi.java b/app/controllers/AuthClientsApi.java index f1989918..2f3b26f3 100644 --- a/app/controllers/AuthClientsApi.java +++ b/app/controllers/AuthClientsApi.java @@ -1,9 +1,5 @@ package controllers; -import dto.AuthClient; -import dto.errors.GenericError; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; import mappers.AuthClientMapper; import play.inject.Injector; import play.mvc.Result; @@ -25,9 +21,9 @@ public AuthClientsApi(Injector injector, AuthClientApiService authClientApiServi this.authClientApiService = authClientApiService; } - @ApiResponses({ - @ApiResponse(code = 200, message = FIND_RESPONSE, response = AuthClient[].class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiResponses({ +// @ApiResponse(code = 200, message = FIND_RESPONSE, response = AuthClient[].class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) public CompletionStage find() { return toJsonList(() -> authClientApiService .getClients() diff --git a/app/controllers/FeatureFlagsApi.java b/app/controllers/FeatureFlagsApi.java index 223e0fe2..b9322784 100644 --- a/app/controllers/FeatureFlagsApi.java +++ b/app/controllers/FeatureFlagsApi.java @@ -2,18 +2,7 @@ import criterias.UserFeatureFlagCriteria; import dto.UserFeatureFlag; -import dto.errors.ConstraintViolationError; -import dto.errors.GenericError; -import dto.errors.NotFoundError; -import dto.errors.PermissionError; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import io.swagger.v3.oas.annotations.Parameter; import play.inject.Injector; import play.mvc.Http; import play.mvc.Result; @@ -24,7 +13,7 @@ import java.util.UUID; import java.util.concurrent.CompletionStage; -@io.swagger.annotations.Api(value = "Feature Flags", produces = "application/json") +////@io.swagger.annotations.Api(value = "Feature Flags", produces = "application/json") public class FeatureFlagsApi extends AbstractApi { private static final String TYPE = "User"; @@ -53,83 +42,83 @@ public FeatureFlagsApi( super(injector, authProvider, userFeatureFlagApiService); } - @ApiOperation(value = FIND, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.UsersPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) +// @ApiOperation(value = FIND, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.UsersPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) public CompletionStage find(Http.Request request) { return toJsons(() -> api.find(UserFeatureFlagCriteria.from(request))); } - @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage get(Http.Request request, @ApiParam(value = FEATURE_FLAG_ID) UUID id) { +// @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage get(Http.Request request, @Parameter(name = FEATURE_FLAG_ID) UUID id) { return toJson(() -> api.get(request, id)); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = CREATE, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.User.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = CREATE, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) public CompletionStage create(Http.Request request) { return toJson(() -> api.create(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = UPDATE, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.User.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = UPDATE, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) public CompletionStage update(Http.Request request) { return toJson(() -> api.update(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = DELETE, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.User.class), - @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage delete(Http.Request request, @ApiParam(value = FEATURE_FLAG_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = DELETE, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage delete(Http.Request request, @Parameter(name = FEATURE_FLAG_ID) UUID id) { return toJson(() -> api.delete(request, id)); } } diff --git a/app/controllers/KeysApi.java b/app/controllers/KeysApi.java index 740ab2ed..d6ff1f46 100644 --- a/app/controllers/KeysApi.java +++ b/app/controllers/KeysApi.java @@ -3,18 +3,7 @@ import com.fasterxml.jackson.databind.node.NullNode; import criterias.KeyCriteria; import dto.Key; -import dto.errors.ConstraintViolationError; -import dto.errors.GenericError; -import dto.errors.NotFoundError; -import dto.errors.PermissionError; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import io.swagger.v3.oas.annotations.Parameter; import models.ProjectRole; import org.apache.commons.lang3.StringUtils; import play.inject.Injector; @@ -31,11 +20,11 @@ import java.util.concurrent.CompletionStage; import java.util.function.Function; -/** - * @author resamsel - * @version 10 Jan 2017 - */ -@io.swagger.annotations.Api(value = "Keys", produces = "application/json") +///** +// * @author resamsel +// * @version 10 Jan 2017 +// */ +////@io.swagger.annotations.Api(value = "Keys", produces = "application/json") public class KeysApi extends AbstractApi { private static final String TYPE = "Key"; @@ -65,28 +54,28 @@ public KeysApi(Injector injector, AuthProvider authProvider, KeyApiService keyAp super(injector, authProvider, keyApiService); } - @ApiOperation(value = FIND, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = KEY_READ, description = KEY_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.KeysPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_FETCH, value = FETCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_LOCALE_ID, value = LOCALE_ID, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_MISSING, value = MISSING, - dataType = "string", paramType = "query")}) - public CompletionStage find(Http.Request request, @ApiParam(value = PROJECT_ID) UUID projectId) { +// @ApiOperation(value = FIND, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = KEY_READ, description = KEY_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.KeysPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_FETCH, value = FETCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_LOCALE_ID, value = LOCALE_ID, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_MISSING, value = MISSING, +// dataType = "string", paramType = "query")}) + public CompletionStage find(Http.Request request, @Parameter(name = PROJECT_ID) UUID projectId) { return toJsons(() -> api.find( KeyCriteria.from(request).withProjectId(projectId), criteria -> checkProjectRole( @@ -100,45 +89,45 @@ public CompletionStage find(Http.Request request, @ApiParam(value = PROJ ); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = KEY_READ, description = KEY_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Key.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage get(Http.Request request, @ApiParam(value = KEY_ID) UUID id, - @ApiParam(value = FETCH) String fetch) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = KEY_READ, description = KEY_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Key.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage get(Http.Request request, @Parameter(name = KEY_ID) UUID id, + @Parameter(name = FETCH) String fetch) { return toJson(() -> api.get(request, id, StringUtils.split(fetch, ","))); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = KEY_READ, description = KEY_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Key.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = KEY_READ, description = KEY_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Key.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) public CompletionStage byOwnerAndProjectNameAndName( Http.Request request, - @ApiParam(value = USER_USERNAME) String username, - @ApiParam(value = PROJECT_NAME) String projectName, - @ApiParam(value = KEY_NAME) String keyName, - @ApiParam(value = FETCH) String fetch) { + @Parameter(name = USER_USERNAME) String username, + @Parameter(name = PROJECT_NAME) String projectName, + @Parameter(name = KEY_NAME) String keyName, + @Parameter(name = FETCH) String fetch) { return key( request, username, @@ -149,66 +138,66 @@ public CompletionStage byOwnerAndProjectNameAndName( .exceptionally(this::handleException); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = CREATE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = KEY_WRITE, description = KEY_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.Key.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = CREATE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = KEY_WRITE, description = KEY_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.Key.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) @BodyParser.Of(BodyParser.Json.class) public CompletionStage create(Http.Request request) { return toJson(() -> api.create(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = UPDATE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = KEY_WRITE, description = KEY_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.Key.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = UPDATE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = KEY_WRITE, description = KEY_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.Key.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) @BodyParser.Of(BodyParser.Json.class) public CompletionStage update(Http.Request request) { return toJson(() -> api.update(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = DELETE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = KEY_WRITE, description = KEY_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.Key.class), - @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage delete(Http.Request request, @ApiParam(value = KEY_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = DELETE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = KEY_WRITE, description = KEY_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.Key.class), +// @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage delete(Http.Request request, @Parameter(name = KEY_ID) UUID id) { return toJson(() -> api.delete(request, id)); } diff --git a/app/controllers/LocalesApi.java b/app/controllers/LocalesApi.java index 61d5f4e0..9aed720b 100644 --- a/app/controllers/LocalesApi.java +++ b/app/controllers/LocalesApi.java @@ -3,18 +3,7 @@ import com.fasterxml.jackson.databind.node.NullNode; import criterias.LocaleCriteria; import dto.Locale; -import dto.errors.ConstraintViolationError; -import dto.errors.GenericError; -import dto.errors.NotFoundError; -import dto.errors.PermissionError; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import io.swagger.v3.oas.annotations.Parameter; import models.ProjectRole; import org.apache.commons.lang3.StringUtils; import play.inject.Injector; @@ -37,7 +26,7 @@ * @author resamsel * @version 10 Jan 2017 */ -@io.swagger.annotations.Api(value = "Locales", produces = "application/json") +//@io.swagger.annotations.Api(value = "Locales", produces = "application/json") public class LocalesApi extends AbstractApi { private static final String TYPE = "Locale"; @@ -75,33 +64,33 @@ public LocalesApi(Injector injector, AuthProvider authProvider, LocaleApiService super(injector, authProvider, localeApiService); } - @ApiOperation(value = FIND, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION)})) - @ApiResponses({ - @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.LocalesPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_LOCALE_NAME, value = LOCALE_NAME, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_FETCH, value = FETCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_MESSAGES_KEY_NAME, value = MESSAGES_KEY_NAME, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_KEY_ID, value = KEY_ID, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_MISSING, value = MISSING, - dataType = "string", paramType = "query")}) - public CompletionStage find(Http.Request request, @ApiParam(value = "The project ID") UUID projectId) { +// @ApiOperation(value = FIND, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION)})) +// @ApiResponses({ +// @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.LocalesPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LOCALE_NAME, value = LOCALE_NAME, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_FETCH, value = FETCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_MESSAGES_KEY_NAME, value = MESSAGES_KEY_NAME, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_KEY_ID, value = KEY_ID, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_MISSING, value = MISSING, +// dataType = "string", paramType = "query")}) + public CompletionStage find(Http.Request request, @Parameter(name = "The project ID") UUID projectId) { return toJsons(() -> api.find( LocaleCriteria.from(request).withProjectId(projectId), criteria -> checkProjectRole( @@ -115,44 +104,44 @@ public CompletionStage find(Http.Request request, @ApiParam(value = "The ); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Locale.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage get(Http.Request request, @ApiParam(value = LOCALE_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Locale.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage get(Http.Request request, @Parameter(name = LOCALE_ID) UUID id) { return toJson(() -> api.get(request, id)); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Locale.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Locale.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) public CompletionStage byOwnerAndProjectNameAndName( Http.Request request, - @ApiParam(value = USER_USERNAME) String username, - @ApiParam(value = PROJECT_NAME) String projectName, - @ApiParam(value = LOCALE_NAME) String localeName, - @ApiParam(value = FETCH) String fetch) { + @Parameter(name = USER_USERNAME) String username, + @Parameter(name = PROJECT_NAME) String projectName, + @Parameter(name = LOCALE_NAME) String localeName, + @Parameter(name = FETCH) String fetch) { return locale( request, username, @@ -163,112 +152,112 @@ public CompletionStage byOwnerAndProjectNameAndName( .exceptionally(this::handleException); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = CREATE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = LOCALE_WRITE, description = LOCALE_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.Locale.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = CREATE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = LOCALE_WRITE, description = LOCALE_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.Locale.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) @BodyParser.Of(BodyParser.Json.class) public CompletionStage create(Http.Request request) { return toJson(() -> api.create(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = UPDATE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = LOCALE_WRITE, description = LOCALE_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.Locale.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = UPDATE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = LOCALE_WRITE, description = LOCALE_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.Locale.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) @BodyParser.Of(BodyParser.Json.class) public CompletionStage update(Http.Request request) { return toJson(() -> api.update(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = DELETE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = LOCALE_WRITE, description = LOCALE_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.Project.class), - @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage delete(Http.Request request, @ApiParam(value = LOCALE_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = DELETE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = LOCALE_WRITE, description = LOCALE_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.Project.class), +// @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage delete(Http.Request request, @Parameter(name = LOCALE_ID) UUID id) { return toJson(() -> api.delete(request, id)); } - @ApiOperation(value = UPLOAD, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_WRITE, description = MESSAGE_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPLOAD_RESPONSE, response = dto.Locale.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage upload(Http.Request request, @ApiParam(value = LOCALE_ID) UUID localeId) { +// @ApiOperation(value = UPLOAD, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_WRITE, description = MESSAGE_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPLOAD_RESPONSE, response = dto.Locale.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage upload(Http.Request request, @Parameter(name = LOCALE_ID) UUID localeId) { return toJson(() -> api.upload(localeId, request)); } - @ApiOperation(value = DOWNLOAD, produces = "text/plain", authorizations = @Authorization( - value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DOWNLOAD_RESPONSE), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) +// @ApiOperation(value = DOWNLOAD, produces = "text/plain", authorizations = @Authorization( +// value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DOWNLOAD_RESPONSE), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) public CompletionStage download(Http.Request request, UUID localeId, String fileType) { return CompletableFuture - .supplyAsync(() -> api.download(request, localeId, fileType, response()), + .supplyAsync(() -> api.download(request, localeId, fileType), executionContext.current()) - .thenApply(data -> ok(new ByteArrayInputStream(data))).exceptionally(this::handleException); + .exceptionally(this::handleException); } - @ApiOperation(value = DOWNLOAD, produces = "text/plain", authorizations = @Authorization( - value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DOWNLOAD_RESPONSE), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) +// @ApiOperation(value = DOWNLOAD, produces = "text/plain", authorizations = @Authorization( +// value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = LOCALE_READ, description = LOCALE_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DOWNLOAD_RESPONSE), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) public CompletionStage downloadBy(Http.Request request, String username, String projectName, String localeName, String fileType) { return locale( @@ -276,8 +265,7 @@ public CompletionStage downloadBy(Http.Request request, String username, username, projectName, localeName, - locale -> ok( - new ByteArrayInputStream(api.download(request, locale.id, fileType, response()))) + locale -> api.download(request, locale.id, fileType) ).exceptionally(this::handleException); } diff --git a/app/controllers/MembersApi.java b/app/controllers/MembersApi.java index c69c63c9..1c3547e6 100644 --- a/app/controllers/MembersApi.java +++ b/app/controllers/MembersApi.java @@ -2,19 +2,7 @@ import criterias.ProjectUserCriteria; import dto.ProjectUser; -import dto.errors.ConstraintViolationError; -import dto.errors.GenericError; -import dto.errors.NotFoundError; -import dto.errors.PermissionError; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import io.swagger.v3.oas.annotations.Parameter; import models.ProjectRole; import org.apache.commons.lang3.StringUtils; import play.inject.Injector; @@ -28,11 +16,11 @@ import java.util.UUID; import java.util.concurrent.CompletionStage; -/** - * @author resamsel - * @version 10 Jan 2017 - */ -@Api(value = "Members", produces = "application/json") +///** +// * @author resamsel +// * @version 10 Jan 2017 +// */ +//@Api(value = "Members", produces = "application/json") public class MembersApi extends AbstractApi { private static final String TYPE = "Member"; @@ -69,26 +57,26 @@ public MembersApi(Injector injector, AuthProvider authProvider, ProjectUserApiSe this.authProvider = authProvider; } - @ApiOperation(value = FIND, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MEMBER_READ, description = MEMBER_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.MembersPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_FETCH, value = FETCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_ROLES, value = FETCH, dataType = "string", - paramType = "query")}) - public CompletionStage find(Http.Request request, @ApiParam(value = PROJECT_ID) UUID projectId) { +// @ApiOperation(value = FIND, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MEMBER_READ, description = MEMBER_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.MembersPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_FETCH, value = FETCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_ROLES, value = FETCH, dataType = "string", +// paramType = "query")}) + public CompletionStage find(Http.Request request, @Parameter(name = PROJECT_ID) UUID projectId) { return toJsons(() -> api.find( ProjectUserCriteria.from(request).withProjectId(projectId), criteria -> checkProjectRole( @@ -102,85 +90,85 @@ public CompletionStage find(Http.Request request, @ApiParam(value = PROJ ); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MEMBER_READ, description = MEMBER_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = ProjectUser.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage get(Http.Request request, @ApiParam(value = MEMBER_ID) Long id, - @ApiParam(value = FETCH) String fetch) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MEMBER_READ, description = MEMBER_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = ProjectUser.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage get(Http.Request request, @Parameter(name = MEMBER_ID) Long id, + @Parameter(name = FETCH) String fetch) { return toJson(() -> api.get(request, id, StringUtils.split(fetch, ","))); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = CREATE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MEMBER_WRITE, description = MEMBER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = ProjectUser.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = CREATE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MEMBER_WRITE, description = MEMBER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = ProjectUser.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) @BodyParser.Of(BodyParser.Json.class) public CompletionStage create(Http.Request request) { return toJson(() -> api.create(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = UPDATE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MEMBER_WRITE, description = MEMBER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = ProjectUser.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = UPDATE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MEMBER_WRITE, description = MEMBER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = ProjectUser.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) @BodyParser.Of(BodyParser.Json.class) public CompletionStage update(Http.Request request) { return toJson(() -> api.update(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = DELETE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MEMBER_WRITE, description = MEMBER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = ProjectUser.class), - @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage delete(Http.Request request, @ApiParam(value = MEMBER_ID) Long id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = DELETE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MEMBER_WRITE, description = MEMBER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = ProjectUser.class), +// @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage delete(Http.Request request, @Parameter(name = MEMBER_ID) Long id) { return toJson(() -> api.delete(request, id)); } } diff --git a/app/controllers/NotificationsApi.java b/app/controllers/NotificationsApi.java index 4b5a72a2..099c7620 100644 --- a/app/controllers/NotificationsApi.java +++ b/app/controllers/NotificationsApi.java @@ -3,19 +3,11 @@ import criterias.NotificationCriteria; import dto.NotificationsPaged; import dto.PermissionException; -import dto.errors.GenericError; -import dto.errors.PermissionError; import io.getstream.client.exception.StreamClientException; import io.getstream.client.model.activities.AggregatedActivity; import io.getstream.client.model.activities.SimpleActivity; import io.getstream.client.model.beans.StreamResponse; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import mappers.AggregatedNotificationMapper; import models.Scope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,7 +26,7 @@ * @author resamsel * @version 10 Jan 2017 */ -@io.swagger.annotations.Api(value = "Notifications", produces = "application/json") +//@io.swagger.annotations.Api(value = "Notifications", produces = "application/json") public class NotificationsApi extends AbstractBaseApi { private static final Logger LOGGER = LoggerFactory.getLogger(NotificationsApi.class); @@ -44,29 +36,31 @@ public class NotificationsApi extends AbstractBaseApi { private final NotificationService notificationService; private final PermissionService permissionService; + private final AggregatedNotificationMapper aggregatedNotificationMapper; @Inject - public NotificationsApi(Injector injector, NotificationService notificationService) { + public NotificationsApi(Injector injector, NotificationService notificationService, AggregatedNotificationMapper aggregatedNotificationMapper) { super(injector); this.notificationService = notificationService; this.permissionService = injector.instanceOf(PermissionService.class); + this.aggregatedNotificationMapper = aggregatedNotificationMapper; } - @ApiOperation(value = FIND, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) - @ApiResponses({ - @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.NotificationsPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) +// @ApiOperation(value = FIND, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) +// @ApiResponses({ +// @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.NotificationsPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) public CompletionStage find(Http.Request request) { StreamResponse> notifications; try { @@ -78,6 +72,7 @@ public CompletionStage find(Http.Request request) { return CompletableFuture.completedFuture(handleException(e)); } - return toJsons(() -> new NotificationsPaged(notifications)); + + return toJsons(() -> new NotificationsPaged(notifications != null ? aggregatedNotificationMapper.toDto(notifications.getResults(), request) : null)); } } diff --git a/app/controllers/ProjectsApi.java b/app/controllers/ProjectsApi.java index d420271e..353bce44 100644 --- a/app/controllers/ProjectsApi.java +++ b/app/controllers/ProjectsApi.java @@ -2,18 +2,7 @@ import criterias.ProjectCriteria; import dto.Project; -import dto.errors.ConstraintViolationError; -import dto.errors.GenericError; -import dto.errors.NotFoundError; -import dto.errors.PermissionError; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import io.swagger.v3.oas.annotations.Parameter; import models.ProjectRole; import org.apache.commons.lang3.StringUtils; import play.data.FormFactory; @@ -32,7 +21,7 @@ * @author resamsel * @version 10 Jan 2017 */ -@io.swagger.annotations.Api(value = "Projects", produces = "application/json") +//@io.swagger.annotations.Api(value = "Projects", produces = "application/json") public class ProjectsApi extends AbstractApi { private static final String TYPE = "Project"; @@ -66,62 +55,62 @@ public ProjectsApi(Injector injector, AuthProvider authProvider, ProjectApiServi this.projectApiService = projectApiService; } - /** - * {@inheritDoc} - */ - @ApiOperation(value = FIND, - authorizations = @Authorization(value = AUTHORIZATION, scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION)})) - @ApiResponses({ - @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.ProjectsPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class) - }) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH_FIELD, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_FETCH, value = FETCH, dataType = "string", paramType = "query") - }) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = FIND, +// authorizations = @Authorization(value = AUTHORIZATION, scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION)})) +// @ApiResponses({ +// @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.ProjectsPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class) +// }) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH_FIELD, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_FETCH, value = FETCH, dataType = "string", paramType = "query") +// }) public CompletionStage find(Http.Request request) { return toJsons(() -> api.find(ProjectCriteria.from(request).withFetches())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Project.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage get(Http.Request request, @ApiParam(value = PROJECT_ID) UUID id, - @ApiParam(value = FETCH) String fetch) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Project.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage get(Http.Request request, @Parameter(name = PROJECT_ID) UUID id, + @Parameter(name = FETCH) String fetch) { return toJson(() -> api.get(request, id, StringUtils.split(fetch, ","))); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Project.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Project.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) public CompletionStage byOwnerAndName( Http.Request request, - @ApiParam(value = USER_USERNAME) String username, - @ApiParam(value = PROJECT_NAME) String projectName, - @ApiParam(value = FETCH) String fetch) { + @Parameter(name = USER_USERNAME) String username, + @Parameter(name = PROJECT_NAME) String projectName, + @Parameter(name = FETCH) String fetch) { return toJson(() -> api.byOwnerAndName( request, username, projectName, @@ -130,90 +119,90 @@ public CompletionStage byOwnerAndName( ); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.AggregatesPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage activity(Http.Request request, @ApiParam(value = PROJECT_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.AggregatesPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage activity(Http.Request request, @Parameter(name = PROJECT_ID) UUID id) { return toJsons(() -> api.activity(request, id)); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = CREATE, authorizations = @Authorization(value = AUTHORIZATION, scopes = { - @AuthorizationScope(scope = PROJECT_WRITE, description = PROJECT_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.Project.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = CREATE, authorizations = @Authorization(value = AUTHORIZATION, scopes = { +// @AuthorizationScope(scope = PROJECT_WRITE, description = PROJECT_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.Project.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) public CompletionStage create(Http.Request request) { return toJson(() -> api.create(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = UPDATE, authorizations = @Authorization(value = AUTHORIZATION, scopes = { - @AuthorizationScope(scope = PROJECT_WRITE, description = PROJECT_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.Project.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = UPDATE, authorizations = @Authorization(value = AUTHORIZATION, scopes = { +// @AuthorizationScope(scope = PROJECT_WRITE, description = PROJECT_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.Project.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) public CompletionStage update(Http.Request request) { return toJson(() -> api.update(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = DELETE, authorizations = @Authorization(value = AUTHORIZATION, scopes = { - @AuthorizationScope(scope = PROJECT_WRITE, description = PROJECT_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.Project.class), - @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage delete(Http.Request request, @ApiParam(value = PROJECT_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = DELETE, authorizations = @Authorization(value = AUTHORIZATION, scopes = { +// @AuthorizationScope(scope = PROJECT_WRITE, description = PROJECT_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.Project.class), +// @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage delete(Http.Request request, @Parameter(name = PROJECT_ID) UUID id) { return toJson(() -> api.delete(request, id)); } - @ApiOperation(value = SEARCH, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION)})) - @ApiResponses({ - @ApiResponse(code = 200, message = SEARCH_RESPONSE, response = dto.SearchResponse.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH_FIELD, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) +// @ApiOperation(value = SEARCH, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION)})) +// @ApiResponses({ +// @ApiResponse(code = 200, message = SEARCH_RESPONSE, response = dto.SearchResponse.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH_FIELD, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) public CompletionStage search(Http.Request request, UUID projectId) { return toJsonSearch(() -> projectApiService.search( request, projectId, - FormUtils.Search.bindFromRequest(injector.instanceOf(FormFactory.class), configuration) + FormUtils.Search.bindFromRequest(injector.instanceOf(FormFactory.class), configuration, request) .get() )); } diff --git a/app/controllers/TranslationsApi.java b/app/controllers/TranslationsApi.java index ada0cfd2..3fba7364 100644 --- a/app/controllers/TranslationsApi.java +++ b/app/controllers/TranslationsApi.java @@ -2,18 +2,7 @@ import criterias.MessageCriteria; import dto.Message; -import dto.errors.ConstraintViolationError; -import dto.errors.GenericError; -import dto.errors.NotFoundError; -import dto.errors.PermissionError; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import io.swagger.v3.oas.annotations.Parameter; import models.ProjectRole; import play.inject.Injector; import play.mvc.BodyParser; @@ -30,7 +19,7 @@ * @author resamsel * @version 10 Jan 2017 */ -@io.swagger.annotations.Api(value = "Messages", produces = "application/json") +//@io.swagger.annotations.Api(value = "Messages", produces = "application/json") public class TranslationsApi extends AbstractApi { private static final String TYPE = "Message"; @@ -61,59 +50,59 @@ public TranslationsApi(Injector injector, AuthProvider authProvider, MessageApiS super(injector, authProvider, messageApiService); } - @ApiOperation(value = FIND, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) - @ApiResponses({ - @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.MessagesPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_LOCALE_ID, value = LOCALE_ID, dataType = "java.util.UUID", - paramType = "query"), - @ApiImplicitParam(name = PARAM_LOCALE_IDS, value = LOCALE_IDS, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_KEY_NAME, value = KEY_NAME, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_KEY_IDS, value = KEY_IDS, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) +// @ApiOperation(value = FIND, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) +// @ApiResponses({ +// @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.MessagesPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LOCALE_ID, value = LOCALE_ID, dataType = "java.util.UUID", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_LOCALE_IDS, value = LOCALE_IDS, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_KEY_NAME, value = KEY_NAME, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_KEY_IDS, value = KEY_IDS, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) public CompletionStage find(Http.Request request) { return findByProject(request, null); } - @ApiOperation(value = FIND, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) - @ApiResponses({ - @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.MessagesPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_LOCALE_ID, value = LOCALE_ID, dataType = "java.util.UUID", - paramType = "query"), - @ApiImplicitParam(name = PARAM_LOCALE_IDS, value = LOCALE_IDS, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_KEY_NAME, value = KEY_NAME, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_KEY_IDS, value = KEY_IDS, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) - public CompletionStage findByProject(Http.Request request, @ApiParam(value = PROJECT_ID) UUID projectId) { +// @ApiOperation(value = FIND, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) +// @ApiResponses({ +// @ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.MessagesPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LOCALE_ID, value = LOCALE_ID, dataType = "java.util.UUID", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_LOCALE_IDS, value = LOCALE_IDS, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_KEY_NAME, value = KEY_NAME, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_KEY_IDS, value = KEY_IDS, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) + public CompletionStage findByProject(Http.Request request, @Parameter(name = PROJECT_ID) UUID projectId) { return toJsons(() -> api.find( MessageCriteria.from(request).withProjectId(projectId), criteria -> checkProjectRole( @@ -125,84 +114,84 @@ public CompletionStage findByProject(Http.Request request, @ApiParam(val ProjectRole.Developer))); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Message.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage get(Http.Request request, @ApiParam(value = MESSAGE_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_READ, description = MESSAGE_READ_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.Message.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage get(Http.Request request, @Parameter(name = MESSAGE_ID) UUID id) { return toJson(() -> api.get(request, id)); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = CREATE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_WRITE, description = MESSAGE_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.Message.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = CREATE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_WRITE, description = MESSAGE_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.Message.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) @BodyParser.Of(BodyParser.Json.class) public CompletionStage create(Http.Request request) { return toJson(() -> api.create(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = UPDATE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_WRITE, description = MESSAGE_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.Message.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = UPDATE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_WRITE, description = MESSAGE_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.Message.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) @BodyParser.Of(BodyParser.Json.class) public CompletionStage update(Http.Request request) { return toJson(() -> api.update(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = DELETE, - authorizations = @Authorization(value = AUTHORIZATION, - scopes = { - @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), - @AuthorizationScope(scope = MESSAGE_WRITE, description = MESSAGE_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.Message.class), - @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage delete(Http.Request request, @ApiParam(value = MESSAGE_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = DELETE, +// authorizations = @Authorization(value = AUTHORIZATION, +// scopes = { +// @AuthorizationScope(scope = PROJECT_READ, description = PROJECT_READ_DESCRIPTION), +// @AuthorizationScope(scope = MESSAGE_WRITE, description = MESSAGE_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.Message.class), +// @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage delete(Http.Request request, @Parameter(name = MESSAGE_ID) UUID id) { return toJson(() -> api.delete(request, id)); } } diff --git a/app/controllers/UsersApi.java b/app/controllers/UsersApi.java index fcddb629..fccbef24 100644 --- a/app/controllers/UsersApi.java +++ b/app/controllers/UsersApi.java @@ -2,18 +2,7 @@ import criterias.UserCriteria; import dto.User; -import dto.errors.ConstraintViolationError; -import dto.errors.GenericError; -import dto.errors.NotFoundError; -import dto.errors.PermissionError; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import io.swagger.annotations.Authorization; -import io.swagger.annotations.AuthorizationScope; +import io.swagger.v3.oas.annotations.Parameter; import org.apache.commons.lang3.StringUtils; import play.inject.Injector; import play.mvc.Http; @@ -29,7 +18,7 @@ * @author resamsel * @version 10 Jan 2017 */ -@io.swagger.annotations.Api(value = "Users", produces = "application/json") +//@io.swagger.annotations.Api(value = "Users", produces = "application/json") public class UsersApi extends AbstractApi { private static final String TYPE = "User"; @@ -61,65 +50,65 @@ public UsersApi(Injector injector, AuthProvider authProvider, UserApiService use super(injector, authProvider, userApiService); } - @ApiOperation(value = FIND, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.UsersPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query"), - @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", - paramType = "query"), - @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), - @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) +// @ApiOperation(value = FIND, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = FIND_RESPONSE, response = dto.UsersPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query"), +// @ApiImplicitParam(name = PARAM_SEARCH, value = SEARCH, dataType = "string", +// paramType = "query"), +// @ApiImplicitParam(name = PARAM_OFFSET, value = OFFSET, dataType = "int", paramType = "query"), +// @ApiImplicitParam(name = PARAM_LIMIT, value = LIMIT, dataType = "int", paramType = "query")}) public CompletionStage find(Http.Request request) { return toJsons(() -> api.find(UserCriteria.from(request))); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage get(Http.Request request, @ApiParam(value = USER_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage get(Http.Request request, @Parameter(name = USER_ID) UUID id) { return toJson(() -> api.get(request, id)); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage byName(Http.Request request, @ApiParam(value = USER_USERNAME) String username, - @ApiParam(value = FETCH) String fetch) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage byName(Http.Request request, @Parameter(name = USER_USERNAME) String username, + @Parameter(name = FETCH) String fetch) { return toJson(() -> api.byUsername(request, username, StringUtils.split(fetch, ","))); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.AggregatesPaged.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage activity(Http.Request request, @ApiParam(value = USER_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.AggregatesPaged.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage activity(Http.Request request, @Parameter(name = USER_ID) UUID id) { return toJsons(() -> api.activity(request, id)); } @@ -127,105 +116,105 @@ public CompletionStage profile(Http.Request request) { return toJson(() -> api.profile(request)); } - @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, - scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) - @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage me(Http.Request request, @ApiParam(value = FETCH) String fetch) { +// @ApiOperation(value = GET, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = @AuthorizationScope(scope = USER_READ, description = USER_READ_DESCRIPTION))) +// @ApiResponses({@ApiResponse(code = 200, message = GET_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage me(Http.Request request, @Parameter(name = FETCH) String fetch) { return toJson(() -> api.me(request, StringUtils.split(fetch, ","))); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = CREATE, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.User.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = CREATE, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = CREATE_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = CREATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) public CompletionStage create(Http.Request request) { return toJson(() -> api.create(request)); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = UPDATE, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.User.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = UPDATE, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPDATE_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = UPDATE_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) public CompletionStage update(Http.Request request) { return toJson(() -> api.update(request, request.body().asJson())); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = DELETE, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.User.class), - @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, - required = true, dataType = "string", paramType = "query")}) - public CompletionStage delete(Http.Request request, @ApiParam(value = PROJECT_ID) UUID id) { +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = DELETE, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = DELETE_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 403, message = INPUT_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({@ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, +// required = true, dataType = "string", paramType = "query")}) + public CompletionStage delete(Http.Request request, @Parameter(name = PROJECT_ID) UUID id) { return toJson(() -> api.delete(request, id)); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = UPDATE_SETTINGS, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = UPDATE_SETTINGS_RESPONSE, response = dto.User.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = UPDATE_SETTINGS_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) - public CompletionStage saveSettings(Http.Request request, @ApiParam(value = USER_ID) UUID id) { - return toJson(() -> api.saveSettings(id, request.body().asJson())); +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = UPDATE_SETTINGS, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = UPDATE_SETTINGS_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = UPDATE_SETTINGS_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) + public CompletionStage saveSettings(Http.Request request, @Parameter(name = USER_ID) UUID id) { + return toJson(() -> api.saveSettings(id, request.body().asJson(), request)); } - /** - * {@inheritDoc} - */ - @ApiOperation(value = PATCH_SETTINGS, authorizations = @Authorization(value = AUTHORIZATION, - scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) - @ApiResponses({@ApiResponse(code = 200, message = PATCH_SETTINGS_RESPONSE, response = dto.User.class), - @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), - @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), - @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), - @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) - @ApiImplicitParams({ - @ApiImplicitParam(name = "body", value = PATCH_SETTINGS_REQUEST, required = true, dataType = TYPE, - paramType = "body"), - @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, - dataType = "string", paramType = "query")}) - public CompletionStage updateSettings(Http.Request request, @ApiParam(value = USER_ID) UUID id) { - return toJson(() -> api.updateSettings(id, request.body().asJson())); +// /** +// * {@inheritDoc} +// */ +// @ApiOperation(value = PATCH_SETTINGS, authorizations = @Authorization(value = AUTHORIZATION, +// scopes = {@AuthorizationScope(scope = USER_WRITE, description = USER_WRITE_DESCRIPTION)})) +// @ApiResponses({@ApiResponse(code = 200, message = PATCH_SETTINGS_RESPONSE, response = dto.User.class), +// @ApiResponse(code = 400, message = INPUT_ERROR, response = ConstraintViolationError.class), +// @ApiResponse(code = 403, message = PERMISSION_ERROR, response = PermissionError.class), +// @ApiResponse(code = 404, message = NOT_FOUND_ERROR, response = NotFoundError.class), +// @ApiResponse(code = 500, message = INTERNAL_SERVER_ERROR, response = GenericError.class)}) +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "body", value = PATCH_SETTINGS_REQUEST, required = true, dataType = TYPE, +// paramType = "body"), +// @ApiImplicitParam(name = PARAM_ACCESS_TOKEN, value = ACCESS_TOKEN, required = true, +// dataType = "string", paramType = "query")}) + public CompletionStage updateSettings(Http.Request request, @Parameter(name = USER_ID) UUID id) { + return toJson(() -> api.updateSettings(id, request.body().asJson(), request)); } } diff --git a/app/criterias/AbstractContextCriteria.java b/app/criterias/AbstractContextCriteria.java index 28a9fd3e..b67e93ef 100644 --- a/app/criterias/AbstractContextCriteria.java +++ b/app/criterias/AbstractContextCriteria.java @@ -4,7 +4,8 @@ import java.util.UUID; public abstract class AbstractContextCriteria> - extends AbstractFetchCriteria implements ContextCriteria { + extends AbstractFetchCriteria + implements ContextCriteria { private UUID loggedInUserId; @CheckForNull diff --git a/app/criterias/AbstractGetCriteria.java b/app/criterias/AbstractGetCriteria.java index 95a10157..49cdb24c 100644 --- a/app/criterias/AbstractGetCriteria.java +++ b/app/criterias/AbstractGetCriteria.java @@ -1,15 +1,24 @@ package criterias; +import play.mvc.Http; + import javax.annotation.Nonnull; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static java.util.Objects.requireNonNull; + public abstract class AbstractGetCriteria, U> - extends AbstractContextCriteria - implements GetCriteria { + extends AbstractContextCriteria implements GetCriteria { private final U id; + private final Http.Request request; - protected AbstractGetCriteria(U id) { + protected AbstractGetCriteria(U id, Http.Request request) { this.id = id; + this.request = requireNonNull(request); } @Nonnull @@ -17,4 +26,9 @@ protected AbstractGetCriteria(U id) { public U getId() { return id; } + + @Override + public Http.Request getRequest() { + return request; + } } diff --git a/app/criterias/DefaultGetCriteria.java b/app/criterias/DefaultGetCriteria.java index f2597e38..bcddb4f2 100644 --- a/app/criterias/DefaultGetCriteria.java +++ b/app/criterias/DefaultGetCriteria.java @@ -1,7 +1,12 @@ package criterias; -public class DefaultGetCriteria extends AbstractGetCriteria, T> { - public DefaultGetCriteria(T id) { - super(id); +import play.mvc.Http; + +public class DefaultGetCriteria, U> + extends AbstractGetCriteria, U> { + public DefaultGetCriteria(U id, Http.Request request, String... fetches) { + super(id, request); + + withFetches(fetches); } } diff --git a/app/criterias/GetCriteria.java b/app/criterias/GetCriteria.java index c52f9976..638eba1b 100644 --- a/app/criterias/GetCriteria.java +++ b/app/criterias/GetCriteria.java @@ -1,12 +1,16 @@ package criterias; +import play.mvc.Http; + import javax.annotation.Nonnull; -public interface GetCriteria extends ContextCriteria { +public interface GetCriteria extends ContextCriteria { @Nonnull - T getId(); + U getId(); + + Http.Request getRequest(); - static GetCriteria of(T id) { - return new DefaultGetCriteria<>(id); + static , U> DefaultGetCriteria from(U id, Http.Request request, String... fetches) { + return new DefaultGetCriteria(id, request, fetches); } } diff --git a/app/dto/NotificationsPaged.java b/app/dto/NotificationsPaged.java index 7e645e1e..03c88852 100644 --- a/app/dto/NotificationsPaged.java +++ b/app/dto/NotificationsPaged.java @@ -1,10 +1,6 @@ package dto; import io.ebean.PagedList; -import io.getstream.client.model.activities.AggregatedActivity; -import io.getstream.client.model.activities.SimpleActivity; -import io.getstream.client.model.beans.StreamResponse; -import mappers.AggregatedNotificationMapper; import java.util.Collections; import java.util.List; @@ -19,9 +15,9 @@ public class NotificationsPaged extends Dto implements PagedList list; - public NotificationsPaged(StreamResponse> delegate) { + public NotificationsPaged(List delegate) { if (delegate != null) - this.list = AggregatedNotificationMapper.toDto(delegate.getResults()); + this.list = delegate; else this.list = Collections.emptyList(); } @@ -38,7 +34,8 @@ public List getList() { * {@inheritDoc} */ @Override - public void loadCount() {} + public void loadCount() { + } /** * {@inheritDoc} diff --git a/app/exporters/AbstractExporter.java b/app/exporters/AbstractExporter.java index 957c284f..d11ba972 100644 --- a/app/exporters/AbstractExporter.java +++ b/app/exporters/AbstractExporter.java @@ -1,24 +1,19 @@ package exporters; import models.Locale; -import play.mvc.Http.Response; +import play.mvc.Result; /** - * * @author resamsel * @version 7 Oct 2016 */ -public abstract class AbstractExporter implements Exporter -{ - @Override - public Exporter addHeaders(Response response, Locale locale) - { - response.setHeader("Cache-Control", "public"); - response.setHeader("Content-Description", "File Transfer"); - response.setHeader("Content-Disposition", String.format("attachment; filename=%s", getFilename(locale))); - response.setHeader("Content-Type", "mime/type"); - response.setHeader("Content-Transfer-Encoding", "binary"); - - return this; - } +public abstract class AbstractExporter implements Exporter { + @Override + public Result addHeaders(Result result, Locale locale) { + return result.withHeader("Cache-Control", "public") + .withHeader("Content-Description", "File Transfer") + .withHeader("Content-Disposition", String.format("attachment; filename=%s", getFilename(locale))) + .withHeader("Content-Type", "mime/type") + .withHeader("Content-Transfer-Encoding", "binary"); + } } diff --git a/app/exporters/Exporter.java b/app/exporters/Exporter.java index 68a6a74c..c1743ba2 100644 --- a/app/exporters/Exporter.java +++ b/app/exporters/Exporter.java @@ -1,12 +1,12 @@ package exporters; import models.Locale; -import play.mvc.Http.Response; +import play.mvc.Result; public interface Exporter { byte[] apply(Locale locale); - Exporter addHeaders(Response response, Locale locale); - + Result addHeaders(Result result, Locale locale); + String getFilename(Locale locale); } diff --git a/app/forms/UserForm.java b/app/forms/UserForm.java deleted file mode 100644 index 6d1fd228..00000000 --- a/app/forms/UserForm.java +++ /dev/null @@ -1,115 +0,0 @@ -package forms; - -import models.User; -import play.api.Play; -import play.data.validation.Constraints; -import play.data.validation.ValidationError; -import play.mvc.Http.Context; -import services.UserService; -import validators.Username; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -/** - * - * @author resamsel - * @version 2 Sep 2016 - */ -public class UserForm { - private UUID id; - - @Constraints.Required - @Constraints.MaxLength(User.NAME_LENGTH) - private String name; - - @Constraints.Required - @Constraints.MaxLength(User.USERNAME_LENGTH) - @Constraints.Pattern("[a-zA-Z0-9_\\.-]*") - @Username - private String username; - - @Constraints.Required - @Constraints.MaxLength(User.EMAIL_LENGTH) - private String email; - - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - /** - * - */ - public List validate() { - List errors = new ArrayList(); - - User user = Play.current().injector().instanceOf(UserService.class).byUsername(username); - if (user != null && !user.id.equals(id)) - errors.add(new ValidationError("username", - Context.current().messages().at("user.username.duplicate"))); - - return errors.isEmpty() ? null : errors; - } - - /** - * @param in - * @return - */ - public User into(User in) { - in.name = name; - in.username = username; - in.email = email; - - return in; - } - - /** - * @param key - * @return - */ - public static UserForm from(User in) { - UserForm out = new UserForm(); - - out.id = in.id; - out.name = in.name; - out.username = in.username; - out.email = in.email; - - return out; - } -} diff --git a/app/mappers/AccessTokenMapper.java b/app/mappers/AccessTokenMapper.java index f6ec8dff..f40bb96d 100644 --- a/app/mappers/AccessTokenMapper.java +++ b/app/mappers/AccessTokenMapper.java @@ -2,6 +2,7 @@ import dto.AccessToken; import models.User; +import play.mvc.Http; public class AccessTokenMapper { public static models.AccessToken toModel(dto.AccessToken in) { diff --git a/app/mappers/AggregatedNotificationMapper.java b/app/mappers/AggregatedNotificationMapper.java index 4a317898..17146e12 100644 --- a/app/mappers/AggregatedNotificationMapper.java +++ b/app/mappers/AggregatedNotificationMapper.java @@ -7,30 +7,46 @@ import io.getstream.client.model.activities.SimpleActivity; import models.LogEntry; import org.joda.time.DateTime; -import play.api.Play; import play.i18n.Messages; +import play.i18n.MessagesApi; import play.mvc.Http; import services.LogEntryService; import utils.FormatUtils; +import javax.inject.Inject; +import javax.inject.Singleton; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.UUID; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; +@Singleton public class AggregatedNotificationMapper { - public static AggregatedNotification toDto(AggregatedActivity in, - Map logEntryMap) { - Messages messages = Http.Context.current().messages(); + private final LogEntryService logEntryService; + private final NotificationMapper notificationMapper; + private final MessagesApi messagesApi; + + @Inject + public AggregatedNotificationMapper(LogEntryService logEntryService, NotificationMapper notificationMapper, MessagesApi messagesApi) { + this.logEntryService = logEntryService; + this.notificationMapper = notificationMapper; + this.messagesApi = messagesApi; + } + + public AggregatedNotification toDto(AggregatedActivity in, + Map logEntryMap, Http.Request request) { + Messages messages = messagesApi.preferred(request); + Locale locale = messages.lang().locale(); AggregatedNotification out = new AggregatedNotification(); out.whenCreated = new DateTime(in.getCreatedAt()); - out.created = FormatUtils.pretty(Http.Context.current().lang().locale(), out.whenCreated); + out.created = FormatUtils.pretty(locale, out.whenCreated); out.whenUpdated = new DateTime(in.getUpdatedAt()); - out.updated = FormatUtils.pretty(Http.Context.current().lang().locale(), out.whenUpdated); + out.updated = FormatUtils.pretty(locale, out.whenUpdated); out.verb = in.getVerb(); out.activityCount = in.getActivityCount(); out.actorCount = in.getActorCount(); @@ -40,11 +56,11 @@ public static AggregatedNotification toDto(AggregatedActivity in if (logEntryMap != null) { UUID logEntryId = Notification.extractUuid(firstActivity.getForeignId()); if (logEntryMap.containsKey(logEntryId)) { - activity = NotificationMapper.toDto(firstActivity, logEntryMap.get(logEntryId)); + activity = notificationMapper.toDto(firstActivity, logEntryMap.get(logEntryId), request); } } if (activity == null) { - activity = NotificationMapper.toDto(firstActivity); + activity = notificationMapper.toDto(firstActivity, request); } out.title = activity.title; @@ -57,18 +73,18 @@ public static AggregatedNotification toDto(AggregatedActivity in out.project = activity.project; } out.subtitle = messages.at("activity." + out.verb + ".subtitle", out.activityCount, - out.actorCount, out.updated); + out.actorCount, out.updated); return out; } - public static List toDto(List> in) { + public List toDto(List> in, Http.Request request) { List ids = in.stream().flatMap(activity -> activity.getActivities().stream()) - .map(activity -> Notification.extractUuid(activity.getForeignId())).collect(toList()); - Map map = Play.current().injector().instanceOf(LogEntryService.class) - .findBy(new LogEntryCriteria().withIds(ids)).getList() - .stream().collect(toMap(LogEntry::getId, a -> a)); + .map(activity -> Notification.extractUuid(activity.getForeignId())).collect(toList()); + Map map = logEntryService + .findBy(new LogEntryCriteria().withIds(ids)).getList() + .stream().collect(toMap(LogEntry::getId, a -> a)); - return in.stream().map(a -> toDto(a, map)).collect(toList()); + return in.stream().map(a -> toDto(a, map, request)).collect(toList()); } } diff --git a/app/mappers/KeyMapper.java b/app/mappers/KeyMapper.java index e90dc9b2..ed39db81 100644 --- a/app/mappers/KeyMapper.java +++ b/app/mappers/KeyMapper.java @@ -4,10 +4,22 @@ import dto.Message; import models.Project; import models.User; +import play.mvc.Http; + +import javax.inject.Inject; +import javax.inject.Singleton; import static java.util.stream.Collectors.toMap; +@Singleton public class KeyMapper { + private final MessageMapper messageMapper; + + @Inject + public KeyMapper(MessageMapper messageMapper) { + this.messageMapper = messageMapper; + } + public static models.Key toModel(Key in) { return toModel(in, ProjectMapper.toModel(in)); } @@ -47,7 +59,7 @@ public static models.Key toModel(Message in) { return out; } - public static Key toDto(models.Key in) { + public Key toDto(models.Key in, Http.Request request) { Key out = new Key(); out.id = in.id; @@ -63,7 +75,7 @@ public static Key toDto(models.Key in) { if (in.messages != null && !in.messages.isEmpty()) { out.messages = in.messages.stream() - .map(MessageMapper::toDto) + .map(message -> messageMapper.toDto(message, request)) .filter(m -> m.localeName != null) .collect(toMap(m -> m.localeName, m -> m)); } diff --git a/app/mappers/LocaleMapper.java b/app/mappers/LocaleMapper.java index 7f7a9b13..7efbc2c7 100644 --- a/app/mappers/LocaleMapper.java +++ b/app/mappers/LocaleMapper.java @@ -6,12 +6,26 @@ import dto.Message; import models.Project; import models.User; +import play.mvc.Http; import services.MessageService; import utils.FormatUtils; +import javax.inject.Inject; +import javax.inject.Singleton; + import static java.util.stream.Collectors.toMap; +@Singleton public class LocaleMapper { + private final FormatUtils formatUtils; + private final MessageMapper messageMapper; + + @Inject + public LocaleMapper(FormatUtils formatUtils, MessageMapper messageMapper) { + this.formatUtils = formatUtils; + this.messageMapper = messageMapper; + } + public static models.Locale toModel(Locale in) { return toModel(in, ProjectMapper.toModel(in)); } @@ -51,7 +65,7 @@ public static models.Locale toModel(Message in) { return out; } - public static Locale toDto(models.Locale in) { + public Locale toDto(models.Locale in, Http.Request request) { Locale out = new Locale(); out.id = in.id; @@ -66,7 +80,7 @@ public static Locale toDto(models.Locale in) { out.name = in.name; out.pathName = in.getPathName(); - out.displayName = FormatUtils.formatDisplayName(in); + out.displayName = formatUtils.formatDisplayName(in, request); if (Strings.isNullOrEmpty(out.displayName)) { out.displayName = in.name; } @@ -74,20 +88,22 @@ public static Locale toDto(models.Locale in) { if (in.messages != null && !in.messages.isEmpty()) { out.messages = - in.messages.stream().map(MessageMapper::toDto).collect(toMap(m -> m.keyName, m -> m)); + in.messages.stream() + .map(message -> messageMapper.toDto(message, request)) + .collect(toMap(m -> m.keyName, m -> m)); } return out; } - public static Locale loadInto(models.Locale in, MessageService messageService) { - Locale out = toDto(in); + public Locale loadInto(models.Locale in, MessageService messageService, Http.Request request) { + Locale out = toDto(in, request); if (out.messages == null) { out.messages = messageService.findBy(new MessageCriteria().withLocaleId(in.id)) .getList() .stream() - .map(MessageMapper::toDto) + .map(message -> messageMapper.toDto(message, request)) .collect(toMap(m -> m.keyName, m -> m)); } diff --git a/app/mappers/MessageMapper.java b/app/mappers/MessageMapper.java index 5ef3da56..36d8cfc6 100644 --- a/app/mappers/MessageMapper.java +++ b/app/mappers/MessageMapper.java @@ -3,9 +3,21 @@ import dto.Message; import models.Key; import models.Locale; +import play.mvc.Http; import utils.FormatUtils; +import javax.inject.Inject; +import javax.inject.Singleton; + +@Singleton public class MessageMapper { + private final FormatUtils formatUtils; + + @Inject + public MessageMapper(FormatUtils formatUtils) { + this.formatUtils = formatUtils; + } + public static models.Message toModel(Message in) { return toModel(in, LocaleMapper.toModel(in), KeyMapper.toModel(in)); } @@ -23,7 +35,7 @@ public static models.Message toModel(Message in, Locale locale, Key key) { return out; } - public static Message toDto(models.Message in) { + public Message toDto(models.Message in, Http.Request request) { Message out = new Message(); out.id = in.id; @@ -35,7 +47,7 @@ public static Message toDto(models.Message in) { if (in.locale != null) { out.localeId = in.locale.id; out.localeName = in.locale.name; - out.localeDisplayName = FormatUtils.formatDisplayName(in.locale); + out.localeDisplayName = formatUtils.formatDisplayName(in.locale, request); out.localePathName = in.locale.getPathName(); } diff --git a/app/mappers/NotificationMapper.java b/app/mappers/NotificationMapper.java index 776760a2..041ff425 100644 --- a/app/mappers/NotificationMapper.java +++ b/app/mappers/NotificationMapper.java @@ -3,27 +3,35 @@ import dto.Notification; import io.getstream.client.model.activities.SimpleActivity; import models.LogEntry; -import play.api.Play; -import play.api.inject.Injector; +import play.mvc.Http; import services.LogEntryService; import services.UserService; import utils.ActivityUtils; +import javax.inject.Inject; +import javax.inject.Singleton; import java.util.Date; +@Singleton public class NotificationMapper { - /** - * - */ - public static Notification toDto(SimpleActivity in) { - return toDto(in, null); + private final UserService userService; + private final LogEntryService logEntryService; + private final ActivityUtils activityUtils; + private final ProjectMapper projectMapper; + + @Inject + public NotificationMapper(UserService userService, LogEntryService logEntryService, ActivityUtils activityUtils, ProjectMapper projectMapper) { + this.userService = userService; + this.logEntryService = logEntryService; + this.activityUtils = activityUtils; + this.projectMapper = projectMapper; } - public static Notification toDto(SimpleActivity in, LogEntry activity) { - Injector injector = Play.current().injector(); - UserService userService = injector.instanceOf(UserService.class); - LogEntryService logEntryService = injector.instanceOf(LogEntryService.class); + public Notification toDto(SimpleActivity in, Http.Request request) { + return toDto(in, null, request); + } + public Notification toDto(SimpleActivity in, LogEntry activity, Http.Request request) { Notification out = new Notification(); out.id = in.getId(); @@ -35,12 +43,12 @@ public static Notification toDto(SimpleActivity in, LogEntry activity) { if (activity != null) { out.activityId = activity.id; out.contentType = activity.getSimpleContentType(); - out.title = ActivityUtils.titleOf(activity); + out.title = activityUtils.titleOf(activity, request); out.name = ActivityUtils.nameOf(activity); out.icon = ActivityUtils.iconOf(activity); out.color = ActivityUtils.colorOf(activity); if (activity.project != null) - out.project = ProjectMapper.toDto(activity.project); + out.project = projectMapper.toDto(activity.project, request); } return out; diff --git a/app/mappers/ProjectMapper.java b/app/mappers/ProjectMapper.java index 7f703e01..69760a62 100644 --- a/app/mappers/ProjectMapper.java +++ b/app/mappers/ProjectMapper.java @@ -7,14 +7,30 @@ import dto.Locale; import dto.Project; import models.User; +import play.mvc.Http; import services.KeyService; import services.LocaleService; import services.MessageService; import utils.EmailUtils; +import javax.inject.Inject; +import javax.inject.Singleton; + import static java.util.stream.Collectors.toList; +@Singleton public class ProjectMapper { + private final LocaleMapper localeMapper; + private final KeyMapper keyMapper; + private final MessageMapper messageMapper; + + @Inject + public ProjectMapper(LocaleMapper localeMapper, KeyMapper keyMapper, MessageMapper messageMapper) { + this.localeMapper = localeMapper; + this.keyMapper = keyMapper; + this.messageMapper = messageMapper; + } + public static models.Project toModel(Project in) { models.Project out = new models.Project(); @@ -25,9 +41,9 @@ public static models.Project toModel(Project in) { out.description = in.description; if (in.ownerId != null) { out.owner = new User() - .withId(in.ownerId) - .withUsername(in.ownerUsername) - .withName(in.ownerName); + .withId(in.ownerId) + .withUsername(in.ownerUsername) + .withName(in.ownerName); } return out; @@ -63,7 +79,7 @@ public static models.Project toModel(Key in) { return out; } - public static Project toDto(models.Project in) { + public Project toDto(models.Project in, Http.Request request) { Project out = new Project(); out.id = in.id; @@ -83,11 +99,15 @@ public static Project toDto(models.Project in) { } if (in.keys != null && !in.keys.isEmpty()) { - out.keys = in.keys.stream().map(KeyMapper::toDto).collect(toList()); + out.keys = in.keys.stream() + .map(key -> keyMapper.toDto(key, request)) + .collect(toList()); } if (in.locales != null && !in.locales.isEmpty()) { - out.locales = in.locales.stream().map(LocaleMapper::toDto).collect(toList()); + out.locales = in.locales.stream() + .map(locale -> localeMapper.toDto(locale, request)) + .collect(toList()); } if (in.members != null && !in.members.isEmpty()) { @@ -97,24 +117,24 @@ public static Project toDto(models.Project in) { return out; } - public static Project loadInto(models.Project in, LocaleService localeService, KeyService keyService, MessageService messageService) { - Project out = toDto(in); + public Project loadInto(models.Project in, LocaleService localeService, KeyService keyService, MessageService messageService, Http.Request request) { + Project out = toDto(in, request); out.keys = keyService.findBy(new KeyCriteria().withProjectId(in.id)) - .getList() - .stream() - .map(KeyMapper::toDto) - .collect(toList()); + .getList() + .stream() + .map(key -> keyMapper.toDto(key, request)) + .collect(toList()); out.locales = localeService.findBy(new LocaleCriteria().withProjectId(in.id)) - .getList() - .stream() - .map(LocaleMapper::toDto) - .collect(toList()); + .getList() + .stream() + .map(locale -> localeMapper.toDto(locale, request)) + .collect(toList()); out.messages = messageService.findBy(new MessageCriteria().withProjectId(in.id)) - .getList() - .stream() - .map(MessageMapper::toDto) - .collect(toList()); + .getList() + .stream() + .map(message -> messageMapper.toDto(message, request)) + .collect(toList()); return out; } diff --git a/app/models/Key.java b/app/models/Key.java index a74e85c9..72b776a1 100644 --- a/app/models/Key.java +++ b/app/models/Key.java @@ -6,7 +6,6 @@ import org.apache.commons.lang3.ObjectUtils; import org.joda.time.DateTime; import play.libs.Json; -import play.mvc.Http.Context; import utils.CacheUtils; import utils.UrlUtils; import validators.KeyNameUniqueChecker; @@ -28,7 +27,7 @@ @Entity @Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"project_id", "name"})}) @NameUnique(checker = KeyNameUniqueChecker.class) -public class Key implements Model, Suggestable { +public class Key implements Model { public static final int NAME_LENGTH = 255; @@ -75,22 +74,6 @@ public UUID getId() { return id; } - /** - * {@inheritDoc} - */ - @Override - public String value() { - return Context.current().messages().at("key.autocomplete", name); - } - - /** - * {@inheritDoc} - */ - @Override - public Data data() { - return Data.from(Key.class, id, name, null); - } - /** * {@inheritDoc} */ diff --git a/app/models/Locale.java b/app/models/Locale.java index a9344c0f..c4604d88 100644 --- a/app/models/Locale.java +++ b/app/models/Locale.java @@ -1,15 +1,11 @@ package models; +import com.fasterxml.jackson.annotation.JsonIgnore; import io.ebean.annotation.CreatedTimestamp; import io.ebean.annotation.UpdatedTimestamp; -import com.fasterxml.jackson.annotation.JsonIgnore; -import controllers.AbstractController; -import controllers.routes; import org.apache.commons.lang3.ObjectUtils; import org.joda.time.DateTime; -import play.api.mvc.Call; import play.libs.Json; -import play.mvc.Http.Context; import utils.CacheUtils; import utils.UrlUtils; import validators.LocaleNameUniqueChecker; @@ -26,15 +22,12 @@ import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import java.util.List; -import java.util.Objects; import java.util.UUID; -import static utils.FormatUtils.formatLocale; - @Entity @Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"project_id", "name"})}) @NameUnique(checker = LocaleNameUniqueChecker.class) -public class Locale implements Model, Suggestable { +public class Locale implements Model { public static final int NAME_LENGTH = 15; @@ -81,18 +74,6 @@ public UUID getId() { return id; } - @Override - public String value() { - Context ctx = Context.current(); - return ctx.messages().at("locale.autocomplete", formatLocale(ctx.lang().locale(), this)); - } - - @Override - public Data data() { - return Data.from(Locale.class, id, formatLocale(Context.current().lang().locale(), this), - null); - } - @Override public Locale updateFrom(Locale in) { project = project.updateFrom(in.project); diff --git a/app/models/Project.java b/app/models/Project.java index bd8ff0a9..4202e87b 100644 --- a/app/models/Project.java +++ b/app/models/Project.java @@ -1,18 +1,15 @@ package models; import com.fasterxml.jackson.annotation.JsonIgnore; -import criterias.MessageCriteria; import io.ebean.annotation.CreatedTimestamp; import io.ebean.annotation.UpdatedTimestamp; import org.apache.commons.lang3.ObjectUtils; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import play.api.Play; import play.data.validation.Constraints; import play.data.validation.Constraints.Required; import play.libs.Json; -import services.MessageService; import utils.CacheUtils; import validators.NameUnique; import validators.ProjectName; @@ -42,7 +39,7 @@ @Entity @Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"owner_id", "name"})}) @NameUnique(checker = ProjectNameUniqueChecker.class, message = "error.projectnameunique") -public class Project implements Model, Suggestable { +public class Project implements Model { private static final Logger LOGGER = LoggerFactory.getLogger(Project.class); @@ -124,67 +121,11 @@ public UUID getId() { return id; } - @Override - public String value() { - return name; - } - - @Override - public Data data() { - return Data.from(Project.class, id, name, null); - } - public Project withId(UUID id) { this.id = id; return this; } - public float progress() { - long keysSize = keysSize(); - long localesSize = localesSize(); - if (keysSize < 1 || localesSize < 1) { - return 0f; - } - return (float) messagesSize() / (float) (keysSize * localesSize); - } - - public long missingKeys(UUID localeId) { - return keysSize() - keysSizeMap(localeId); - } - - private long keysSizeMap(UUID localeId) { - if (keysSizeMap == null) - // FIXME: This is an expensive operation, consider doing this in a group by query. - { - keysSizeMap = messageList().stream().collect(groupingBy(m -> m.locale.id, counting())); - } - - return keysSizeMap.getOrDefault(localeId, 0L); - } - - public long missingLocales(UUID keyId) { - return localesSize() - localesSizeMap(keyId); - } - - private long localesSizeMap(UUID keyId) { - if (localesSizeMap == null) - // FIXME: This is an expensive operation, consider doing this in a group by query. - { - localesSizeMap = messageList().stream().collect(groupingBy(m -> m.key.id, counting())); - } - - return localesSizeMap.getOrDefault(keyId, 0L); - } - - private List messageList() { - if (messages == null) { - messages = Play.current().injector().instanceOf(MessageService.class) - .findBy(new MessageCriteria().withProjectId(this.id)).getList(); - } - - return messages; - } - public long membersSize() { return members.size(); } @@ -197,10 +138,6 @@ public long keysSize() { return keys.size(); } - public long messagesSize() { - return Play.current().injector().instanceOf(MessageService.class).countBy(this); - } - public Project withName(String name) { this.name = name; return this; diff --git a/app/modules/StreamModule.java b/app/modules/StreamModule.java index 7424c2e4..e010b43b 100644 --- a/app/modules/StreamModule.java +++ b/app/modules/StreamModule.java @@ -1,12 +1,8 @@ package modules; -import org.apache.commons.lang3.StringUtils; -import play.api.Configuration; -import play.api.Environment; -import play.api.inject.Binding; -import play.api.inject.Module; -import scala.Option; -import scala.collection.Seq; +import com.google.inject.AbstractModule; +import com.typesafe.config.Config; +import play.Environment; import services.NotificationService; import services.NotificationSync; import services.impl.NotificationServiceDummy; @@ -18,27 +14,21 @@ * @author resamsel * @version 19 May 2017 */ -public class StreamModule extends Module { - /** - * {@inheritDoc} - */ - @Override - public Seq> bindings(Environment environment, Configuration configuration) { - Option streamIoKey = - configuration.getString(ConfigKey.StreamIOKey.key(), Option.empty()); - Option streamIoSecret = - configuration.getString(ConfigKey.StreamIOSecret.key(), Option.empty()); - - if (!streamIoKey.isDefined() || !streamIoSecret.isDefined()) - return seq(bind(NotificationService.class).to(NotificationServiceDummy.class)); +public class StreamModule extends AbstractModule { + private final Config config; - String streamIoKeyValue = streamIoKey.get(); - String streamIoSecretValue = streamIoSecret.get(); + public StreamModule(final Environment environment, final Config config) { + this.config = config; + } - if (StringUtils.isEmpty(streamIoKeyValue) || StringUtils.isEmpty(streamIoSecretValue)) - return seq(bind(NotificationService.class).to(NotificationServiceDummy.class)); + @Override + protected void configure() { + if (!ConfigKey.StreamIOKey.existsIn(config) || !ConfigKey.StreamIOSecret.existsIn(config)) { + bind(NotificationService.class).to(NotificationServiceDummy.class); + return; + } - return seq(bind(NotificationService.class).to(NotificationServiceImpl.class), - bind(NotificationSync.class).to(NotificationSyncImpl.class)); + bind(NotificationService.class).to(NotificationServiceImpl.class); + bind(NotificationSync.class).to(NotificationSyncImpl.class); } } diff --git a/app/repositories/ProjectUserRepository.java b/app/repositories/ProjectUserRepository.java index 976bf00a..8e552323 100644 --- a/app/repositories/ProjectUserRepository.java +++ b/app/repositories/ProjectUserRepository.java @@ -18,7 +18,7 @@ public interface ProjectUserRepository extends ModelRepository { - List PROPERTIES_TO_FETCH = Arrays.asList(FETCH_PROJECT, FETCH_USER); + String[] PROPERTIES_TO_FETCH = new String[] {FETCH_PROJECT, FETCH_USER}; Map> FETCH_MAP = ImmutableMap.of( diff --git a/app/repositories/impl/AbstractModelRepository.java b/app/repositories/impl/AbstractModelRepository.java index 4bfe1ca8..2132315e 100644 --- a/app/repositories/impl/AbstractModelRepository.java +++ b/app/repositories/impl/AbstractModelRepository.java @@ -1,25 +1,28 @@ package repositories.impl; import actors.ActivityActorRef; -import io.ebean.Query; import criterias.AbstractSearchCriteria; import criterias.ContextCriteria; import criterias.GetCriteria; +import io.ebean.Query; import models.Model; -import org.apache.commons.lang3.NotImplementedException; import org.postgresql.util.PSQLException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import repositories.ModelRepository; import repositories.Persistence; import services.AuthProvider; +import utils.QueryUtils; import javax.persistence.PersistenceException; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.ValidationException; import javax.validation.Validator; +import java.util.Arrays; import java.util.Collection; +import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -28,7 +31,7 @@ * @version 9 Sep 2016 */ public abstract class AbstractModelRepository, ID, CRITERIA extends AbstractSearchCriteria> - implements ModelRepository { + implements ModelRepository { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractModelRepository.class); @@ -48,18 +51,41 @@ public abstract class AbstractModelRepository, ID public MODEL byId(GetCriteria criteria) { return fetch( - createQuery(criteria) - .setId(criteria.getId()) - .findOne(), - criteria + createQuery(criteria) + .setId(criteria.getId()) + .findOne(), + criteria ); } + protected abstract Query createQuery(ContextCriteria criteria); + + /** + * Creates the query given on the info of this fetch criteria. + */ + protected Query createQuery(Class clazz, String[] defaultFetches, Map> fetchMap, String... fetches) { + return createQuery(clazz, defaultFetches, fetchMap, Arrays.asList(fetches)); + } + /** * Creates the query given on the info of this fetch criteria. */ - protected Query createQuery(ContextCriteria criteria) { - throw new NotImplementedException("fetchQuery(FetchCriteria)"); + protected Query createQuery(Class clazz, String[] defaultFetches, List fetches) { + return QueryUtils.fetch( + persistence.find(clazz).setDisableLazyLoading(true), + QueryUtils.mergeFetches(defaultFetches, fetches) + ); + } + + /** + * Creates the query given on the info of this fetch criteria. + */ + protected Query createQuery(Class clazz, String[] defaultFetches, Map> fetchMap, List fetches) { + return QueryUtils.fetch( + persistence.find(clazz).setDisableLazyLoading(true), + QueryUtils.mergeFetches(defaultFetches, fetches), + fetchMap + ); } /** @@ -80,7 +106,7 @@ public MODEL create(MODEL model) { return save(model); } catch (PersistenceException e) { if (e.getCause() != null && e.getCause() instanceof PSQLException - && "23505".equals(((PSQLException) e.getCause()).getSQLState())) { + && "23505".equals(((PSQLException) e.getCause()).getSQLState())) { throw new ValidationException("Entry already exists (duplicate key)"); } @@ -111,8 +137,8 @@ protected MODEL validate(MODEL model) { if (!violations.isEmpty()) { throw new ConstraintViolationException( - "Constraint violations detected: " + violations.stream().map(Object::toString).collect( - Collectors.joining(",")), violations); + "Constraint violations detected: " + violations.stream().map(Object::toString).collect( + Collectors.joining(",")), violations); } return model; diff --git a/app/repositories/impl/AccessTokenRepositoryImpl.java b/app/repositories/impl/AccessTokenRepositoryImpl.java index 20aba0df..134ab518 100644 --- a/app/repositories/impl/AccessTokenRepositoryImpl.java +++ b/app/repositories/impl/AccessTokenRepositoryImpl.java @@ -3,6 +3,7 @@ import actors.ActivityActorRef; import actors.ActivityProtocol.Activity; import criterias.AccessTokenCriteria; +import criterias.ContextCriteria; import criterias.PagedListFactory; import io.ebean.ExpressionList; import io.ebean.PagedList; @@ -16,7 +17,6 @@ import repositories.AccessTokenRepository; import repositories.Persistence; import services.AuthProvider; -import utils.QueryUtils; import javax.inject.Inject; import javax.inject.Singleton; @@ -80,8 +80,12 @@ private Query fetch(List fetches) { } private Query fetch(String... fetches) { - return QueryUtils.fetch(persistence.find(AccessToken.class).setDisableLazyLoading(true), - QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, fetches), FETCH_MAP); + return createQuery(AccessToken.class, PROPERTIES_TO_FETCH, FETCH_MAP, fetches); + } + + @Override + protected Query createQuery(ContextCriteria criteria) { + return createQuery(AccessToken.class, PROPERTIES_TO_FETCH, FETCH_MAP, criteria.getFetches()); } /** @@ -89,7 +93,7 @@ private Query fetch(String... fetches) { */ @Override protected void preSave(AccessToken t, boolean update) { - User loggedInUser = authProvider.loggedInUser(); + User loggedInUser = authProvider.loggedInUser(null) /* FIXME: will fail! */; if (t.user == null || t.user.id == null || (loggedInUser != null && t.user.id != loggedInUser.id && loggedInUser.role != UserRole.Admin)) { // only allow admins to create access tokens for other users @@ -106,7 +110,7 @@ protected void prePersist(AccessToken t, boolean update) { activityActor.tell( new Activity<>( ActionType.Update, - authProvider.loggedInUser(), + authProvider.loggedInUser(null) /* FIXME: will fail! */, null, dto.AccessToken.class, AccessTokenMapper.toDto(byId(t.id)), @@ -126,7 +130,7 @@ protected void postSave(AccessToken t, boolean update) { activityActor.tell( new Activity<>( ActionType.Create, - authProvider.loggedInUser(), + authProvider.loggedInUser(null) /* FIXME: will fail! */, null, dto.AccessToken.class, null, diff --git a/app/repositories/impl/KeyRepositoryImpl.java b/app/repositories/impl/KeyRepositoryImpl.java index 2fec7664..a578713b 100644 --- a/app/repositories/impl/KeyRepositoryImpl.java +++ b/app/repositories/impl/KeyRepositoryImpl.java @@ -3,14 +3,15 @@ import actors.ActivityActorRef; import actors.ActivityProtocol.Activities; import actors.ActivityProtocol.Activity; -import io.ebean.ExpressionList; -import io.ebean.PagedList; -import io.ebean.Query; -import io.ebean.RawSqlBuilder; import com.google.common.collect.ImmutableMap; +import criterias.ContextCriteria; import criterias.KeyCriteria; import criterias.PagedListFactory; import dto.PermissionException; +import io.ebean.ExpressionList; +import io.ebean.PagedList; +import io.ebean.Query; +import io.ebean.RawSqlBuilder; import mappers.KeyMapper; import models.ActionType; import models.Key; @@ -31,7 +32,9 @@ import javax.inject.Inject; import javax.inject.Singleton; import javax.validation.Validator; +import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; @@ -56,18 +59,22 @@ public class KeyRepositoryImpl extends AbstractModelRepository findBy(KeyCriteria criteria) { public Key byId(UUID id, String... fetches) { return QueryUtils.fetch(persistence.find(Key.class).setId(id).setDisableLazyLoading(true), QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, fetches), FETCH_MAP) - .findOneOrEmpty() - .orElse(null); + .findOne(); } @Override @@ -163,15 +169,20 @@ public Key byOwnerAndProjectAndName(String username, String projectName, String .findOne(); } - private Query fetch(List fetches) { - return fetch(fetches.toArray(new String[0])); + @Override + protected Query createQuery(ContextCriteria criteria) { + return fetch(criteria.getFetches()); } - private Query fetch(String... fetches) { + private Query fetch(List fetches) { return QueryUtils.fetch(persistence.find(Key.class).alias("k").setDisableLazyLoading(true), QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, fetches), FETCH_MAP); } + private Query fetch(String... fetches) { + return fetch(fetches != null ? Arrays.asList(fetches) : Collections.emptyList()); + } + private PagedList fetch(@Nonnull PagedList paged, @Nonnull KeyCriteria criteria) { if (criteria.hasFetch(FETCH_PROGRESS)) { Map progressMap = progress(criteria.getProjectId()); @@ -215,8 +226,8 @@ protected void prePersist(Key t, boolean update) { if (update) { activityActor.tell( new Activity<>( - ActionType.Update, authProvider.loggedInUser(), t.project, dto.Key.class, - KeyMapper.toDto(byId(t.id)), KeyMapper.toDto(t)), + ActionType.Update, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.project, dto.Key.class, + keyMapper.toDto(byId(t.id), null), keyMapper.toDto(t, null)), null ); } @@ -229,7 +240,7 @@ protected void prePersist(Key t, boolean update) { protected void postSave(Key t, boolean update) { if (!update) { activityActor.tell( - new Activity<>(ActionType.Create, authProvider.loggedInUser(), t.project, dto.Key.class, null, KeyMapper.toDto(t)), + new Activity<>(ActionType.Create, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.project, dto.Key.class, null, keyMapper.toDto(t, null)), null ); } @@ -241,13 +252,13 @@ protected void postSave(Key t, boolean update) { @Override protected void preDelete(Key t) { if (!permissionService - .hasPermissionAny(t.project.id, authProvider.loggedInUser(), ProjectRole.Owner, ProjectRole.Manager, + .hasPermissionAny(t.project.id, authProvider.loggedInUser(null) /* FIXME: will fail! */, ProjectRole.Owner, ProjectRole.Manager, ProjectRole.Developer)) { throw new PermissionException("User not allowed in project"); } activityActor.tell( - new Activity<>(ActionType.Delete, authProvider.loggedInUser(), t.project, dto.Key.class, KeyMapper.toDto(t), null), + new Activity<>(ActionType.Delete, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.project, dto.Key.class, keyMapper.toDto(t, null), null), null ); @@ -262,8 +273,8 @@ protected void preDelete(Collection t) { activityActor.tell( new Activities<>( t.stream() - .map(k -> new Activity<>(ActionType.Delete, authProvider.loggedInUser(), k.project, dto.Key.class, - KeyMapper.toDto(k), null)) + .map(k -> new Activity<>(ActionType.Delete, authProvider.loggedInUser(null) /* FIXME: will fail! */, k.project, dto.Key.class, + keyMapper.toDto(k, null), null)) .collect(Collectors.toList())), null ); diff --git a/app/repositories/impl/LinkedAccountRepositoryImpl.java b/app/repositories/impl/LinkedAccountRepositoryImpl.java index 08a44eaf..62571eb5 100644 --- a/app/repositories/impl/LinkedAccountRepositoryImpl.java +++ b/app/repositories/impl/LinkedAccountRepositoryImpl.java @@ -1,15 +1,16 @@ package repositories.impl; import actors.ActivityActorRef; +import criterias.ContextCriteria; import criterias.LinkedAccountCriteria; import criterias.PagedListFactory; import io.ebean.ExpressionList; import io.ebean.PagedList; +import io.ebean.Query; import models.LinkedAccount; import repositories.LinkedAccountRepository; import repositories.Persistence; import services.AuthProvider; -import utils.QueryUtils; import javax.inject.Inject; import javax.inject.Singleton; @@ -17,8 +18,8 @@ @Singleton public class LinkedAccountRepositoryImpl extends - AbstractModelRepository implements - LinkedAccountRepository { + AbstractModelRepository implements + LinkedAccountRepository { @Inject public LinkedAccountRepositoryImpl(Persistence persistence, @@ -28,10 +29,14 @@ public LinkedAccountRepositoryImpl(Persistence persistence, super(persistence, validator, authProvider, activityActor); } + @Override + protected Query createQuery(ContextCriteria criteria) { + return createQuery(LinkedAccount.class, PROPERTIES_TO_FETCH, criteria.getFetches()); + } + @Override public PagedList findBy(LinkedAccountCriteria criteria) { - ExpressionList query = QueryUtils.fetch(persistence.find(LinkedAccount.class), PROPERTIES_TO_FETCH) - .where(); + ExpressionList query = createQuery(criteria).where(); if (criteria.getUserId() != null) { query.eq("user.id", criteria.getUserId()); @@ -52,7 +57,6 @@ public PagedList findBy(LinkedAccountCriteria criteria) { public LinkedAccount byId(Long id, String... fetches) { return persistence.find(LinkedAccount.class) .setId(id) - .findOneOrEmpty() - .orElse(null); + .findOne(); } } diff --git a/app/repositories/impl/LocaleRepositoryImpl.java b/app/repositories/impl/LocaleRepositoryImpl.java index 89e45983..8f22a98e 100644 --- a/app/repositories/impl/LocaleRepositoryImpl.java +++ b/app/repositories/impl/LocaleRepositoryImpl.java @@ -4,6 +4,7 @@ import actors.ActivityProtocol.Activities; import actors.ActivityProtocol.Activity; import com.google.common.collect.ImmutableMap; +import criterias.ContextCriteria; import criterias.LocaleCriteria; import criterias.MessageCriteria; import criterias.PagedListFactory; @@ -33,6 +34,7 @@ import javax.inject.Inject; import javax.inject.Singleton; import javax.validation.Validator; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -61,18 +63,22 @@ public class LocaleRepositoryImpl extends private final MessageRepository messageRepository; private final PermissionService permissionService; + private final LocaleMapper localeMapper; @Inject - public LocaleRepositoryImpl(Persistence persistence, - Validator validator, - AuthProvider authProvider, - ActivityActorRef activityActor, - MessageRepository messageRepository, - PermissionService permissionService) { + public LocaleRepositoryImpl( + Persistence persistence, + Validator validator, + AuthProvider authProvider, + ActivityActorRef activityActor, + MessageRepository messageRepository, + PermissionService permissionService, + LocaleMapper localeMapper) { super(persistence, validator, authProvider, activityActor); this.messageRepository = messageRepository; this.permissionService = permissionService; + this.localeMapper = localeMapper; } @Override @@ -81,7 +87,7 @@ public PagedList findBy(LocaleCriteria criteria) { if (StringUtils.isEmpty(criteria.getMessagesKeyName()) && !criteria.getFetches().isEmpty()) { QueryUtils.fetch(q, QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, criteria.getFetches()), - FETCH_MAP); + FETCH_MAP); } ExpressionList query = q.where(); @@ -125,22 +131,31 @@ public PagedList findBy(LocaleCriteria criteria) { @Override public Locale byId(UUID id, String... fetches) { return QueryUtils.fetch(persistence.find(Locale.class).setId(id).setDisableLazyLoading(true), - QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, fetches), FETCH_MAP).findOne(); + QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, fetches), FETCH_MAP).findOne(); + } + + @Override + protected Query createQuery(ContextCriteria criteria) { + return fetch(criteria.getFetches()); } private Query fetch(String... fetches) { + return fetch(fetches != null ? Arrays.asList(fetches) : Collections.emptyList()); + } + + private Query fetch(List fetches) { return QueryUtils.fetch(persistence.find(Locale.class).alias("l").setDisableLazyLoading(true), - QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, fetches), FETCH_MAP); + QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, fetches), FETCH_MAP); } private PagedList fetch(@Nonnull PagedList paged, @Nonnull LocaleCriteria criteria) { if (StringUtils.isNotEmpty(criteria.getMessagesKeyName()) - && criteria.hasFetch("messages")) { + && criteria.hasFetch("messages")) { // Retrieve messages that match the given keyName and locales retrieved Map messages = messageRepository - .findBy(new MessageCriteria().withKeyName(criteria.getMessagesKeyName()) - .withLocaleIds(paged.getList().stream().map(l -> l.id).collect(toList()))) - .getList().stream().collect(toMap(m -> m.locale.id, m -> m)); + .findBy(new MessageCriteria().withKeyName(criteria.getMessagesKeyName()) + .withLocaleIds(paged.getList().stream().map(l -> l.id).collect(toList()))) + .getList().stream().collect(toMap(m -> m.locale.id, m -> m)); for (Locale locale : paged.getList()) { if (messages.containsKey(locale.id)) { @@ -153,7 +168,7 @@ private PagedList fetch(@Nonnull PagedList paged, @Nonnull Local Map progressMap = progress(criteria.getProjectId()); paged.getList() - .forEach(l -> l.progress = progressMap.getOrDefault(l.id, 0.0)); + .forEach(l -> l.progress = progressMap.getOrDefault(l.id, 0.0)); } return paged; @@ -162,22 +177,22 @@ private PagedList fetch(@Nonnull PagedList paged, @Nonnull Local @Override public Map progress(UUID projectId) { List stats = log( - () -> persistence.createQuery(Stat.class) - .setRawSql(RawSqlBuilder - .parse("SELECT " + - PROGRESS_COLUMN_ID + ", " + PROGRESS_COLUMN_COUNT + - " FROM locale l" + - " LEFT OUTER JOIN message m ON m.locale_id = l.id" + - " LEFT OUTER JOIN key k ON k.project_id = l.project_id" + - " GROUP BY " + PROGRESS_COLUMN_ID) - .columnMapping(PROGRESS_COLUMN_ID, "id") - .columnMapping(PROGRESS_COLUMN_COUNT, "count") - .create()) - .where() - .eq("l.project_id", projectId) - .findList(), - LOGGER, - "Retrieving locale progress" + () -> persistence.createQuery(Stat.class) + .setRawSql(RawSqlBuilder + .parse("SELECT " + + PROGRESS_COLUMN_ID + ", " + PROGRESS_COLUMN_COUNT + + " FROM locale l" + + " LEFT OUTER JOIN message m ON m.locale_id = l.id" + + " LEFT OUTER JOIN key k ON k.project_id = l.project_id" + + " GROUP BY " + PROGRESS_COLUMN_ID) + .columnMapping(PROGRESS_COLUMN_ID, "id") + .columnMapping(PROGRESS_COLUMN_COUNT, "count") + .create()) + .where() + .eq("l.project_id", projectId) + .findList(), + LOGGER, + "Retrieving locale progress" ); return stats.stream().collect(Collectors.toMap(stat -> stat.id, stat -> stat.count)); @@ -186,8 +201,8 @@ public Map progress(UUID projectId) { @Override public List latest(Project project, int limit) { return log( - () -> fetch().where().eq("project", project).order("whenUpdated desc").setMaxRows(limit) - .findList(), LOGGER, "last(%d)", limit); + () -> fetch().where().eq("project", project).order("whenUpdated desc").setMaxRows(limit) + .findList(), LOGGER, "last(%d)", limit); } @Override @@ -207,13 +222,15 @@ public Locale byProjectAndName(UUID projectId, String name) { public Locale byOwnerAndProjectAndName(String username, String projectName, String localeName, String... fetches) { return fetch(fetches) - .where() - .eq("project.owner.username", username) - .eq("project.name", projectName) - .eq("name", localeName) - .findOne(); + .where() + .eq("project.owner.username", username) + .eq("project.name", projectName) + .eq("name", localeName) + .findOne(); } + // FIXME: pull pre/post persist logic to service!? + /** * {@inheritDoc} */ @@ -221,9 +238,9 @@ public Locale byOwnerAndProjectAndName(String username, String projectName, Stri protected void prePersist(Locale t, boolean update) { if (update) { activityActor.tell( - new Activity<>(ActionType.Update, authProvider.loggedInUser(), t.project, dto.Locale.class, - LocaleMapper.toDto(byId(t.id)), LocaleMapper.toDto(t)), - null + new Activity<>(ActionType.Update, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.project, dto.Locale.class, + localeMapper.toDto(byId(t.id), null), localeMapper.toDto(t, null)), + null ); } } @@ -235,8 +252,8 @@ protected void prePersist(Locale t, boolean update) { protected void postSave(Locale t, boolean update) { if (!update) { activityActor.tell( - new Activity<>(ActionType.Create, authProvider.loggedInUser(), t.project, dto.Locale.class, null, LocaleMapper.toDto(t)), - null + new Activity<>(ActionType.Create, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.project, dto.Locale.class, null, localeMapper.toDto(t, null)), + null ); } } @@ -247,14 +264,14 @@ protected void postSave(Locale t, boolean update) { @Override public void preDelete(Locale t) { if (!permissionService - .hasPermissionAny(t.project.id, authProvider.loggedInUser(), ProjectRole.Owner, ProjectRole.Manager, - ProjectRole.Translator)) { + .hasPermissionAny(t.project.id, authProvider.loggedInUser(null) /* FIXME: will fail! */, ProjectRole.Owner, ProjectRole.Manager, + ProjectRole.Translator)) { throw new PermissionException("User not allowed in project"); } activityActor.tell( - new Activity<>(ActionType.Delete, authProvider.loggedInUser(), t.project, dto.Locale.class, LocaleMapper.toDto(t), null), - null + new Activity<>(ActionType.Delete, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.project, dto.Locale.class, localeMapper.toDto(t, null), null), + null ); messageRepository.delete(messageRepository.byLocale(t.id)); @@ -266,12 +283,12 @@ public void preDelete(Locale t) { @Override public void preDelete(Collection t) { activityActor.tell( - new Activities<>(t.stream().map(l -> new Activity<>(ActionType.Delete, authProvider.loggedInUser(), l.project, - dto.Locale.class, LocaleMapper.toDto(l), null)).collect(Collectors.toList())), - null + new Activities<>(t.stream().map(l -> new Activity<>(ActionType.Delete, authProvider.loggedInUser(null) /* FIXME: will fail! */, l.project, + dto.Locale.class, localeMapper.toDto(l, null), null)).collect(Collectors.toList())), + null ); messageRepository.delete( - messageRepository.byLocales(t.stream().map(m -> m.id).collect(Collectors.toList()))); + messageRepository.byLocales(t.stream().map(m -> m.id).collect(Collectors.toList()))); } } diff --git a/app/repositories/impl/LogEntryRepositoryImpl.java b/app/repositories/impl/LogEntryRepositoryImpl.java index ba197339..a3f2949d 100644 --- a/app/repositories/impl/LogEntryRepositoryImpl.java +++ b/app/repositories/impl/LogEntryRepositoryImpl.java @@ -3,10 +3,12 @@ import actors.ActivityActorRef; import actors.NotificationActorRef; import actors.NotificationProtocol.PublishNotification; +import criterias.ContextCriteria; import criterias.LogEntryCriteria; import criterias.PagedListFactory; import io.ebean.ExpressionList; import io.ebean.PagedList; +import io.ebean.Query; import models.LogEntry; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; @@ -14,7 +16,6 @@ import repositories.LogEntryRepository; import repositories.Persistence; import services.AuthProvider; -import services.ContextProvider; import utils.QueryUtils; import javax.inject.Inject; @@ -29,19 +30,16 @@ public class LogEntryRepositoryImpl extends LogEntryRepository { private static final Logger LOGGER = LoggerFactory.getLogger(LogEntryRepositoryImpl.class); - private final ContextProvider contextProvider; private final NotificationActorRef notificationActor; @Inject public LogEntryRepositoryImpl(Persistence persistence, Validator validator, AuthProvider authProvider, - ContextProvider contextProvider, ActivityActorRef activityActor, NotificationActorRef notificationActor) { super(persistence, validator, authProvider, activityActor); - this.contextProvider = contextProvider; this.notificationActor = notificationActor; } @@ -106,13 +104,18 @@ private ExpressionList findQuery(LogEntryCriteria criteria) { return query; } + @Override + protected Query createQuery(ContextCriteria criteria) { + return createQuery(LogEntry.class, PROPERTIES_TO_FETCH, criteria.getFetches()); + } + /** * {@inheritDoc} */ @Override public void preSave(LogEntry t, boolean update) { if (t.user == null) { - t.user = authProvider.loggedInUser(); + t.user = authProvider.loggedInUser(null) /* FIXME: will fail! */; LOGGER.debug("preSave(): user of log entry is {}", t.user); } } diff --git a/app/repositories/impl/MessageRepositoryImpl.java b/app/repositories/impl/MessageRepositoryImpl.java index 75d35663..1aec1247 100644 --- a/app/repositories/impl/MessageRepositoryImpl.java +++ b/app/repositories/impl/MessageRepositoryImpl.java @@ -5,6 +5,7 @@ import actors.ActivityProtocol.Activity; import actors.MessageWordCountActorRef; import actors.WordCountProtocol.ChangeMessageWordCount; +import criterias.ContextCriteria; import criterias.MessageCriteria; import criterias.PagedListFactory; import io.ebean.ExpressionList; @@ -27,6 +28,7 @@ import javax.inject.Inject; import javax.inject.Singleton; import javax.validation.Validator; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -46,16 +48,20 @@ public class MessageRepositoryImpl extends private static final Logger LOGGER = LoggerFactory.getLogger(MessageRepositoryImpl.class); private final MessageWordCountActorRef messageWordCountActor; + private final MessageMapper messageMapper; @Inject - public MessageRepositoryImpl(Persistence persistence, + public MessageRepositoryImpl( + Persistence persistence, Validator validator, AuthProvider authProvider, ActivityActorRef activityActor, - MessageWordCountActorRef messageWordCountActor) { + MessageWordCountActorRef messageWordCountActor, + MessageMapper messageMapper) { super(persistence, validator, authProvider, activityActor); this.messageWordCountActor = messageWordCountActor; + this.messageMapper = messageMapper; } @Override @@ -106,11 +112,16 @@ public Map byIds(List ids) { .findMap(); } - private Query fetch(List fetches) { - return fetch(fetches.toArray(new String[0])); + @Override + protected Query createQuery(ContextCriteria criteria) { + return fetch(criteria.getFetches()); } private Query fetch(String... fetches) { + return fetch(fetches != null ? Arrays.asList(fetches) : Collections.emptyList()); + } + + private Query fetch(List fetches) { return QueryUtils.fetch(persistence.find(Message.class).alias("k").setDisableLazyLoading(true), QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, fetches), FETCH_MAP); } @@ -259,7 +270,7 @@ protected void postSave(Collection t) { @Override public void preDelete(Message t) { activityActor.tell( - new Activity<>(ActionType.Delete, authProvider.loggedInUser(), t.key.project, dto.Message.class, MessageMapper.toDto(t), + new Activity<>(ActionType.Delete, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.key.project, dto.Message.class, messageMapper.toDto(t, null), null), null ); @@ -271,8 +282,8 @@ public void preDelete(Message t) { @Override protected void preDelete(Collection t) { activityActor.tell( - new Activities<>(t.stream().map(m -> new Activity<>(ActionType.Delete, authProvider.loggedInUser(), m.key.project, - dto.Message.class, MessageMapper.toDto(m), null)).collect(toList())), + new Activities<>(t.stream().map(m -> new Activity<>(ActionType.Delete, authProvider.loggedInUser(null) /* FIXME: will fail! */, m.key.project, + dto.Message.class, messageMapper.toDto(m, null), null)).collect(toList())), null ); } @@ -307,22 +318,22 @@ protected void postDelete(Collection t) { private Activity logEntryCreate(Message message) { return new Activity<>( ActionType.Create, - authProvider.loggedInUser(), + authProvider.loggedInUser(null) /* FIXME: will fail! */, message.key.project, dto.Message.class, null, - MessageMapper.toDto(message) + messageMapper.toDto(message, null) ); } private Activity logEntryUpdate(Message message, Message previous) { return new Activity<>( ActionType.Update, - authProvider.loggedInUser(), + authProvider.loggedInUser(null) /* FIXME: will fail! */, message.key.project, dto.Message.class, - MessageMapper.toDto(previous), - MessageMapper.toDto(message) + messageMapper.toDto(previous, null), + messageMapper.toDto(message, null) ); } } diff --git a/app/repositories/impl/ProjectRepositoryImpl.java b/app/repositories/impl/ProjectRepositoryImpl.java index 00cd0f79..e1070a67 100644 --- a/app/repositories/impl/ProjectRepositoryImpl.java +++ b/app/repositories/impl/ProjectRepositoryImpl.java @@ -5,7 +5,7 @@ import actors.ActivityProtocol.Activity; import criterias.ContextCriteria; import criterias.DefaultContextCriteria; -import criterias.DefaultGetCriteria; +import criterias.GetCriteria; import criterias.PagedListFactory; import criterias.ProjectCriteria; import dto.NotFoundException; @@ -23,13 +23,13 @@ import models.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import play.mvc.Http; import repositories.KeyRepository; import repositories.LocaleRepository; import repositories.Persistence; import repositories.ProjectRepository; import services.AuthProvider; import services.PermissionService; -import utils.QueryUtils; import javax.inject.Inject; import javax.inject.Singleton; @@ -59,6 +59,7 @@ public class ProjectRepositoryImpl extends private final LocaleRepository localeRepository; private final KeyRepository keyRepository; private final PermissionService permissionService; + private final ProjectMapper projectMapper; @Inject public ProjectRepositoryImpl(Persistence persistence, @@ -67,12 +68,14 @@ public ProjectRepositoryImpl(Persistence persistence, ActivityActorRef activityActor, LocaleRepository localeRepository, KeyRepository keyRepository, - PermissionService permissionService) { + PermissionService permissionService, + ProjectMapper projectMapper) { super(persistence, validator, authProvider, activityActor); this.localeRepository = localeRepository; this.keyRepository = keyRepository; this.permissionService = permissionService; + this.projectMapper = projectMapper; } @Override @@ -188,13 +191,13 @@ public Project byId(UUID id, String... fetches) { return null; } - return byId(new DefaultGetCriteria<>(id).withFetches(fetches).withLoggedInUserId(authProvider.loggedInUserId())); + return byId(GetCriteria.from(id, null /* FIXME */, fetches).withLoggedInUserId(authProvider.loggedInUserId(null) /* FIXME: will fail! */)); } @Override public Project byOwnerAndName(String username, String name, String... fetches) { ContextCriteria criteria = new DefaultContextCriteria() - .withLoggedInUserId(authProvider.loggedInUserId()) + .withLoggedInUserId(authProvider.loggedInUserId(null) /* FIXME: will fail! */) .withFetches(fetches); return fetch( @@ -214,7 +217,7 @@ public Project byOwnerAndName(String username, String name, String... fetches) { protected void preSave(Project t, boolean update) { persistence.markAsDirty(t); if (t.owner == null || t.owner.id == null) { - t.owner = authProvider.loggedInUser(); + t.owner = authProvider.loggedInUser(null) /* FIXME: will fail! */; } if (t.members == null) { t.members = new ArrayList<>(); @@ -228,7 +231,7 @@ protected void preSave(Project t, boolean update) { protected void prePersist(Project t, boolean update) { if (update) { activityActor.tell( - new Activity<>(ActionType.Update, authProvider.loggedInUser(), t, dto.Project.class, toDto(byId(t.id)), toDto(t)), + new Activity<>(ActionType.Update, authProvider.loggedInUser(null) /* FIXME: will fail! */, t, dto.Project.class, toDto(byId(t.id), null), toDto(t, null)), null ); } @@ -245,7 +248,7 @@ protected void postSave(Project t, boolean update) { if (!update) { activityActor.tell( - new Activity<>(ActionType.Create, authProvider.loggedInUser(), t, dto.Project.class, null, toDto(t)), + new Activity<>(ActionType.Create, authProvider.loggedInUser(null) /* FIXME: will fail! */, t, dto.Project.class, null, toDto(t, null)), null ); } @@ -260,7 +263,7 @@ public void delete(Project t) { throw new NotFoundException(dto.Project.class.getSimpleName(), t != null ? t.id : null); } if (!permissionService - .hasPermissionAny(t.id, authProvider.loggedInUser(), ProjectRole.Owner, ProjectRole.Manager)) { + .hasPermissionAny(t.id, authProvider.loggedInUser(null) /* FIXME: will fail! */, ProjectRole.Owner, ProjectRole.Manager)) { throw new PermissionException("User not allowed in project"); } @@ -268,7 +271,7 @@ public void delete(Project t) { keyRepository.delete(t.keys); activityActor.tell( - new Activity<>(ActionType.Delete, authProvider.loggedInUser(), t, dto.Project.class, toDto(t), null), + new Activity<>(ActionType.Delete, authProvider.loggedInUser(null) /* FIXME: will fail! */, t, dto.Project.class, toDto(t, null), null), null ); @@ -280,7 +283,7 @@ public void delete(Project t) { */ @Override public void delete(Collection t) { - User loggedInUser = authProvider.loggedInUser(); + User loggedInUser = authProvider.loggedInUser(null) /* FIXME: will fail! */; for (Project p : t) { if (p == null || p.deleted) { throw new NotFoundException(dto.Project.class.getSimpleName(), p != null ? p.id : null); @@ -299,7 +302,7 @@ public void delete(Collection t) { activityActor.tell( new Activities<>(t.stream() - .map(p -> new Activity<>(ActionType.Delete, authProvider.loggedInUser(), p, dto.Project.class, toDto(p), null)) + .map(p -> new Activity<>(ActionType.Delete, authProvider.loggedInUser(null) /* FIXME: will fail! */, p, dto.Project.class, toDto(p, null), null)) .collect(toList())), null ); @@ -311,15 +314,11 @@ public void delete(Collection t) { @Override protected Query createQuery(ContextCriteria criteria) { - return QueryUtils.fetch( - persistence.find(Project.class).setDisableLazyLoading(true), - QueryUtils.mergeFetches(PROPERTIES_TO_FETCH, criteria.getFetches()), - FETCH_MAP - ); + return createQuery(Project.class, PROPERTIES_TO_FETCH, FETCH_MAP, criteria.getFetches()); } - private dto.Project toDto(Project t) { - dto.Project out = ProjectMapper.toDto(t); + private dto.Project toDto(Project t, Http.Request request) { + dto.Project out = projectMapper.toDto(t, request); out.keys = Collections.emptyList(); out.locales = Collections.emptyList(); diff --git a/app/repositories/impl/ProjectUserRepositoryImpl.java b/app/repositories/impl/ProjectUserRepositoryImpl.java index 2b1bf2a6..9393dbf3 100644 --- a/app/repositories/impl/ProjectUserRepositoryImpl.java +++ b/app/repositories/impl/ProjectUserRepositoryImpl.java @@ -4,10 +4,12 @@ import actors.ActivityProtocol.Activity; import actors.NotificationActorRef; import actors.NotificationProtocol.FollowNotification; +import criterias.ContextCriteria; import criterias.PagedListFactory; import criterias.ProjectUserCriteria; import io.ebean.ExpressionList; import io.ebean.PagedList; +import io.ebean.Query; import mappers.ProjectUserMapper; import models.ActionType; import models.ProjectUser; @@ -66,8 +68,7 @@ public int countBy(ProjectUserCriteria criteria) { } private ExpressionList findQuery(ProjectUserCriteria criteria) { - ExpressionList query = QueryUtils - .fetch(persistence.find(ProjectUser.class), PROPERTIES_TO_FETCH, FETCH_MAP).where(); + ExpressionList query = createQuery(criteria).where(); query.eq("project.deleted", false); @@ -95,6 +96,11 @@ private ExpressionList findQuery(ProjectUserCriteria criteria) { return query; } + @Override + protected Query createQuery(ContextCriteria criteria) { + return createQuery(ProjectUser.class, PROPERTIES_TO_FETCH, FETCH_MAP, criteria.getFetches()); + } + /** * {@inheritDoc} */ @@ -103,7 +109,7 @@ protected void prePersist(ProjectUser t, boolean update) { if (update) { activityActor.tell( new Activity<>( - ActionType.Update, authProvider.loggedInUser(), t.project, dto.ProjectUser.class, toDto(byId(t.id)), toDto(t) + ActionType.Update, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.project, dto.ProjectUser.class, toDto(byId(t.id)), toDto(t) ), null ); @@ -119,7 +125,7 @@ protected void postSave(ProjectUser t, boolean update) { persistence.refresh(t.user); activityActor.tell( new Activity<>( - ActionType.Create, authProvider.loggedInUser(), t.project, dto.ProjectUser.class, null, toDto(t) + ActionType.Create, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.project, dto.ProjectUser.class, null, toDto(t) ), null ); @@ -135,7 +141,7 @@ protected void postSave(ProjectUser t, boolean update) { public void preDelete(ProjectUser t) { activityActor.tell( new Activity<>( - ActionType.Delete, authProvider.loggedInUser(), t.project, dto.ProjectUser.class, toDto(t), null + ActionType.Delete, authProvider.loggedInUser(null) /* FIXME: will fail! */, t.project, dto.ProjectUser.class, toDto(t), null ), null ); diff --git a/app/repositories/impl/UserFeatureFlagRepositoryImpl.java b/app/repositories/impl/UserFeatureFlagRepositoryImpl.java index 4265f7bc..f90ef238 100644 --- a/app/repositories/impl/UserFeatureFlagRepositoryImpl.java +++ b/app/repositories/impl/UserFeatureFlagRepositoryImpl.java @@ -1,6 +1,7 @@ package repositories.impl; import actors.ActivityActorRef; +import criterias.ContextCriteria; import criterias.PagedListFactory; import criterias.UserFeatureFlagCriteria; import io.ebean.ExpressionList; @@ -14,11 +15,13 @@ import repositories.Persistence; import repositories.UserFeatureFlagRepository; import services.AuthProvider; -import utils.QueryUtils; import javax.inject.Inject; import javax.inject.Singleton; import javax.validation.Validator; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import java.util.UUID; @Singleton @@ -69,8 +72,17 @@ public UserFeatureFlag byUserIdAndFeature(UUID userId, Feature feature) { .findOne(); } - private Query fetch() { - return QueryUtils.fetch(persistence.find(UserFeatureFlag.class).setDisableLazyLoading(true), PROPERTIES_TO_FETCH); + @Override + protected Query createQuery(ContextCriteria criteria) { + return fetch(criteria.getFetches()); + } + + private Query fetch(String... fetches) { + return fetch(fetches != null ? Arrays.asList(fetches) : Collections.emptyList()); + } + + private Query fetch(List fetches) { + return createQuery(UserFeatureFlag.class, PROPERTIES_TO_FETCH, fetches); } /** @@ -78,7 +90,7 @@ private Query fetch() { */ @Override protected void preSave(UserFeatureFlag t, boolean update) { - User loggedInUser = authProvider.loggedInUser(); + User loggedInUser = authProvider.loggedInUser(null) /* FIXME: will fail! */; if (t.user == null || t.user.id == null || (loggedInUser != null && t.user.id != loggedInUser.id && loggedInUser.role != UserRole.Admin)) { // only allow admins to create access tokens for other users diff --git a/app/repositories/impl/UserRepositoryImpl.java b/app/repositories/impl/UserRepositoryImpl.java index 5a9a5693..14df0d65 100644 --- a/app/repositories/impl/UserRepositoryImpl.java +++ b/app/repositories/impl/UserRepositoryImpl.java @@ -2,6 +2,7 @@ import actors.ActivityActorRef; import actors.ActivityProtocol.Activity; +import criterias.ContextCriteria; import criterias.PagedListFactory; import criterias.UserCriteria; import dto.NotFoundException; @@ -72,8 +73,7 @@ public PagedList findBy(UserCriteria criteria) { @Override public User byId(UUID id, String... fetches) { return QueryUtils.fetch(persistence.find(User.class).setId(id), fetches, FETCH_MAP) - .findOneOrEmpty() - .orElse(null); + .findOne(); } @Override @@ -81,8 +81,7 @@ public User byUsername(String username, String... fetches) { return QueryUtils.fetch(persistence.find(User.class), fetches, FETCH_MAP) .where() .eq("username", username) - .findOneOrEmpty() - .orElse(null); + .findOne(); } @Override @@ -91,8 +90,7 @@ public User byLinkedAccount(String providerKey, String providerUserId) { .where() .eq("linkedAccounts.providerKey", providerKey) .eq("linkedAccounts.providerUserId", providerUserId) - .findOneOrEmpty() - .orElse(null); + .findOne(); } @Override @@ -100,8 +98,7 @@ public User byAccessToken(String accessTokenKey) { return persistence.find(User.class) .where() .eq("accessTokens.key", accessTokenKey) - .findOneOrEmpty() - .orElse(null); + .findOne(); } @Override @@ -155,6 +152,11 @@ public User updateSettings(UUID userId, Map settings) { return persistSettings(userId, settings, false); } + @Override + protected Query createQuery(ContextCriteria criteria) { + return createQuery(User.class, PROPERTIES_TO_FETCH, FETCH_MAP, criteria.getFetches()); + } + /** * Replaces or updates existing settings based on the given replace flag. */ @@ -201,7 +203,7 @@ protected void preSave(User t, boolean update) { protected void prePersist(User t, boolean update) { if (update) { activityActor.tell( - new Activity<>(ActionType.Update, authProvider.loggedInUser(), null, dto.User.class, toDto(byId(t.id)), toDto(t)), + new Activity<>(ActionType.Update, authProvider.loggedInUser(null) /* FIXME: will fail! */, null, dto.User.class, toDto(byId(t.id)), toDto(t)), null ); } diff --git a/app/services/AccessTokenService.java b/app/services/AccessTokenService.java index 05d025ea..a64b3833 100644 --- a/app/services/AccessTokenService.java +++ b/app/services/AccessTokenService.java @@ -3,6 +3,7 @@ import com.google.inject.ImplementedBy; import criterias.AccessTokenCriteria; import models.AccessToken; +import play.mvc.Http; import services.impl.AccessTokenServiceImpl; /** @@ -16,5 +17,5 @@ public interface AccessTokenService extends ModelService loggedInProfile(WebContext context); - void updateUser(CommonProfile profile); + void updateUser(CommonProfile profile, Http.Request request); } diff --git a/app/services/ContextProvider.java b/app/services/ContextProvider.java deleted file mode 100644 index dc269a2c..00000000 --- a/app/services/ContextProvider.java +++ /dev/null @@ -1,12 +0,0 @@ -package services; - -import com.google.inject.ImplementedBy; -import play.mvc.Http; -import services.impl.ContextProviderImpl; - -@ImplementedBy(ContextProviderImpl.class) -public interface ContextProvider { - Http.Context get(); - - Http.Context getOrNull(); -} diff --git a/app/services/KeyService.java b/app/services/KeyService.java index 0e57efbf..e82517f4 100644 --- a/app/services/KeyService.java +++ b/app/services/KeyService.java @@ -4,10 +4,9 @@ import criterias.KeyCriteria; import models.Key; import models.Project; +import play.mvc.Http; import services.impl.KeyServiceImpl; -import java.util.List; -import java.util.Map; import java.util.UUID; /** @@ -16,15 +15,11 @@ */ @ImplementedBy(KeyServiceImpl.class) public interface KeyService extends ModelService { - Map progress(UUID projectId); - - void increaseWordCountBy(UUID keyId, int wordCountDiff); + void increaseWordCountBy(UUID keyId, int wordCountDiff, Http.Request request); void resetWordCount(UUID projectId); - List latest(Project project, int limit); - - Key byProjectAndName(Project project, String keyName); + Key byProjectAndName(Project project, String keyName, Http.Request request); - Key byOwnerAndProjectAndName(String username, String projectName, String keyName, String... fetches); + Key byOwnerAndProjectAndName(String username, String projectName, String keyName, Http.Request request, String... fetches); } diff --git a/app/services/LocaleService.java b/app/services/LocaleService.java index beef3840..dd64d929 100644 --- a/app/services/LocaleService.java +++ b/app/services/LocaleService.java @@ -4,6 +4,7 @@ import criterias.LocaleCriteria; import models.Locale; import models.Project; +import play.mvc.Http; import services.impl.LocaleServiceImpl; import java.util.List; @@ -17,16 +18,12 @@ @ImplementedBy(LocaleServiceImpl.class) public interface LocaleService extends ModelService { - List latest(Project project, int limit); + Locale byProjectAndName(Project project, String name, Http.Request request); - Locale byProjectAndName(Project project, String name); - - Map progress(UUID projectId); - - void increaseWordCountBy(UUID localeId, int wordCountDiff); + void increaseWordCountBy(UUID localeId, int wordCountDiff, Http.Request request); void resetWordCount(UUID projectId); - Locale byOwnerAndProjectAndName(String username, String projectName, String localeName, + Locale byOwnerAndProjectAndName(String username, String projectName, String localeName, Http.Request request, String... fetches); } diff --git a/app/services/ModelService.java b/app/services/ModelService.java index ecd80f91..5dffe3b4 100644 --- a/app/services/ModelService.java +++ b/app/services/ModelService.java @@ -1,8 +1,10 @@ package services; +import criterias.GetCriteria; import io.ebean.PagedList; import criterias.AbstractSearchCriteria; import models.Model; +import play.mvc.Http; import java.util.Collection; @@ -14,17 +16,19 @@ public interface ModelService, ID, CRITERIA extends AbstractSearchCriteria> { PagedList findBy(CRITERIA criteria); - T byId(ID id, String... propertiesToFetch); + T byId(ID id, Http.Request request, String... propertiesToFetch); - T create(T model); + T byId(GetCriteria criteria); - T update(T model); + T create(T model, Http.Request request); - T save(T t); + T update(T model, Http.Request request); - Collection save(Collection t); + T save(T t, Http.Request request); - void delete(T t); + Collection save(Collection t, Http.Request request); - void delete(Collection t); + void delete(T t, Http.Request request); + + void delete(Collection t, Http.Request request); } diff --git a/app/services/ProjectService.java b/app/services/ProjectService.java index 4baec056..bb4eaed0 100644 --- a/app/services/ProjectService.java +++ b/app/services/ProjectService.java @@ -4,6 +4,7 @@ import criterias.ProjectCriteria; import models.Project; import models.User; +import play.mvc.Http; import services.impl.ProjectServiceImpl; import java.util.UUID; @@ -21,11 +22,11 @@ public interface ProjectService extends ModelService { /** * @param user * @param otherUser + * @param request * @return */ - User merge(User user, User otherUser); + User merge(User user, User otherUser, Http.Request request); /** * @param username + * @param request * @param fetches * @return */ - User byUsername(String username, String... fetches); + User byUsername(String username, Http.Request request, String... fetches); /** * @param userId @@ -39,12 +42,12 @@ public interface UserService extends ModelService { /** * Replace user settings with given settings. */ - User saveSettings(UUID userId, Map settings); + User saveSettings(UUID userId, Map settings, Http.Request request); /** * Add to or update user settings with given settings. */ - User updateSettings(UUID userId, Map settings); + User updateSettings(UUID userId, Map settings, Http.Request request); User byLinkedAccount(String providerKey, String providerUserId); diff --git a/app/services/api/LocaleApiService.java b/app/services/api/LocaleApiService.java index 479b6abe..1a2b2421 100644 --- a/app/services/api/LocaleApiService.java +++ b/app/services/api/LocaleApiService.java @@ -3,12 +3,13 @@ import com.google.inject.ImplementedBy; import criterias.LocaleCriteria; import dto.Locale; -import java.util.UUID; import play.mvc.Http; import play.mvc.Http.Request; -import play.mvc.Http.Response; +import play.mvc.Result; import services.api.impl.LocaleApiServiceImpl; +import java.util.UUID; + /** * @author resamsel * @version 29 Jan 2017 @@ -17,7 +18,7 @@ public interface LocaleApiService extends ApiService { Locale upload(UUID localeId, Request request); - byte[] download(Http.Request request, UUID localeId, String fileType, Response response); + Result download(Request request, UUID localeId, String fileType); Locale byOwnerAndProjectAndName(Http.Request request, String username, String projectName, String localeName, String... fetches); diff --git a/app/services/api/UserApiService.java b/app/services/api/UserApiService.java index 03455685..3fb79c7b 100644 --- a/app/services/api/UserApiService.java +++ b/app/services/api/UserApiService.java @@ -31,10 +31,10 @@ public interface UserApiService extends ApiService { /** * Replace given settings of the user. */ - User saveSettings(UUID userId, JsonNode json); + User saveSettings(UUID userId, JsonNode json, Http.Request request); /** * Add or update given settings of the user. */ - User updateSettings(UUID userId, JsonNode json); + User updateSettings(UUID userId, JsonNode json, Http.Request request); } diff --git a/app/services/api/impl/AbstractApiService.java b/app/services/api/impl/AbstractApiService.java index 7c6a9e04..2478980f 100644 --- a/app/services/api/impl/AbstractApiService.java +++ b/app/services/api/impl/AbstractApiService.java @@ -1,5 +1,6 @@ package services.api.impl; +import criterias.GetCriteria; import io.ebean.PagedList; import com.fasterxml.jackson.databind.JsonNode; import criterias.AbstractSearchCriteria; @@ -18,6 +19,7 @@ import javax.validation.ConstraintViolationException; import javax.validation.Validator; import java.util.Set; +import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; @@ -33,7 +35,7 @@ public abstract class AbstractApiService protected SERVICE service; private final Class dtoClass; - Function dtoMapper; + BiFunction dtoMapper; Scope[] readScopes; private final Scope[] writeScopes; protected final PermissionService permissionService; @@ -42,7 +44,7 @@ public abstract class AbstractApiService protected AbstractApiService( SERVICE service, Class dtoClass, - Function dtoMapper, + BiFunction dtoMapper, Scope[] readScopes, Scope[] writeScopes, PermissionService permissionService, @@ -63,7 +65,7 @@ protected AbstractApiService( * @return the DTO mapper */ protected Function getDtoMapper(Http.Request request) { - return dtoMapper; + return model -> dtoMapper.apply(model, request); } /** @@ -92,7 +94,7 @@ public PagedList find(CRITERIA criteria, Consumer validator) { public DTO get(Http.Request request, ID id, String... propertiesToFetch) { permissionService.checkPermissionAll(request, "Access token not allowed", readScopes); - MODEL obj = service.byId(id, propertiesToFetch); + MODEL obj = service.byId(GetCriteria.from(id, request).withFetches(propertiesToFetch)); if (obj == null) { throw new NotFoundException(dtoClass.getSimpleName(), id); @@ -108,7 +110,7 @@ public DTO get(Http.Request request, ID id, String... propertiesToFetch) { public DTO create(Http.Request request, JsonNode in) { permissionService.checkPermissionAll(request, "Access token not allowed", writeScopes); - return getDtoMapper(request).apply(service.create(toModel(toDto(in)))); + return getDtoMapper(request).apply(service.create(toModel(toDto(in)), request)); } /** @@ -118,7 +120,7 @@ public DTO create(Http.Request request, JsonNode in) { public DTO update(Http.Request request, JsonNode in) { permissionService.checkPermissionAll(request, "Access token not allowed", writeScopes); - return getDtoMapper(request).apply(service.update(toModel(toDto(in)))); + return getDtoMapper(request).apply(service.update(toModel(toDto(in)), request)); } /** @@ -128,7 +130,7 @@ public DTO update(Http.Request request, JsonNode in) { public DTO delete(Http.Request request, ID id) { permissionService.checkPermissionAll(request, "Access token not allowed", writeScopes); - MODEL m = service.byId(id); + MODEL m = service.byId(GetCriteria.from(id, request)); if (m == null) { throw new NotFoundException(dtoClass.getSimpleName(), id); @@ -136,7 +138,7 @@ public DTO delete(Http.Request request, ID id) { DTO out = getDtoMapper(request).apply(m); - service.delete(m); + service.delete(m, request); return out; } diff --git a/app/services/api/impl/AccessTokenApiServiceImpl.java b/app/services/api/impl/AccessTokenApiServiceImpl.java index 9a1c05aa..11d0b389 100644 --- a/app/services/api/impl/AccessTokenApiServiceImpl.java +++ b/app/services/api/impl/AccessTokenApiServiceImpl.java @@ -20,7 +20,7 @@ public AccessTokenApiServiceImpl(AccessTokenService service, PermissionService p super( service, dto.AccessToken.class, - AccessTokenMapper::toDto, + (in, request) -> AccessTokenMapper.toDto(in), new Scope[]{Scope.AccessTokenRead}, new Scope[]{Scope.AccessTokenWrite}, permissionService, diff --git a/app/services/api/impl/ActivityApiServiceImpl.java b/app/services/api/impl/ActivityApiServiceImpl.java index f6c4819a..78b9da2a 100644 --- a/app/services/api/impl/ActivityApiServiceImpl.java +++ b/app/services/api/impl/ActivityApiServiceImpl.java @@ -1,10 +1,10 @@ package services.api.impl; -import io.ebean.PagedList; import criterias.LogEntryCriteria; import dto.AuthorizationException; import dto.DtoPagedList; import dto.PermissionException; +import io.ebean.PagedList; import mappers.ActivityMapper; import mappers.AggregateMapper; import models.LogEntry; @@ -30,7 +30,7 @@ public class ActivityApiServiceImpl extends @Inject protected ActivityApiServiceImpl( LogEntryService logEntryService, PermissionService permissionService, Validator validator) { - super(logEntryService, dto.Activity.class, ActivityMapper::toDto, + super(logEntryService, dto.Activity.class, (in, request) -> ActivityMapper.toDto(in), new Scope[]{Scope.ProjectRead}, new Scope[]{Scope.ProjectWrite}, permissionService, @@ -54,6 +54,6 @@ public PagedList getAggregates(LogEntryCriteria criteria) { */ @Override protected LogEntry toModel(dto.Activity in) { - return ActivityMapper.toModel(in, service.byId(in.id)); + return ActivityMapper.toModel(in, service.byId(in.id, null /* FIXME */)); } } diff --git a/app/services/api/impl/KeyApiServiceImpl.java b/app/services/api/impl/KeyApiServiceImpl.java index eda861bc..6e75d07a 100644 --- a/app/services/api/impl/KeyApiServiceImpl.java +++ b/app/services/api/impl/KeyApiServiceImpl.java @@ -29,8 +29,8 @@ public class KeyApiServiceImpl extends @Inject protected KeyApiServiceImpl(KeyService localeService, ProjectService projectService, - PermissionService permissionService, Validator validator) { - super(localeService, dto.Key.class, KeyMapper::toDto, + PermissionService permissionService, Validator validator, KeyMapper keyMapper) { + super(localeService, dto.Key.class, keyMapper::toDto, new Scope[]{Scope.ProjectRead, Scope.KeyRead}, new Scope[]{Scope.ProjectRead, Scope.KeyWrite}, permissionService, @@ -45,12 +45,12 @@ public dto.Key byOwnerAndProjectAndName(Http.Request request, String username, S .checkPermissionAll(request, "Access token not allowed", Scope.ProjectRead, Scope.KeyRead, Scope.MessageRead); - Key key = service.byOwnerAndProjectAndName(username, projectName, keyName, fetches); + Key key = service.byOwnerAndProjectAndName(username, projectName, keyName, request, fetches); if (key == null) { throw new NotFoundException(dto.Key.class.getSimpleName(), keyName); } - return dtoMapper.apply(key); + return dtoMapper.apply(key, request); } /** @@ -58,6 +58,6 @@ public dto.Key byOwnerAndProjectAndName(Http.Request request, String username, S */ @Override protected Key toModel(dto.Key in) { - return KeyMapper.toModel(in, projectService.byId(in.projectId)); + return KeyMapper.toModel(in, projectService.byId(in.projectId, null /* FIXME */)); } } diff --git a/app/services/api/impl/LocaleApiServiceImpl.java b/app/services/api/impl/LocaleApiServiceImpl.java index 0efeb8d7..2d0bda08 100644 --- a/app/services/api/impl/LocaleApiServiceImpl.java +++ b/app/services/api/impl/LocaleApiServiceImpl.java @@ -1,5 +1,6 @@ package services.api.impl; +import criterias.GetCriteria; import criterias.LocaleCriteria; import dto.NotFoundException; import exporters.Exporter; @@ -14,11 +15,10 @@ import play.data.FormFactory; import play.inject.Injector; import play.mvc.Http; -import play.mvc.Http.Context; import play.mvc.Http.MultipartFormData; import play.mvc.Http.MultipartFormData.FilePart; import play.mvc.Http.Request; -import play.mvc.Http.Response; +import play.mvc.Result; import repositories.LocaleRepository; import services.LocaleService; import services.PermissionService; @@ -30,11 +30,13 @@ import javax.inject.Singleton; import javax.validation.ValidationException; import javax.validation.Validator; +import java.io.ByteArrayInputStream; import java.io.File; import java.util.UUID; import java.util.function.Supplier; import static java.util.Optional.ofNullable; +import static play.mvc.Results.ok; /** * @author resamsel @@ -42,8 +44,8 @@ */ @Singleton public class LocaleApiServiceImpl extends - AbstractApiService implements - LocaleApiService { + AbstractApiService implements + LocaleApiService { private static final Logger LOGGER = LoggerFactory.getLogger(LocaleApiServiceImpl.class); @@ -52,13 +54,13 @@ public class LocaleApiServiceImpl extends @Inject protected LocaleApiServiceImpl( - LocaleService localeService, ProjectService projectService, - Injector injector, PermissionService permissionService, Validator validator) { - super(localeService, dto.Locale.class, LocaleMapper::toDto, - new Scope[]{Scope.ProjectRead, Scope.LocaleRead}, - new Scope[]{Scope.ProjectRead, Scope.LocaleWrite}, - permissionService, - validator); + LocaleService localeService, ProjectService projectService, + Injector injector, PermissionService permissionService, Validator validator, LocaleMapper localeMapper) { + super(localeService, dto.Locale.class, localeMapper::toDto, + new Scope[]{Scope.ProjectRead, Scope.LocaleRead}, + new Scope[]{Scope.ProjectRead, Scope.LocaleWrite}, + permissionService, + validator); this.projectService = projectService; this.injector = injector; @@ -68,15 +70,15 @@ protected LocaleApiServiceImpl( public dto.Locale byOwnerAndProjectAndName(Http.Request request, String username, String projectName, String localeName, String... fetches) { permissionService - .checkPermissionAll(request, "Access token not allowed", Scope.ProjectRead, Scope.LocaleRead, - Scope.MessageRead); + .checkPermissionAll(request, "Access token not allowed", Scope.ProjectRead, Scope.LocaleRead, + Scope.MessageRead); - Locale locale = service.byOwnerAndProjectAndName(username, projectName, localeName, fetches); + Locale locale = service.byOwnerAndProjectAndName(username, projectName, localeName, request, fetches); if (locale == null) { throw new NotFoundException(dto.Locale.class.getSimpleName(), localeName); } - return dtoMapper.apply(locale); + return dtoMapper.apply(locale, request); } /** @@ -85,29 +87,28 @@ public dto.Locale byOwnerAndProjectAndName(Http.Request request, String username @Override public dto.Locale upload(UUID localeId, Request request) { permissionService - .checkPermissionAll(request, "Access token not allowed", Scope.ProjectRead, Scope.LocaleRead, - Scope.MessageWrite); + .checkPermissionAll(request, "Access token not allowed", Scope.ProjectRead, Scope.LocaleRead, + Scope.MessageWrite); - Locale locale = ofNullable(service.byId(localeId)) - .orElseThrow(() -> new NotFoundException(dto.Locale.class.getSimpleName(), localeId)); + Locale locale = ofNullable(service.byId(GetCriteria.from(localeId, request))) + .orElseThrow(() -> new NotFoundException(dto.Locale.class.getSimpleName(), localeId)); MultipartFormData body = ofNullable(request.body().asMultipartFormData()) - .orElseThrow(() -> new IllegalArgumentException( - Context.current().messages().at("import.error.multipartMissing"))); + .orElseThrow(() -> new IllegalArgumentException("import.error.multipartMissing")); FilePart messages = ofNullable(body.getFile("messages")) - .orElseThrow(() -> new IllegalArgumentException("Part 'messages' missing")); + .orElseThrow(() -> new IllegalArgumentException("Part 'messages' missing")); ImportLocaleForm form = injector.instanceOf(FormFactory.class) - .form(ImportLocaleForm.class) - .bindFromRequest() - .get(); + .form(ImportLocaleForm.class) + .bindFromRequest(request) + .get(); LOGGER.debug("Type: {}", form.getFileType()); Importer importer = ofNullable(FileFormatRegistry.IMPORTER_MAP.get(FileType.fromKey(form.getFileType()))) - .map(injector::instanceOf) - .orElseThrow(() -> new IllegalArgumentException("File type " + form.getFileType() + " not supported yet")); + .map(injector::instanceOf) + .orElseThrow(() -> new IllegalArgumentException("File type " + form.getFileType() + " not supported yet")); try { importer.apply(messages.getRef(), locale); @@ -117,27 +118,23 @@ public dto.Locale upload(UUID localeId, Request request) { LOGGER.debug("End of import"); - return dtoMapper.apply(locale); + return dtoMapper.apply(locale, request); } - /** - * {@inheritDoc} - */ @Override - public byte[] download(Http.Request request, UUID localeId, String fileType, Response response) { + public Result download(Request request, UUID localeId, String fileType) { permissionService - .checkPermissionAll(request, "Access token not allowed", Scope.ProjectRead, Scope.LocaleRead, - Scope.MessageRead); + .checkPermissionAll(request, "Access token not allowed", Scope.ProjectRead, Scope.LocaleRead, + Scope.MessageRead); - Locale locale = ofNullable(service.byId(localeId, LocaleRepository.FETCH_MESSAGES)) - .orElseThrow(() -> new NotFoundException(dto.Locale.class.getSimpleName(), localeId)); + Locale locale = ofNullable(service.byId(GetCriteria.from(localeId, request, LocaleRepository.FETCH_MESSAGES))) + .orElseThrow(() -> new NotFoundException(dto.Locale.class.getSimpleName(), localeId)); Exporter exporter = ofNullable(FileFormatRegistry.EXPORTER_MAP.get(FileType.fromKey(fileType))) - .map(Supplier::get) - .orElseThrow(() -> new ValidationException("File type " + fileType + " not supported yet")); - exporter.addHeaders(response, locale); + .map(Supplier::get) + .orElseThrow(() -> new ValidationException("File type " + fileType + " not supported yet")); - return exporter.apply(locale); + return exporter.addHeaders(ok(new ByteArrayInputStream(exporter.apply(locale))), locale); } /** @@ -145,6 +142,6 @@ public byte[] download(Http.Request request, UUID localeId, String fileType, Res */ @Override protected Locale toModel(dto.Locale in) { - return LocaleMapper.toModel(in, projectService.byId(in.projectId)); + return LocaleMapper.toModel(in, projectService.byId(GetCriteria.from(in.projectId, null /* FIXME */))); } } diff --git a/app/services/api/impl/MessageApiServiceImpl.java b/app/services/api/impl/MessageApiServiceImpl.java index a19b6f3a..16e7f8de 100644 --- a/app/services/api/impl/MessageApiServiceImpl.java +++ b/app/services/api/impl/MessageApiServiceImpl.java @@ -29,8 +29,9 @@ public class MessageApiServiceImpl extends @Inject protected MessageApiServiceImpl(MessageService messageService, LocaleService localeService, - KeyService keyService, PermissionService permissionService, Validator validator) { - super(messageService, dto.Message.class, MessageMapper::toDto, + KeyService keyService, PermissionService permissionService, Validator validator, + MessageMapper messageMapper) { + super(messageService, dto.Message.class, messageMapper::toDto, new Scope[]{Scope.ProjectRead, Scope.MessageRead}, new Scope[]{Scope.ProjectRead, Scope.MessageWrite}, permissionService, @@ -45,6 +46,6 @@ protected MessageApiServiceImpl(MessageService messageService, LocaleService loc */ @Override protected Message toModel(dto.Message in) { - return MessageMapper.toModel(in, localeService.byId(in.localeId), keyService.byId(in.keyId)); + return MessageMapper.toModel(in, localeService.byId(in.localeId, null /* FIXME */), keyService.byId(in.keyId, null /* FIXME */)); } } diff --git a/app/services/api/impl/ProjectApiServiceImpl.java b/app/services/api/impl/ProjectApiServiceImpl.java index a86b76e2..7d475f73 100644 --- a/app/services/api/impl/ProjectApiServiceImpl.java +++ b/app/services/api/impl/ProjectApiServiceImpl.java @@ -23,8 +23,8 @@ import models.User; import models.UserRole; import play.i18n.Messages; +import play.i18n.MessagesApi; import play.mvc.Http; -import play.mvc.Http.Context; import services.AuthProvider; import services.KeyService; import services.LocaleService; @@ -42,6 +42,7 @@ import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; +import java.util.stream.Collectors; import static utils.FunctionalUtils.peek; @@ -59,13 +60,15 @@ public class ProjectApiServiceImpl extends private final KeyService keyService; private final LogEntryService logEntryService; private final AuthProvider authProvider; + private final MessagesApi messagesApi; @Inject protected ProjectApiServiceImpl( Config configuration, ProjectService projectService, LocaleService localeService, KeyService keyService, LogEntryService logEntryService, - PermissionService permissionService, AuthProvider authProvider, Validator validator) { - super(projectService, dto.Project.class, ProjectMapper::toDto, + PermissionService permissionService, AuthProvider authProvider, Validator validator, + MessagesApi messagesApi, ProjectMapper projectMapper) { + super(projectService, dto.Project.class, projectMapper::toDto, new Scope[]{Scope.ProjectRead}, new Scope[]{Scope.ProjectWrite}, permissionService, @@ -76,6 +79,7 @@ protected ProjectApiServiceImpl( this.keyService = keyService; this.logEntryService = logEntryService; this.authProvider = authProvider; + this.messagesApi = messagesApi; } @Override @@ -93,11 +97,11 @@ public dto.Project byOwnerAndName(Http.Request request, String username, String permissionService .checkPermissionAll(request, "Access token not allowed", readScopes); - Project project = service.byOwnerAndName(username, name, fetches); + Project project = service.byOwnerAndName(username, name, request, fetches); return Optional.ofNullable(project) .map(peek(validator)) - .map(dtoMapper) + .map(getDtoMapper(request)) .orElseThrow(() -> new NotFoundException(dto.Project.class.getSimpleName(), username + "/" + name)); } @@ -118,7 +122,7 @@ public PagedList activity(Http.Request request, UUID id) { public SearchResponse search(Http.Request request, UUID projectId, SearchForm search) { permissionService.checkPermissionAll(request, "Access token not allowed", readScopes); - Messages messages = Context.current().messages(); + Messages messages = messagesApi.preferred(request); dto.Project project = get(request, projectId); @@ -127,13 +131,20 @@ public SearchResponse search(Http.Request request, UUID projectId, SearchForm se List suggestions = new ArrayList<>(); if (permissionService.hasPermissionAll(request, Scope.KeyRead)) { - PagedList keys = keyService + PagedList keys = keyService .findBy(KeyCriteria.from(search).withProjectId(project.id).withOrder("whenUpdated desc")); search.pager(keys); if (!keys.getList().isEmpty()) { - suggestions.addAll(keys.getList()); + suggestions.addAll(keys + .getList() + .stream() + .map(key -> Suggestable.DefaultSuggestable.from( + messages.at("key.autocomplete", key.name), + Data.from(Key.class, key.id, key.name, null) + )) + .collect(Collectors.toList())); } if (search.hasMore) { suggestions.add(Suggestable.DefaultSuggestable.from( @@ -150,12 +161,18 @@ public SearchResponse search(Http.Request request, UUID projectId, SearchForm se } if (permissionService.hasPermissionAll(request, Scope.LocaleRead)) { - PagedList locales = localeService.findBy(new LocaleCriteria() + PagedList locales = localeService.findBy(new LocaleCriteria() .withProjectId(project.id).withSearch(search.search).withOrder("whenUpdated desc")); search.pager(locales); if (!locales.getList().isEmpty()) { - suggestions.addAll(locales.getList()); + suggestions.addAll(locales.getList() + .stream() + .map(locale -> Suggestable.DefaultSuggestable.from( + messages.at("locale.autocomplete", locale.name), + Data.from(Locale.class, locale.id, locale.name, null) + )) + .collect(Collectors.toList())); } if (search.hasMore) { suggestions.add(Suggestable.DefaultSuggestable.from( diff --git a/app/services/api/impl/ProjectUserApiServiceImpl.java b/app/services/api/impl/ProjectUserApiServiceImpl.java index c27883b3..d3ddacc1 100644 --- a/app/services/api/impl/ProjectUserApiServiceImpl.java +++ b/app/services/api/impl/ProjectUserApiServiceImpl.java @@ -23,7 +23,7 @@ public class ProjectUserApiServiceImpl extends @Inject protected ProjectUserApiServiceImpl(ProjectUserService projectUserService, PermissionService permissionService, Validator validator) { - super(projectUserService, dto.ProjectUser.class, ProjectUserMapper::toDto, + super(projectUserService, dto.ProjectUser.class, (in, request) -> ProjectUserMapper.toDto(in), new Scope[]{Scope.ProjectRead, Scope.MemberRead}, new Scope[]{Scope.ProjectRead, Scope.MemberWrite}, permissionService, diff --git a/app/services/api/impl/UserApiServiceImpl.java b/app/services/api/impl/UserApiServiceImpl.java index 04a61435..084fe0ec 100644 --- a/app/services/api/impl/UserApiServiceImpl.java +++ b/app/services/api/impl/UserApiServiceImpl.java @@ -1,6 +1,7 @@ package services.api.impl; import com.fasterxml.jackson.databind.JsonNode; +import criterias.GetCriteria; import criterias.LogEntryCriteria; import criterias.UserCriteria; import dto.DtoPagedList; @@ -49,7 +50,7 @@ protected UserApiServiceImpl( AuthProvider authProvider, PermissionService permissionService, LogEntryService logEntryService, Validator validator) { - super(userService, dto.User.class, UserMapper::toDto, + super(userService, dto.User.class, (in, request) -> UserMapper.toDto(in), new Scope[]{Scope.UserRead}, new Scope[]{Scope.UserWrite}, permissionService, @@ -77,14 +78,14 @@ public dto.User create(Http.Request request) { user.linkedAccounts = Collections.singletonList(linkedAccount); }); - return getDtoMapper(request).apply(service.create(user)); + return getDtoMapper(request).apply(service.create(user, request)); } @Override public dto.User byUsername(Http.Request request, String username, String... propertiesToFetch) { permissionService.checkPermissionAll(request, "Access token not allowed", readScopes); - return Optional.ofNullable(service.byUsername(username, propertiesToFetch)) + return Optional.ofNullable(service.byUsername(username, request, propertiesToFetch)) .map(getDtoMapper(request)) .orElseThrow(() -> new NotFoundException(dto.User.class.getSimpleName(), username)); } @@ -109,17 +110,17 @@ public Profile profile(Http.Request request) { public dto.User me(Http.Request request, String... propertiesToFetch) { UUID loggedInUserId = authProvider.loggedInUserId(request); - return dtoMapper.apply(service.byId(loggedInUserId, propertiesToFetch)); + return dtoMapper.apply(service.byId(GetCriteria.from(loggedInUserId, request, propertiesToFetch)), request); } @Override - public dto.User saveSettings(UUID userId, JsonNode json) { - return dtoMapper.apply(service.saveSettings(userId, Json.fromJson(json, Map.class))); + public dto.User saveSettings(UUID userId, JsonNode json, Http.Request request) { + return dtoMapper.apply(service.saveSettings(userId, Json.fromJson(json, Map.class), request), request); } @Override - public dto.User updateSettings(UUID userId, JsonNode json) { - return dtoMapper.apply(service.updateSettings(userId, Json.fromJson(json, Map.class))); + public dto.User updateSettings(UUID userId, JsonNode json, Http.Request request) { + return dtoMapper.apply(service.updateSettings(userId, Json.fromJson(json, Map.class), request), request); } /** @@ -127,6 +128,6 @@ public dto.User updateSettings(UUID userId, JsonNode json) { */ @Override protected User toModel(dto.User in) { - return UserMapper.toModel(in, service.byId(in.id)); + return UserMapper.toModel(in, service.byId(GetCriteria.from(in.id, null /* FIXME */))); } } diff --git a/app/services/api/impl/UserFeatureFlagApiServiceImpl.java b/app/services/api/impl/UserFeatureFlagApiServiceImpl.java index 28379749..807fd0ce 100644 --- a/app/services/api/impl/UserFeatureFlagApiServiceImpl.java +++ b/app/services/api/impl/UserFeatureFlagApiServiceImpl.java @@ -21,7 +21,7 @@ public UserFeatureFlagApiServiceImpl(UserFeatureFlagService service, PermissionS super( service, dto.UserFeatureFlag.class, - UserFeatureFlagMapper::toDto, + (in, request) -> UserFeatureFlagMapper.toDto(in), new Scope[]{Scope.FeatureFlagRead}, new Scope[]{Scope.FeatureFlagWrite}, permissionService, diff --git a/app/services/impl/AbstractModelService.java b/app/services/impl/AbstractModelService.java index 77beac2d..526d5e05 100644 --- a/app/services/impl/AbstractModelService.java +++ b/app/services/impl/AbstractModelService.java @@ -1,10 +1,12 @@ package services.impl; +import criterias.GetCriteria; import io.ebean.PagedList; import criterias.AbstractSearchCriteria; import models.Model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import play.mvc.Http; import repositories.ModelRepository; import services.AuthProvider; import services.CacheService; @@ -50,21 +52,21 @@ public AbstractModelService(Validator validator, CacheService cache, */ @Override public PagedList findBy(CRITERIA criteria) { - criteria.setLoggedInUserId(authProvider.loggedInUserId()); + criteria.setLoggedInUserId(authProvider.loggedInUserId(criteria.getRequest())); return postFind(cache.getOrElseUpdate( requireNonNull(criteria, "criteria is null").getCacheKey(), () -> modelRepository.findBy(criteria), 60 - )); + ), criteria.getRequest()); } - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { return pagedList; } @Override - public MODEL byId(ID id, String... fetches) { + public MODEL byId(ID id, Http.Request request, String... fetches) { if (id == null) { return null; } @@ -73,10 +75,25 @@ public MODEL byId(ID id, String... fetches) { cacheKeyGetter.apply(id, fetches), () -> modelRepository.byId(id, fetches), 60 - )); + ), + request); } - protected MODEL postGet(MODEL model) { + @Override + public MODEL byId(GetCriteria criteria) { + if (criteria == null) { + return null; + } + + return postGet(cache.getOrElseUpdate( + cacheKeyGetter.apply(criteria.getId(), criteria.getFetches().toArray(new String[0])), + () -> modelRepository.byId(criteria), + 60 + ), + criteria.getRequest()); + } + + protected MODEL postGet(MODEL model, Http.Request request) { return model; } @@ -84,22 +101,22 @@ protected MODEL postGet(MODEL model) { * {@inheritDoc} */ @Override - public MODEL create(MODEL model) { + public MODEL create(MODEL model, Http.Request request) { LOGGER.debug("create({})", model); - preCreate(model); + preCreate(model, request); MODEL m = modelRepository.save(model); - postCreate(m); + postCreate(m, request); return m; } - protected void preCreate(MODEL t) { + protected void preCreate(MODEL t, Http.Request request) { } - protected void postCreate(MODEL t) { + protected void postCreate(MODEL t, Http.Request request) { cache.set(cacheKeyGetter.apply(t.getId(), new String[0]), t, 60); } @@ -107,17 +124,17 @@ protected void postCreate(MODEL t) { * {@inheritDoc} */ @Override - public MODEL update(MODEL t) { + public MODEL update(MODEL t, Http.Request request) { LOGGER.debug("update({})", t); MODEL m = modelRepository.update(t); - postUpdate(m); + postUpdate(m, request); return m; } - protected MODEL postUpdate(MODEL t) { + protected MODEL postUpdate(MODEL t, Http.Request request) { cache.removeByPrefix(cacheKeyGetter.apply(t.getId(), new String[0])); cache.set(cacheKeyGetter.apply(t.getId(), new String[0]), t, 60); @@ -125,28 +142,28 @@ protected MODEL postUpdate(MODEL t) { } @Override - public MODEL save(MODEL t) { + public MODEL save(MODEL t, Http.Request request) { return modelRepository.save(t); } @Override - public Collection save(Collection t) { + public Collection save(Collection t, Http.Request request) { return modelRepository.save(t); } @Override - public void delete(MODEL t) { + public void delete(MODEL t, Http.Request request) { modelRepository.delete(t); - postDelete(t); + postDelete(t, request); } @Override - public void delete(Collection t) { + public void delete(Collection t, Http.Request request) { modelRepository.delete(t); } - protected void postDelete(MODEL t) { + protected void postDelete(MODEL t, Http.Request request) { cache.removeByPrefix(cacheKeyGetter.apply(t.getId(), new String[0])); } } diff --git a/app/services/impl/AccessTokenServiceImpl.java b/app/services/impl/AccessTokenServiceImpl.java index f6a5679b..eee9cf7f 100644 --- a/app/services/impl/AccessTokenServiceImpl.java +++ b/app/services/impl/AccessTokenServiceImpl.java @@ -8,6 +8,7 @@ import models.UserRole; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import play.mvc.Http; import repositories.AccessTokenRepository; import services.*; @@ -45,7 +46,7 @@ public AccessTokenServiceImpl( @Override public PagedList findBy(AccessTokenCriteria criteria) { - User loggedInUser = authProvider.loggedInUser(); + User loggedInUser = authProvider.loggedInUser(criteria.getRequest()); if (loggedInUser != null && loggedInUser.role != UserRole.Admin) { criteria.setUserId(loggedInUser.id); } @@ -54,36 +55,36 @@ public PagedList findBy(AccessTokenCriteria criteria) { } @Override - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { metricService.logEvent(AccessToken.class, ActionType.Read); - return super.postFind(pagedList); + return super.postFind(pagedList, request); } @Override - protected AccessToken postGet(AccessToken accessToken) { + protected AccessToken postGet(AccessToken accessToken, Http.Request request) { metricService.logEvent(AccessToken.class, ActionType.Read); - return super.postGet(accessToken); + return super.postGet(accessToken, request); } /** * {@inheritDoc} */ @Override - public AccessToken byKey(String accessTokenKey) { + public AccessToken byKey(String accessTokenKey, Http.Request request) { metricService.logEvent(AccessToken.class, ActionType.Read); return log( - () -> postGet(accessTokenRepository.byKey(accessTokenKey)), + () -> postGet(accessTokenRepository.byKey(accessTokenKey), request), LOGGER, "byKey" ); } @Override - protected void postCreate(AccessToken t) { - super.postCreate(t); + protected void postCreate(AccessToken t, Http.Request request) { + super.postCreate(t, request); metricService.logEvent(AccessToken.class, ActionType.Create); @@ -92,8 +93,8 @@ protected void postCreate(AccessToken t) { } @Override - protected AccessToken postUpdate(AccessToken t) { - super.postUpdate(t); + protected AccessToken postUpdate(AccessToken t, Http.Request request) { + super.postUpdate(t, request); metricService.logEvent(AccessToken.class, ActionType.Update); @@ -107,8 +108,8 @@ protected AccessToken postUpdate(AccessToken t) { * {@inheritDoc} */ @Override - protected void postDelete(AccessToken t) { - super.postDelete(t); + protected void postDelete(AccessToken t, Http.Request request) { + super.postDelete(t, request); metricService.logEvent(AccessToken.class, ActionType.Delete); diff --git a/app/services/impl/AuthProviderImpl.java b/app/services/impl/AuthProviderImpl.java index 7e2d4f84..cf27f559 100644 --- a/app/services/impl/AuthProviderImpl.java +++ b/app/services/impl/AuthProviderImpl.java @@ -14,7 +14,6 @@ import play.libs.typedmap.TypedKey; import play.mvc.Http; import services.AuthProvider; -import services.ContextProvider; import services.UserService; import javax.inject.Inject; @@ -26,7 +25,6 @@ @Singleton public class AuthProviderImpl implements AuthProvider { - private final ContextProvider contextProvider; private final Injector injector; private final PlaySessionStore sessionStore; @@ -38,23 +36,12 @@ public class AuthProviderImpl implements AuthProvider { @Inject public AuthProviderImpl( - ContextProvider contextProvider, Injector injector, PlaySessionStore sessionStore) { - this.contextProvider = contextProvider; this.injector = injector; this.sessionStore = sessionStore; } - /** - * @deprecated use {{@link AuthProviderImpl#loggedInUser(Http.Request)} instead. - */ - @Override - @Deprecated - public User loggedInUser() { - return loggedInUser(contextProvider.getOrNull().request()); - } - @Override public User loggedInUser(Http.Request request) { // Logged-in via auth plugin? @@ -87,15 +74,9 @@ public User loggedInUser(Http.Request request) { return null; } - @Deprecated - @Override - public UUID loggedInUserId() { - return loggedInUserId(contextProvider.getOrNull().request()); - } - @Override public UUID loggedInUserId(Http.Request request) { - User loggedInUser = loggedInUser(); + User loggedInUser = loggedInUser(request); if (loggedInUser == null) { return null; @@ -115,7 +96,7 @@ public Optional loggedInProfile(WebContext context) { } @Override - public void updateUser(CommonProfile profile) { + public void updateUser(CommonProfile profile, Http.Request request) { if (profile == null) { return; } @@ -132,7 +113,7 @@ public void updateUser(CommonProfile profile) { if (!newRole.equals(user.role)) { user.role = newRole; - userService.update(user); + userService.update(user, request); } } diff --git a/app/services/impl/CacheServiceImpl.java b/app/services/impl/CacheServiceImpl.java index 15e10f98..4b3e3548 100644 --- a/app/services/impl/CacheServiceImpl.java +++ b/app/services/impl/CacheServiceImpl.java @@ -32,13 +32,13 @@ public CacheServiceImpl(SyncCacheApi cache) { } @Override - public T get(String key) { + public Optional get(String key) { return cache.get(key); } @Override public Optional getOptional(String key) { - return cache.getOptional(key); + return cache.get(key); } @Override diff --git a/app/services/impl/ContextProviderImpl.java b/app/services/impl/ContextProviderImpl.java deleted file mode 100644 index cb168ea2..00000000 --- a/app/services/impl/ContextProviderImpl.java +++ /dev/null @@ -1,22 +0,0 @@ -package services.impl; - -import play.mvc.Http; -import services.ContextProvider; - -public class ContextProviderImpl implements ContextProvider { - @Override - public Http.Context get() { - return Http.Context.current(); - } - - @Override - public Http.Context getOrNull() { - Http.Context ctx = Http.Context.current.get(); - - if (ctx != null) { - return ctx; - } - - return null; - } -} diff --git a/app/services/impl/KeyServiceImpl.java b/app/services/impl/KeyServiceImpl.java index d870bf3a..4686329d 100644 --- a/app/services/impl/KeyServiceImpl.java +++ b/app/services/impl/KeyServiceImpl.java @@ -1,5 +1,6 @@ package services.impl; +import criterias.GetCriteria; import io.ebean.PagedList; import criterias.KeyCriteria; import models.ActionType; @@ -7,6 +8,7 @@ import models.Project; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import play.mvc.Http; import repositories.KeyRepository; import repositories.Persistence; import services.*; @@ -14,7 +16,7 @@ import javax.inject.Inject; import javax.validation.Validator; import java.util.List; -import java.util.Map; +import java.util.Optional; import java.util.UUID; import static utils.Stopwatch.log; @@ -50,21 +52,13 @@ public KeyServiceImpl(Validator validator, CacheService cache, KeyRepository key * {@inheritDoc} */ @Override - public Map progress(UUID projectId) { - return keyRepository.progress(projectId); - } - - /** - * {@inheritDoc} - */ - @Override - public void increaseWordCountBy(UUID keyId, int wordCountDiff) { + public void increaseWordCountBy(UUID keyId, int wordCountDiff, Http.Request request) { if (wordCountDiff == 0) { LOGGER.debug("Not changing word count"); return; } - Key key = modelRepository.byId(keyId); + Key key = modelRepository.byId(GetCriteria.from(keyId, request)); if (key == null) { return; @@ -97,37 +91,28 @@ public void resetWordCount(UUID projectId) { } @Override - public List latest(Project project, int limit) { - return postFind(cache.getOrElseUpdate( - String.format("project:id:%s:latest:keys:%d", project.id, limit), - () -> keyRepository.latest(project, limit), - 60 - )); - } - - @Override - public Key byProjectAndName(Project project, String name) { + public Key byProjectAndName(Project project, String name, Http.Request request) { return postGet(cache.getOrElseUpdate( getCacheKey(project.id, name), () -> keyRepository.byProjectAndName(project, name), 60 - )); + ), request); } @Override - public Key byOwnerAndProjectAndName(String username, String projectName, String keyName, String... fetches) { + public Key byOwnerAndProjectAndName(String username, String projectName, String keyName, Http.Request request, String... fetches) { return postGet(cache.getOrElseUpdate( String.format("key:owner:%s:projectName:%s:name:%s", username, projectName, keyName), () -> keyRepository.byOwnerAndProjectAndName(username, projectName, keyName, fetches), 60 - )); + ), request); } @Override - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { metricService.logEvent(Key.class, ActionType.Read); - return super.postFind(pagedList); + return super.postFind(pagedList, request); } protected List postFind(List list) { @@ -137,15 +122,15 @@ protected List postFind(List list) { } @Override - protected Key postGet(Key key) { + protected Key postGet(Key key, Http.Request request) { metricService.logEvent(Key.class, ActionType.Read); - return super.postGet(key); + return super.postGet(key, request); } @Override - protected void postCreate(Key t) { - super.postCreate(t); + protected void postCreate(Key t, Http.Request request) { + super.postCreate(t, request); metricService.logEvent(Key.class, ActionType.Create); @@ -160,17 +145,17 @@ protected void postCreate(Key t) { } @Override - protected Key postUpdate(Key t) { + protected Key postUpdate(Key t, Http.Request request) { metricService.logEvent(Key.class, ActionType.Update); - Key existing = cache.get(Key.getCacheKey(t.id)); - if (existing != null) { - cache.removeByPrefix(getCacheKey(existing.project.id, existing.name)); + Optional existing = cache.get(Key.getCacheKey(t.id)); + if (existing.isPresent()) { + cache.removeByPrefix(getCacheKey(existing.get().project.id, existing.get().name)); } else { cache.removeByPrefix(getCacheKey(t.project.id, "")); } - super.postUpdate(t); + super.postUpdate(t, request); // When locale has been updated, the locale cache needs to be invalidated cache.removeByPrefix("key:criteria:" + t.project.id); @@ -182,15 +167,15 @@ protected Key postUpdate(Key t) { * {@inheritDoc} */ @Override - protected void postDelete(Key t) { + protected void postDelete(Key t, Http.Request request) { metricService.logEvent(Key.class, ActionType.Delete); - Key existing = byId(t.id); + Key existing = byId(t.id, request); if (existing != null) { cache.removeByPrefix(getCacheKey(existing.project.id, existing.name)); } - super.postDelete(t); + super.postDelete(t, request); // When key has been deleted, the project cache needs to be invalidated cache.removeByPrefix(Project.getCacheKey(t.project.id)); diff --git a/app/services/impl/LinkedAccountServiceImpl.java b/app/services/impl/LinkedAccountServiceImpl.java index 1c3f53aa..d6d2cefc 100644 --- a/app/services/impl/LinkedAccountServiceImpl.java +++ b/app/services/impl/LinkedAccountServiceImpl.java @@ -4,6 +4,7 @@ import criterias.LinkedAccountCriteria; import models.ActionType; import models.LinkedAccount; +import play.mvc.Http; import repositories.LinkedAccountRepository; import services.*; @@ -31,17 +32,17 @@ public LinkedAccountServiceImpl(Validator validator, CacheService cache, } @Override - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { metricService.logEvent(LinkedAccount.class, ActionType.Read); - return super.postFind(pagedList); + return super.postFind(pagedList, request); } @Override - protected LinkedAccount postGet(LinkedAccount model) { + protected LinkedAccount postGet(LinkedAccount model, Http.Request request) { metricService.logEvent(LinkedAccount.class, ActionType.Read); - return super.postGet(model); + return super.postGet(model, request); } /** @@ -58,8 +59,8 @@ public LinkedAccount create(LinkedAccount linkedAccount) { } @Override - protected void postCreate(LinkedAccount t) { - super.postCreate(t); + protected void postCreate(LinkedAccount t, Http.Request request) { + super.postCreate(t, request); metricService.logEvent(LinkedAccount.class, ActionType.Create); @@ -68,8 +69,8 @@ protected void postCreate(LinkedAccount t) { } @Override - protected LinkedAccount postUpdate(LinkedAccount t) { - super.postUpdate(t); + protected LinkedAccount postUpdate(LinkedAccount t, Http.Request request) { + super.postUpdate(t, request); metricService.logEvent(LinkedAccount.class, ActionType.Update); @@ -83,8 +84,8 @@ protected LinkedAccount postUpdate(LinkedAccount t) { * {@inheritDoc} */ @Override - protected void postDelete(LinkedAccount t) { - super.postDelete(t); + protected void postDelete(LinkedAccount t, Http.Request request) { + super.postDelete(t, request); metricService.logEvent(LinkedAccount.class, ActionType.Delete); diff --git a/app/services/impl/LocaleServiceImpl.java b/app/services/impl/LocaleServiceImpl.java index 49ecc798..f3c24bff 100644 --- a/app/services/impl/LocaleServiceImpl.java +++ b/app/services/impl/LocaleServiceImpl.java @@ -1,5 +1,6 @@ package services.impl; +import criterias.GetCriteria; import io.ebean.PagedList; import criterias.LocaleCriteria; import models.ActionType; @@ -7,6 +8,7 @@ import models.Project; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import play.mvc.Http; import repositories.LocaleRepository; import repositories.Persistence; import services.*; @@ -15,7 +17,6 @@ import javax.inject.Singleton; import javax.validation.Validator; import java.util.List; -import java.util.Map; import java.util.UUID; import static utils.Stopwatch.log; @@ -46,50 +47,34 @@ public LocaleServiceImpl(Validator validator, CacheService cache, } @Override - public List latest(Project project, int limit) { - return postFind(cache.getOrElseUpdate( - String.format("project:id:%s:latest:locales:%d", project.id, limit), - () -> localeRepository.latest(project, limit), - 60)); - } - - @Override - public Locale byProjectAndName(Project project, String name) { + public Locale byProjectAndName(Project project, String name, Http.Request request) { return postGet(cache.getOrElseUpdate( String.format("project:id:%s:locale:%s", project.id, name), () -> localeRepository.byProjectAndName(project, name), - 60)); + 60), request); } @Override - public Locale byOwnerAndProjectAndName(String username, String projectName, String localeName, + public Locale byOwnerAndProjectAndName(String username, String projectName, String localeName, Http.Request request, String... fetches) { return postGet(cache.getOrElseUpdate( String.format("locale:owner:%s:projectName:%s:name:%s", username, projectName, localeName), () -> localeRepository.byOwnerAndProjectAndName(username, projectName, localeName, fetches), 60 - )); - } - - /** - * {@inheritDoc} - */ - @Override - public Map progress(UUID projectId) { - return localeRepository.progress(projectId); + ), request); } /** * {@inheritDoc} */ @Override - public void increaseWordCountBy(UUID localeId, int wordCountDiff) { + public void increaseWordCountBy(UUID localeId, int wordCountDiff, Http.Request request) { if (wordCountDiff == 0) { LOGGER.debug("Not changing word count"); return; } - Locale locale = modelRepository.byId(localeId); + Locale locale = modelRepository.byId(GetCriteria.from(localeId, request)); if (locale == null) { return; @@ -117,10 +102,10 @@ public void resetWordCount(UUID projectId) { } @Override - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { metricService.logEvent(Locale.class, ActionType.Read); - return super.postFind(pagedList); + return super.postFind(pagedList, request); } protected List postFind(List list) { @@ -130,15 +115,15 @@ protected List postFind(List list) { } @Override - protected Locale postGet(Locale locale) { + protected Locale postGet(Locale locale, Http.Request request) { metricService.logEvent(Locale.class, ActionType.Read); - return super.postGet(locale); + return super.postGet(locale, request); } @Override - protected void postCreate(Locale t) { - super.postCreate(t); + protected void postCreate(Locale t, Http.Request request) { + super.postCreate(t, request); metricService.logEvent(Locale.class, ActionType.Create); @@ -153,8 +138,8 @@ protected void postCreate(Locale t) { } @Override - protected Locale postUpdate(Locale t) { - super.postUpdate(t); + protected Locale postUpdate(Locale t, Http.Request request) { + super.postUpdate(t, request); metricService.logEvent(Locale.class, ActionType.Update); @@ -168,8 +153,8 @@ protected Locale postUpdate(Locale t) { * {@inheritDoc} */ @Override - protected void postDelete(Locale t) { - super.postDelete(t); + protected void postDelete(Locale t, Http.Request request) { + super.postDelete(t, request); metricService.logEvent(Locale.class, ActionType.Delete); diff --git a/app/services/impl/LogEntryServiceImpl.java b/app/services/impl/LogEntryServiceImpl.java index 10524b31..a72497d1 100644 --- a/app/services/impl/LogEntryServiceImpl.java +++ b/app/services/impl/LogEntryServiceImpl.java @@ -10,6 +10,7 @@ import models.LogEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import play.mvc.Http; import repositories.LogEntryRepository; import repositories.Persistence; import services.AuthProvider; @@ -110,16 +111,16 @@ private RawSql getAggregatesRawSql() { } @Override - protected void postCreate(LogEntry t) { - super.postCreate(t); + protected void postCreate(LogEntry t, Http.Request request) { + super.postCreate(t, request); // When user has been created cache.removeByPrefix("activity:criteria:"); } @Override - protected LogEntry postUpdate(LogEntry t) { - super.postUpdate(t); + protected LogEntry postUpdate(LogEntry t, Http.Request request) { + super.postUpdate(t, request); // When user has been updated, the user cache needs to be invalidated cache.removeByPrefix("activity:criteria:"); @@ -131,8 +132,8 @@ protected LogEntry postUpdate(LogEntry t) { * {@inheritDoc} */ @Override - protected void postDelete(LogEntry t) { - super.postDelete(t); + protected void postDelete(LogEntry t, Http.Request request) { + super.postDelete(t, request); // When locale has been deleted, the locale cache needs to be invalidated cache.removeByPrefix("activity:criteria:"); diff --git a/app/services/impl/MessageServiceImpl.java b/app/services/impl/MessageServiceImpl.java index 54033cd8..91c14804 100644 --- a/app/services/impl/MessageServiceImpl.java +++ b/app/services/impl/MessageServiceImpl.java @@ -8,6 +8,7 @@ import models.Project; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import play.mvc.Http; import repositories.MessageRepository; import services.*; @@ -82,22 +83,22 @@ public List latest(Project project, int limit) { } @Override - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { metricService.logEvent(Message.class, ActionType.Read); - return super.postFind(pagedList); + return super.postFind(pagedList, request); } @Override - protected Message postGet(Message message) { + protected Message postGet(Message message, Http.Request request) { metricService.logEvent(Message.class, ActionType.Read); - return super.postGet(message); + return super.postGet(message, request); } @Override - protected void postCreate(Message t) { - super.postCreate(t); + protected void postCreate(Message t, Http.Request request) { + super.postCreate(t, request); metricService.logEvent(Message.class, ActionType.Create); @@ -110,8 +111,8 @@ protected void postCreate(Message t) { } @Override - protected Message postUpdate(Message t) { - super.postUpdate(t); + protected Message postUpdate(Message t, Http.Request request) { + super.postUpdate(t, request); metricService.logEvent(Message.class, ActionType.Update); @@ -124,8 +125,8 @@ protected Message postUpdate(Message t) { } @Override - protected void postDelete(Message t) { - super.postDelete(t); + protected void postDelete(Message t, Http.Request request) { + super.postDelete(t, request); metricService.logEvent(Message.class, ActionType.Delete); } diff --git a/app/services/impl/NoCacheServiceImpl.java b/app/services/impl/NoCacheServiceImpl.java index c6155d5b..add3ff8a 100644 --- a/app/services/impl/NoCacheServiceImpl.java +++ b/app/services/impl/NoCacheServiceImpl.java @@ -31,6 +31,4 @@ public T getOrElseUpdate(String key, Callable block, int expiration) { return null; } } - - } diff --git a/app/services/impl/NotificationServiceImpl.java b/app/services/impl/NotificationServiceImpl.java index 4f4f1f87..f41e56a0 100644 --- a/app/services/impl/NotificationServiceImpl.java +++ b/app/services/impl/NotificationServiceImpl.java @@ -67,7 +67,7 @@ public boolean isEnabled() { public StreamResponse> find(NotificationCriteria criteria) throws IOException, StreamClientException { Feed feed = - streamClient.newFeed(FEED_GROUP_TIMELINE_AGGREGATED, authProvider.loggedInUser().id.toString()); + streamClient.newFeed(FEED_GROUP_TIMELINE_AGGREGATED, authProvider.loggedInUser(criteria.getRequest()).id.toString()); AggregatedActivityServiceImpl activityService = feed.newAggregatedActivityService(SimpleActivity.class); diff --git a/app/services/impl/NotificationSyncImpl.java b/app/services/impl/NotificationSyncImpl.java index 2659bf29..ef2c070a 100644 --- a/app/services/impl/NotificationSyncImpl.java +++ b/app/services/impl/NotificationSyncImpl.java @@ -37,8 +37,8 @@ public NotificationSyncImpl(NotificationService notificationService, private void init() { CompletableFuture.runAsync(() -> { - projectService.findBy(new ProjectCriteria()).getList().stream().forEach(project -> { - project.members.stream().forEach(member -> { + projectService.findBy(new ProjectCriteria()).getList().forEach(project -> { + project.members.forEach(member -> { try { notificationService.follow(member.user.id, project.id); } catch (IOException | StreamClientException e) { diff --git a/app/services/impl/ProjectServiceImpl.java b/app/services/impl/ProjectServiceImpl.java index ab840a18..0ab3bfa4 100644 --- a/app/services/impl/ProjectServiceImpl.java +++ b/app/services/impl/ProjectServiceImpl.java @@ -1,5 +1,6 @@ package services.impl; +import criterias.GetCriteria; import io.ebean.PagedList; import criterias.ProjectCriteria; import models.ActionType; @@ -10,6 +11,7 @@ import models.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import play.mvc.Http; import repositories.MessageRepository; import repositories.ProjectRepository; import services.AuthProvider; @@ -26,6 +28,7 @@ import javax.inject.Singleton; import javax.validation.Validator; import java.util.List; +import java.util.Optional; import java.util.UUID; import static java.util.Objects.requireNonNull; @@ -71,13 +74,13 @@ public ProjectServiceImpl(Validator validator, CacheService cache, * {@inheritDoc} */ @Override - public Project byOwnerAndName(String username, String name, String... fetches) { + public Project byOwnerAndName(String username, String name, Http.Request request, String... fetches) { return log( () -> postGet(cache.getOrElseUpdate( Project.getCacheKey(username, name, fetches), () -> projectRepository.byOwnerAndName(username, name, fetches), 10 * 30 - )), + ), request), LOGGER, "byOwnerAndName" ); @@ -87,13 +90,13 @@ public Project byOwnerAndName(String username, String name, String... fetches) { * {@inheritDoc} */ @Override - public void increaseWordCountBy(UUID projectId, int wordCountDiff) { + public void increaseWordCountBy(UUID projectId, int wordCountDiff, Http.Request request) { if (wordCountDiff == 0) { LOGGER.debug("Not changing word count"); return; } - Project project = byId(projectId); + Project project = byId(GetCriteria.from(projectId, request)); if (project == null) { return; } @@ -110,31 +113,31 @@ public void increaseWordCountBy(UUID projectId, int wordCountDiff) { wordCountDiff ); - postUpdate(project); + postUpdate(project, request); } /** * {@inheritDoc} */ @Override - public void resetWordCount(UUID projectId) { - Project project = byId(projectId, ProjectRepository.FETCH_LOCALES); + public void resetWordCount(UUID projectId, Http.Request request) { + Project project = byId(projectId, request, ProjectRepository.FETCH_LOCALES); List localeIds = project.locales.stream().map(Locale::getId).collect(toList()); project.wordCount = null; modelRepository.save(project); - postUpdate(project); + postUpdate(project, request); localeService.resetWordCount(projectId); keyService.resetWordCount(projectId); messageService.resetWordCount(projectId); - messageService.save(messageRepository.byLocales(localeIds)); + messageService.save(messageRepository.byLocales(localeIds), request); } @Override - public void changeOwner(Project project, User owner) { + public void changeOwner(Project project, User owner, Http.Request request) { LOGGER.debug("changeOwner(project={}, owner={})", project, owner); requireNonNull(project, "project"); @@ -160,30 +163,39 @@ public void changeOwner(Project project, User owner) { project.members.add(newOwnerRole); } - update(project.withOwner(owner)); - projectUserService.update(ownerRole); - projectUserService.update(newOwnerRole); + update(project.withOwner(owner), request); + projectUserService.update(ownerRole, request); + projectUserService.update(newOwnerRole, request); } @Override - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { metricService.logEvent(Project.class, ActionType.Read); - return super.postFind(pagedList); + return super.postFind(pagedList, request); } @Override - protected Project postGet(Project project) { + protected Project postGet(Project project, Http.Request request) { metricService.logEvent(Project.class, ActionType.Read); - return super.postGet(project); + return super.postGet(project, request); } @Override - protected void postCreate(Project t) { - super.postCreate(t); + protected void preCreate(Project t, Http.Request request) { + if (t.owner == null || t.owner.id == null) { + t.owner = authProvider.loggedInUser(request); + } + + super.preCreate(t, request); + } + + @Override + protected void postCreate(Project t, Http.Request request) { + super.postCreate(t, request); - projectUserService.create(new ProjectUser().withProject(t).withUser(t.owner).withRole(ProjectRole.Owner)); + projectUserService.create(new ProjectUser().withProject(t).withUser(t.owner).withRole(ProjectRole.Owner), request); metricService.logEvent(Project.class, ActionType.Create); @@ -192,17 +204,17 @@ protected void postCreate(Project t) { } @Override - protected Project postUpdate(Project t) { + protected Project postUpdate(Project t, Http.Request request) { metricService.logEvent(Project.class, ActionType.Update); // When project has been updated, the project cache needs to be invalidated cache.removeByPrefix("project:criteria:"); - Project cached = cache.get(Project.getCacheKey(t.id)); - if (cached != null) { + Optional cached = cache.get(Project.getCacheKey(t.id)); + if (cached.isPresent()) { cache.removeByPrefix(Project.getCacheKey( - requireNonNull(cached.owner, "owner (cached)").username, - cached.name + requireNonNull(cached.get().owner, "owner (cached)").username, + cached.get().name )); } else { cache.removeByPrefix(Project.getCacheKey( @@ -211,15 +223,15 @@ protected Project postUpdate(Project t) { )); } - return super.postUpdate(t); + return super.postUpdate(t, request); } /** * {@inheritDoc} */ @Override - protected void postDelete(Project t) { - super.postDelete(t); + protected void postDelete(Project t, Http.Request request) { + super.postDelete(t, request); metricService.logEvent(Project.class, ActionType.Delete); diff --git a/app/services/impl/ProjectUserServiceImpl.java b/app/services/impl/ProjectUserServiceImpl.java index 0ea253c5..3d0714d6 100644 --- a/app/services/impl/ProjectUserServiceImpl.java +++ b/app/services/impl/ProjectUserServiceImpl.java @@ -4,6 +4,7 @@ import criterias.ProjectUserCriteria; import models.ActionType; import models.ProjectUser; +import play.mvc.Http; import repositories.ProjectUserRepository; import services.*; @@ -41,22 +42,22 @@ public int countBy(ProjectUserCriteria criteria) { } @Override - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { metricService.logEvent(ProjectUser.class, ActionType.Read); - return super.postFind(pagedList); + return super.postFind(pagedList, request); } @Override - protected ProjectUser postGet(ProjectUser projectUser) { + protected ProjectUser postGet(ProjectUser projectUser, Http.Request request) { metricService.logEvent(ProjectUser.class, ActionType.Read); - return super.postGet(projectUser); + return super.postGet(projectUser, request); } @Override - protected void postCreate(ProjectUser t) { - super.postCreate(t); + protected void postCreate(ProjectUser t, Http.Request request) { + super.postCreate(t, request); metricService.logEvent(ProjectUser.class, ActionType.Create); @@ -64,8 +65,8 @@ protected void postCreate(ProjectUser t) { } @Override - protected ProjectUser postUpdate(ProjectUser t) { - super.postUpdate(t); + protected ProjectUser postUpdate(ProjectUser t, Http.Request request) { + super.postUpdate(t, request); metricService.logEvent(ProjectUser.class, ActionType.Update); @@ -79,8 +80,8 @@ protected ProjectUser postUpdate(ProjectUser t) { * {@inheritDoc} */ @Override - protected void postDelete(ProjectUser t) { - super.postDelete(t); + protected void postDelete(ProjectUser t, Http.Request request) { + super.postDelete(t, request); metricService.logEvent(ProjectUser.class, ActionType.Delete); diff --git a/app/services/impl/UserFeatureFlagServiceImpl.java b/app/services/impl/UserFeatureFlagServiceImpl.java index 29741104..493d3150 100644 --- a/app/services/impl/UserFeatureFlagServiceImpl.java +++ b/app/services/impl/UserFeatureFlagServiceImpl.java @@ -6,6 +6,7 @@ import models.User; import models.UserFeatureFlag; import models.UserRole; +import play.mvc.Http; import repositories.UserFeatureFlagRepository; import services.*; @@ -31,7 +32,7 @@ public UserFeatureFlagServiceImpl( @Override public PagedList findBy(UserFeatureFlagCriteria criteria) { - User loggedInUser = authProvider.loggedInUser(); + User loggedInUser = authProvider.loggedInUser(criteria.getRequest()); if (loggedInUser != null && loggedInUser.role != UserRole.Admin) { criteria.setUserId(loggedInUser.id); } @@ -40,29 +41,29 @@ public PagedList findBy(UserFeatureFlagCriteria criteria) { } @Override - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { metricService.logEvent(UserFeatureFlag.class, ActionType.Read); - return super.postFind(pagedList); + return super.postFind(pagedList, request); } @Override - protected UserFeatureFlag postGet(UserFeatureFlag userFeatureFlag) { + protected UserFeatureFlag postGet(UserFeatureFlag userFeatureFlag, Http.Request request) { metricService.logEvent(UserFeatureFlag.class, ActionType.Read); - return super.postGet(userFeatureFlag); + return super.postGet(userFeatureFlag, request); } @Override - protected void postCreate(UserFeatureFlag t) { - super.postCreate(t); + protected void postCreate(UserFeatureFlag t, Http.Request request) { + super.postCreate(t, request); metricService.logEvent(UserFeatureFlag.class, ActionType.Create); } @Override - protected UserFeatureFlag postUpdate(UserFeatureFlag t) { - super.postUpdate(t); + protected UserFeatureFlag postUpdate(UserFeatureFlag t, Http.Request request) { + super.postUpdate(t, request); metricService.logEvent(UserFeatureFlag.class, ActionType.Update); @@ -70,8 +71,8 @@ protected UserFeatureFlag postUpdate(UserFeatureFlag t) { } @Override - protected void postDelete(UserFeatureFlag t) { - super.postDelete(t); + protected void postDelete(UserFeatureFlag t, Http.Request request) { + super.postDelete(t, request); metricService.logEvent(UserFeatureFlag.class, ActionType.Delete); } diff --git a/app/services/impl/UserServiceImpl.java b/app/services/impl/UserServiceImpl.java index e2c18924..ee4c43a0 100644 --- a/app/services/impl/UserServiceImpl.java +++ b/app/services/impl/UserServiceImpl.java @@ -13,6 +13,7 @@ import models.UserStats; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import play.mvc.Http; import repositories.UserRepository; import services.AccessTokenService; import services.AuthProvider; @@ -30,6 +31,7 @@ import java.util.Arrays; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.UUID; import static java.util.stream.Collectors.toList; @@ -74,25 +76,25 @@ public UserServiceImpl(Validator validator, CacheService cache, UserRepository u * {@inheritDoc} */ @Override - public User merge(final User user, final User otherUser) { + public User merge(final User user, final User otherUser, Http.Request request) { linkedAccountService.save( linkedAccountService.findBy(new LinkedAccountCriteria() .withUserId(Objects.requireNonNull(otherUser, "other user").id)) .getList() .stream() .map(linkedAccount -> linkedAccount.withUser(user)) - .collect(toList()) + .collect(toList()), request ); otherUser.linkedAccounts.clear(); accessTokenService .save(accessTokenService.findBy(new AccessTokenCriteria().withUserId(otherUser.id)) - .getList().stream().map(accessToken -> accessToken.withUser(user)).collect(toList())); + .getList().stream().map(accessToken -> accessToken.withUser(user)).collect(toList()), request); logEntryService .save(logEntryService.findBy(new LogEntryCriteria().withUserId(otherUser.id)).getList() .stream().filter(logEntry -> !logEntry.contentType.equals("User")) - .map(logEntry -> logEntry.withUser(user)).collect(toList())); + .map(logEntry -> logEntry.withUser(user)).collect(toList()), request); projectService .save( @@ -100,15 +102,15 @@ public User merge(final User user, final User otherUser) { .stream() .map(project -> project.withOwner(user) .withName(String.format("%s (%s)", project.name, user.email))) - .collect(toList())); + .collect(toList()), request); projectUserService .save(projectUserService.findBy(new ProjectUserCriteria().withUserId(otherUser.id)) - .getList().stream().map(member -> member.withUser(user)).collect(toList())); + .getList().stream().map(member -> member.withUser(user)).collect(toList()), request); // deactivate the merged user that got added to this one otherUser.active = false; - save(Arrays.asList(otherUser, user)); + save(Arrays.asList(otherUser, user), request); return user; } @@ -117,11 +119,11 @@ public User merge(final User user, final User otherUser) { * {@inheritDoc} */ @Override - public User byUsername(String username, String... fetches) { + public User byUsername(String username, Http.Request request, String... fetches) { return postGet(cache.getOrElseUpdate( User.getCacheKey(username, fetches), () -> userRepository.byUsername(username, fetches), - 60)); + 60), request); } @Override @@ -135,13 +137,13 @@ public User byAccessToken(String accessTokenKey) { } @Override - public User saveSettings(UUID userId, Map settings) { - return postUpdate(userRepository.saveSettings(userId, cleanSettings(settings))); + public User saveSettings(UUID userId, Map settings, Http.Request request) { + return postUpdate(userRepository.saveSettings(userId, cleanSettings(settings)), request); } @Override - public User updateSettings(UUID userId, Map settings) { - return postUpdate(userRepository.updateSettings(userId, cleanSettings(settings))); + public User updateSettings(UUID userId, Map settings, Http.Request request) { + return postUpdate(userRepository.updateSettings(userId, cleanSettings(settings)), request); } private Map cleanSettings(Map settings) { @@ -170,30 +172,28 @@ public UserStats getUserStats(UUID userId) { } @Override - protected PagedList postFind(PagedList pagedList) { + protected PagedList postFind(PagedList pagedList, Http.Request request) { metricService.logEvent(User.class, ActionType.Read); - return super.postFind(pagedList); + return super.postFind(pagedList, request); } @Override - protected User postGet(User user) { + protected User postGet(User user, Http.Request request) { metricService.logEvent(User.class, ActionType.Read); - return super.postGet(user); + return super.postGet(user, request); } @Override - protected void preCreate(User t) { - User cached = cache.get(User.getCacheKey(t.getId())); - if (cached != null) { - cache.removeByPrefix(User.getCacheKey(cached.username)); - } + protected void preCreate(User t, Http.Request request) { + Optional cached = cache.get(User.getCacheKey(t.getId())); + cached.ifPresent(user -> cache.removeByPrefix(User.getCacheKey(user.username))); } @Override - protected void postCreate(User t) { - super.postCreate(t); + protected void postCreate(User t, Http.Request request) { + super.postCreate(t, request); metricService.logEvent(User.class, ActionType.Create); @@ -202,23 +202,23 @@ protected void postCreate(User t) { } @Override - protected User postUpdate(User t) { - super.postUpdate(t); + protected User postUpdate(User t, Http.Request request) { + super.postUpdate(t, request); metricService.logEvent(User.class, ActionType.Update); // When user has been updated, the user cache needs to be invalidated cache.removeByPrefix("user:criteria:"); - return byId(t.id).updateFrom(t); + return byId(t.id, request).updateFrom(t); } /** * {@inheritDoc} */ @Override - protected void postDelete(User t) { - super.postDelete(t); + protected void postDelete(User t, Http.Request request) { + super.postDelete(t, request); metricService.logEvent(User.class, ActionType.Delete); diff --git a/app/utils/ActivityUtils.java b/app/utils/ActivityUtils.java index fe797b23..556ba93d 100644 --- a/app/utils/ActivityUtils.java +++ b/app/utils/ActivityUtils.java @@ -1,18 +1,21 @@ package utils; import com.fasterxml.jackson.databind.JsonNode; -import mappers.*; import models.LogEntry; import play.i18n.Messages; +import play.i18n.MessagesApi; import play.libs.Json; -import play.mvc.Call; -import play.mvc.Http.Context; +import play.mvc.Http; + +import javax.inject.Inject; +import javax.inject.Singleton; /** * * @author resamsel * @version 2 Oct 2016 */ +@Singleton public class ActivityUtils { public static final String PROJECTS_ICON = "dashboard"; public static final String PROJECT_ICON = "view_quilt"; @@ -36,6 +39,12 @@ public class ActivityUtils { public static final String ACCESS_TOKEN_COLOR = "red"; public static final String PROJECT_USER_COLOR = "purple"; public static final String ACTIVITY_COLOR = "green"; + private final MessagesApi messagesApi; + + @Inject + public ActivityUtils(MessagesApi messagesApi) { + this.messagesApi = messagesApi; + } public static String nameOf(LogEntry activity) { if (activity == null) @@ -115,24 +124,22 @@ static String contentTypeOf(LogEntry activity) { return contentType.substring(contentType.lastIndexOf(".") + 1); } - public static String titleOf(LogEntry logEntry) { - Context ctx = Context.current(); - Messages messages = ctx.messages(); + public String titleOf(LogEntry logEntry, Http.Request request) { + Messages messages = messagesApi.preferred(request); return messages.at("activity." + logEntry.type.normalize() + ".title", logEntry.project != null ? logEntry.project.name : "", messages.at("contentType." + logEntry.contentType), ActivityUtils.nameOf(logEntry), - FormatUtils.pretty(ctx.lang().locale(), logEntry.whenCreated), logEntry.user.name, + FormatUtils.pretty(messages.lang().locale(), logEntry.whenCreated), logEntry.user.name, logEntry.user.username, logEntry.user.id); } - public static String infoOf(LogEntry logEntry) { - Context ctx = Context.current(); - Messages messages = ctx.messages(); + public String infoOf(LogEntry logEntry, Http.Request request) { + Messages messages = messagesApi.preferred(request); return messages.at("activity." + logEntry.type.normalize() + ".info", messages.at("contentType." + logEntry.contentType), - FormatUtils.pretty(ctx.lang().locale(), logEntry.whenCreated)); + FormatUtils.pretty(messages.lang().locale(), logEntry.whenCreated)); } public static JsonNode parse(LogEntry activity) { diff --git a/app/utils/FormUtils.java b/app/utils/FormUtils.java index bc6c2b9a..2a2db7bc 100644 --- a/app/utils/FormUtils.java +++ b/app/utils/FormUtils.java @@ -11,6 +11,7 @@ import play.data.Form; import play.data.FormFactory; import play.data.validation.ValidationError; +import play.mvc.Http; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; @@ -21,8 +22,8 @@ */ public class FormUtils { - protected static Form bindFromRequest(FormFactory formFactory, Class formClass) { - return formFactory.form(formClass).bindFromRequest(); + protected static Form bindFromRequest(FormFactory formFactory, Class formClass, Http.Request request) { + return formFactory.form(formClass).bindFromRequest(request); } public static Form include(Form form, Throwable t) { @@ -48,8 +49,9 @@ private static String pathFrom(ConstraintViolation violation) { public static class Search { public static Form bindFromRequest(FormFactory formFactory, - Config configuration) { - return init(FormUtils.bindFromRequest(formFactory, SearchForm.class), configuration); + Config configuration, + Http.Request request) { + return init(FormUtils.bindFromRequest(formFactory, SearchForm.class, request), configuration); } protected static Form init(Form form, @@ -64,75 +66,4 @@ protected static Form init(Form form, } } - public static class LocaleSearch { - - public static Form bindFromRequest(FormFactory formFactory, - Config configuration) { - return init(FormUtils.bindFromRequest(formFactory, LocaleSearchForm.class), configuration); - } - - protected static Form init(Form form, - Config configuration) { - LocaleSearchForm obj = form.get(); - - if (obj.missing == null) { - obj.missing = configuration.getBoolean("translatr.search.missing"); - } - - return Search.init(form, configuration); - } - } - - public static class Locale { - - public static Form bindFromRequest(FormFactory formFactory, - Config configuration) { - return Search.init(FormUtils.bindFromRequest(formFactory, LocaleForm.class), configuration); - } - } - - public static class KeySearch { - - public static Form bindFromRequest(FormFactory formFactory, - Config configuration) { - return init(FormUtils.bindFromRequest(formFactory, KeySearchForm.class), configuration); - } - - protected static Form init(Form form, - Config configuration) { - KeySearchForm obj = form.get(); - - if (obj.missing == null) { - obj.missing = configuration.getBoolean("translatr.search.missing"); - } - - return Search.init(form, configuration); - } - } - - public static class Key { - - public static Form bindFromRequest(FormFactory formFactory, - Config configuration) { - return Search.init(FormUtils.bindFromRequest(formFactory, KeyForm.class), configuration); - } - } - - public static class ActivitySearch { - - public static Form bindFromRequest(FormFactory formFactory, - Config configuration) { - return Search.init(FormUtils.bindFromRequest(formFactory, ActivitySearchForm.class), - configuration); - } - } - - public static class AccessToken { - - public static Form bindFromRequest(FormFactory formFactory, - Config configuration) { - return Search.init(FormUtils.bindFromRequest(formFactory, AccessTokenForm.class), - configuration); - } - } } diff --git a/app/utils/FormatUtils.java b/app/utils/FormatUtils.java index d82aa94f..7d753f90 100644 --- a/app/utils/FormatUtils.java +++ b/app/utils/FormatUtils.java @@ -4,24 +4,31 @@ import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.ocpsoft.prettytime.PrettyTime; +import play.i18n.Messages; +import play.i18n.MessagesApi; import play.mvc.Http; -import java.util.HashMap; -import java.util.Map; +import javax.inject.Inject; +import javax.inject.Singleton; +@Singleton public class FormatUtils { + private final MessagesApi messagesApi; - private static final Map CONTEXT_LOCALE_MAP = new HashMap<>(); + @Inject + public FormatUtils(MessagesApi messagesApi) { + this.messagesApi = messagesApi; + } - public static final String pretty(java.util.Locale locale, DateTime dateTime) { + public static String pretty(java.util.Locale locale, DateTime dateTime) { return new PrettyTime(locale).format(dateTime.toDate()); } - public static final String formatLocale(java.util.Locale userLocale, Locale locale) { + public static String formatLocale(java.util.Locale userLocale, Locale locale) { return formatLocale(userLocale, locale.name); } - public static final String formatLocale(java.util.Locale userLocale, String localeName) { + public static String formatLocale(java.util.Locale userLocale, String localeName) { java.util.Locale locale = java.util.Locale.forLanguageTag(localeName.replaceAll("_", "-")); if (locale.getDisplayName(userLocale).equalsIgnoreCase(localeName)) { @@ -31,20 +38,18 @@ public static final String formatLocale(java.util.Locale userLocale, String loca return String.format("%s — %s", localeName, locale.getDisplayName(userLocale)); } - public static String formatDisplayName(Locale locale) { + public String formatDisplayName(Locale locale, Http.Request request) { if (StringUtils.isEmpty(locale.name)) { return null; } java.util.Locale l = java.util.Locale.forLanguageTag(locale.name); - - Http.Context ctx = Http.Context.current.get(); - if (ctx == null) { + if (request == null) { return l.getDisplayName(); } - java.util.Locale ctxLocale = CONTEXT_LOCALE_MAP - .computeIfAbsent(ctx, context -> context.lang().locale()); + Messages messages = messagesApi.preferred(request); + java.util.Locale ctxLocale = messages.lang().locale(); return l.getDisplayName(ctxLocale); } diff --git a/app/validators/AccessTokenByUserAndNameValidator.java b/app/validators/AccessTokenByUserAndNameValidator.java index a78738ca..f21e1c8f 100644 --- a/app/validators/AccessTokenByUserAndNameValidator.java +++ b/app/validators/AccessTokenByUserAndNameValidator.java @@ -40,7 +40,7 @@ public void initialize(AccessTokenByUserAndName constraintAnnotation) { @Override public boolean isValid(Object object) { return object != null && object instanceof String - && accessTokenRepository.byUserAndName(authProvider.loggedInUserId(), (String) object) == null; + && accessTokenRepository.byUserAndName(authProvider.loggedInUserId(null) /* FIXME: will fail! */, (String) object) == null; } /** diff --git a/app/validators/NameUniqueValidator.java b/app/validators/NameUniqueValidator.java index a3321f8a..42024575 100644 --- a/app/validators/NameUniqueValidator.java +++ b/app/validators/NameUniqueValidator.java @@ -1,14 +1,10 @@ package validators; -import play.i18n.Lang; -import play.i18n.MessagesApi; import play.inject.Injector; -import play.mvc.Http; import javax.inject.Inject; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -import java.util.Locale; /** * @author resamsel @@ -22,8 +18,6 @@ public class NameUniqueValidator implements ConstraintValidator !Objects.equals(member.id, value.id) && member.role == ProjectRole.Owner)) { context.disableDefaultConstraintViolation(); - context.buildConstraintViolationWithTemplate(messagesApi.get(lang, constraintAnnotation.message())) + context.buildConstraintViolationWithTemplate(constraintAnnotation.message()) .addPropertyNode("role") .addConstraintViolation(); return false; diff --git a/app/validators/UserByUsernameValidator.java b/app/validators/UserByUsernameValidator.java index 175c07d0..05f4d391 100644 --- a/app/validators/UserByUsernameValidator.java +++ b/app/validators/UserByUsernameValidator.java @@ -36,7 +36,7 @@ public void initialize(UserByUsername constraintAnnotation) { @Override public boolean isValid(Object object) { return object != null && object instanceof String - && userService.byUsername((String) object) != null; + && userService.byUsername((String) object, null /* FIXME */) != null; } /** diff --git a/build.sbt b/build.sbt index e2e0dd35..75a77245 100644 --- a/build.sbt +++ b/build.sbt @@ -5,63 +5,71 @@ name := """translatr""" version := "3.0.3" lazy val root = (project in file(".")) - .configs(IntegrationTest) - .enablePlugins(PlayJava, PlayEbean, BuildInfoPlugin) - .settings( - Defaults.itSettings, - buildInfoKeys := Seq[BuildInfoKey](name, version) - ) - -scalaVersion := "2.12.11" + .configs(IntegrationTest) + .enablePlugins(PlayJava, PlayEbean, BuildInfoPlugin) + .settings( + scalaVersion := "2.13.2", + Defaults.itSettings, + buildInfoKeys := Seq[BuildInfoKey](name, version) + ) libraryDependencies ++= Seq( - javaJdbc, + javaJdbc, + + guice, - guice, + "com.typesafe.play" %% "play-json" % "2.8.1", + // https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-joda + "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.10.5", - "com.typesafe.play" %% "play-json" % "2.6.14", - "com.fasterxml.jackson.datatype" % "jackson-datatype-joda" % "2.11.2", - ehcache, -// "com.typesafe.play.modules" %% "play-modules-redis" % "2.6.0", + ehcache, + // "com.typesafe.play.modules" %% "play-modules-redis" % "2.6.0", - // Database - "org.postgresql" % "postgresql" % "42.1.3", + // Database + "org.postgresql" % "postgresql" % "42.1.3", - // OAuth for Play - "org.pac4j" %% "play-pac4j" % "10.0.1", - "org.pac4j" % "pac4j-http" % "4.0.3", - "org.pac4j" % "pac4j-oauth" % "4.0.3", - "org.pac4j" % "pac4j-oidc" % "4.0.3" exclude("commons-io" , "commons-io"), - "org.pac4j" % "pac4j-sql" % "4.0.3", - "be.objectify" %% "deadbolt-java" % "2.7.1", - // https://mvnrepository.com/artifact/org.apache.shiro/shiro-core - "org.apache.shiro" % "shiro-core" % "1.5.3", + // OAuth for Play + "org.pac4j" %% "play-pac4j" % "10.0.1", + "org.pac4j" % "pac4j-http" % "4.0.3", + "org.pac4j" % "pac4j-oauth" % "4.0.3", + "org.pac4j" % "pac4j-oidc" % "4.0.3" exclude("commons-io", "commons-io"), + "org.pac4j" % "pac4j-sql" % "4.0.3", + "be.objectify" %% "deadbolt-java" % "2.8.1", + // https://mvnrepository.com/artifact/org.apache.shiro/shiro-core + "org.apache.shiro" % "shiro-core" % "1.5.3", - // Apache Commons IO - "commons-io" % "commons-io" % "2.7", + // Apache Commons IO + "commons-io" % "commons-io" % "2.7", + // https://mvnrepository.com/artifact/org.apache.commons/commons-text + "org.apache.commons" % "commons-text" % "1.9", - // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient - "org.apache.httpcomponents" % "httpclient" % "4.5.3", + // https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient + "org.apache.httpcomponents" % "httpclient" % "4.5.3", - // https://mvnrepository.com/artifact/io.getstream.client/stream-repo-apache - "io.getstream.client" % "stream-repo-apache" % "1.3.0", + // https://mvnrepository.com/artifact/io.getstream.client/stream-repo-apache + "io.getstream.client" % "stream-repo-apache" % "1.3.0", - // https://mvnrepository.com/artifact/org.jsoup/jsoup - "org.jsoup" % "jsoup" % "1.10.3", + // https://mvnrepository.com/artifact/org.jsoup/jsoup + "org.jsoup" % "jsoup" % "1.10.3", - "io.prometheus" % "simpleclient_common" % "0.8.1", - "io.prometheus" % "simpleclient_hotspot" % "0.8.1", + "io.prometheus" % "simpleclient_common" % "0.8.1", + "io.prometheus" % "simpleclient_hotspot" % "0.8.1", - "org.ocpsoft.prettytime" % "prettytime" % "4.0.1.Final", + "org.ocpsoft.prettytime" % "prettytime" % "4.0.1.Final", - // https://mvnrepository.com/artifact/io.swagger/swagger-play2 - "io.swagger" %% "swagger-play2" % "1.7.1", -// "org.webjars" % "swagger-ui" % "2.2.10", + // https://mvnrepository.com/artifact/io.swagger.core.v3/swagger-annotations + "io.swagger.core.v3" % "swagger-annotations" % "2.1.4", + + "com.typesafe.play" %% "play-test" % play.core.PlayVersion.current % "it", + "org.assertj" % "assertj-core" % "3.15.0" % "it,test", + "org.mockito" % "mockito-core" % "2.8.47" % "it,test" +) - "com.typesafe.play" %% "play-test" % play.core.PlayVersion.current % "it", - "org.assertj" % "assertj-core" % "3.15.0" % "it,test", - "org.mockito" % "mockito-core" % "2.8.47" % "it,test" +dependencyOverrides ++= Seq( + // INFO: Necessary because: Scala module 2.10.3 requires Jackson Databind version >= 2.10.0 and < 2.11.0 + // https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind + "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.5", ) // re-create maven directory structure @@ -88,37 +96,37 @@ dockerExposedVolumes := Seq("/opt/docker/logs", "/opt/docker/data") // Concat // Concat.groups := Seq( - "styles.css" -> group(Seq( - "stylesheets/materialize.min.css", - "stylesheets/nprogress.css", - "stylesheets/font-awesome.min.css", - "stylesheets/d3.v3.css", - "stylesheets/codemirror.css", - "stylesheets/codemirror.translatr.css", - "stylesheets/main.css", - "stylesheets/editor.css", - "stylesheets/template.css", - "stylesheets/media.css" - )), - "scripts.js" -> group(Seq( - "javascripts/jquery.min.js", - "javascripts/jquery.ba-bbq.min.js", - "javascripts/materialize.min.js", - "javascripts/jquery.autocomplete.min.js", - "javascripts/d3.v3.min.js", - "javascripts/moment.min.js", - "javascripts/nprogress.js", - "javascripts/codemirror.js", - "javascripts/codemirror.xml.js", - "javascripts/underscore-min.js", - "javascripts/backbone-min.js", - "javascripts/backbone.undo.js", - "javascripts/backbone-pageable.min.js", - "javascripts/app.js", - "javascripts/main.js", - "javascripts/notification.js", - "javascripts/editor.js" - )) + "styles.css" -> group(Seq( + "stylesheets/materialize.min.css", + "stylesheets/nprogress.css", + "stylesheets/font-awesome.min.css", + "stylesheets/d3.v3.css", + "stylesheets/codemirror.css", + "stylesheets/codemirror.translatr.css", + "stylesheets/main.css", + "stylesheets/editor.css", + "stylesheets/template.css", + "stylesheets/media.css" + )), + "scripts.js" -> group(Seq( + "javascripts/jquery.min.js", + "javascripts/jquery.ba-bbq.min.js", + "javascripts/materialize.min.js", + "javascripts/jquery.autocomplete.min.js", + "javascripts/d3.v3.min.js", + "javascripts/moment.min.js", + "javascripts/nprogress.js", + "javascripts/codemirror.js", + "javascripts/codemirror.xml.js", + "javascripts/underscore-min.js", + "javascripts/backbone-min.js", + "javascripts/backbone.undo.js", + "javascripts/backbone-pageable.min.js", + "javascripts/app.js", + "javascripts/main.js", + "javascripts/notification.js", + "javascripts/editor.js" + )) ) // Put everything into the concat dir diff --git a/project/plugins.sbt b/project/plugins.sbt index a727169e..6d82e5cc 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -3,7 +3,7 @@ resolvers += "sonatype-releases" at "https://oss.sonatype.org/content/repositori resolvers += Classpaths.sbtPluginReleases // The Play plugin -addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.5") +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.8.2") // Web plugins addSbtPlugin("net.ground5hark.sbt" % "sbt-concat" % "0.2.0") @@ -17,3 +17,5 @@ addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.2.2") // Play Ebean support, to enable, uncomment this line, and enable in your build.sbt using // enablePlugins(PlayEbean). addSbtPlugin("com.typesafe.sbt" % "sbt-play-ebean" % "5.0.2") + +addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.10.0-RC1") diff --git a/src/it/java/controllers/LocalesApiTest.java b/src/it/java/controllers/LocalesApiTest.java index fecbcd6f..398e8d76 100644 --- a/src/it/java/controllers/LocalesApiTest.java +++ b/src/it/java/controllers/LocalesApiTest.java @@ -97,7 +97,7 @@ protected Binding[] createBindings() { withSettings().invocationListeners(i -> LOGGER.debug("{}", i.getInvocation())) ); - when(accessTokenService.byKey(eq(accessToken.key))).thenReturn(accessToken); + when(accessTokenService.byKey(eq(accessToken.key), any())).thenReturn(accessToken); when(projectUserService.findBy(any())) .thenReturn(PagedListFactory.create(project1.members)); when(localeApiService @@ -105,7 +105,7 @@ protected Binding[] createBindings() { .thenReturn(LocaleMapper.toDto(locale)); when(localeApiService.byOwnerAndProjectAndName(request, eq("a"), eq("b"), eq("c"))) .thenThrow(new NotFoundException(dto.Locale.class.getName(), "c")); - when(localeApiService.download(request, eq(locale.id), eq("java_properties"), any())) + when(localeApiService.download(request, eq(locale.id), eq("java_properties"))) .thenReturn("".getBytes()); //noinspection unchecked diff --git a/src/test/java/services/KeyServiceTest.java b/src/test/java/services/KeyServiceTest.java index 81a097b4..4b2cc432 100644 --- a/src/test/java/services/KeyServiceTest.java +++ b/src/test/java/services/KeyServiceTest.java @@ -104,11 +104,11 @@ public void testByProjectAndName() { keyRepository.create(key); // This invocation should feed the cache - assertThat(target.byProjectAndName(key.project, key.name)).nameIsEqualTo("a"); + assertThat(target.byProjectAndName(key.project, key.name, request)).nameIsEqualTo("a"); verify(keyRepository, times(1)).byProjectAndName(eq(key.project), eq(key.name)); // This invocation should use the cache, not the repository - assertThat(target.byProjectAndName(key.project, key.name)).nameIsEqualTo("a"); + assertThat(target.byProjectAndName(key.project, key.name, request)).nameIsEqualTo("a"); verify(keyRepository, times(1)).byProjectAndName(eq(key.project), eq(key.name)); // This should trigger cache invalidation @@ -117,7 +117,7 @@ public void testByProjectAndName() { assertThat(cacheService.keys().keySet()) .doesNotContain("key:project:" + key.project.id + ":name:a"); - assertThat(target.byProjectAndName(key.project, key.name)).nameIsEqualTo("ab"); + assertThat(target.byProjectAndName(key.project, key.name, request)).nameIsEqualTo("ab"); verify(keyRepository, times(1)).byProjectAndName(eq(key.project), eq(key.name)); } diff --git a/src/test/java/services/UserServiceTest.java b/src/test/java/services/UserServiceTest.java index 5070193d..b6a28a34 100644 --- a/src/test/java/services/UserServiceTest.java +++ b/src/test/java/services/UserServiceTest.java @@ -95,7 +95,7 @@ public void testMerge() { userRepository.create(user); userRepository.create(otherUser); - target.merge(user, otherUser); + target.merge(user, otherUser, request); assertThat(userRepository.byId(user.id)).nameIsEqualTo("a").activeIsTrue(); assertThat(userRepository.byId(otherUser.id)).nameIsEqualTo("b").activeIsFalse(); diff --git a/src/test/java/utils/ActivityUtilsTest.java b/src/test/java/utils/ActivityUtilsTest.java index 23dee3d2..2182a6d7 100644 --- a/src/test/java/utils/ActivityUtilsTest.java +++ b/src/test/java/utils/ActivityUtilsTest.java @@ -13,7 +13,7 @@ public class ActivityUtilsTest { @Test public void instanceOf() { - assertThat(new ActivityUtils()).isNotNull(); + assertThat(new ActivityUtils(null)).isNotNull(); } @Test diff --git a/src/test/java/utils/FormatUtilsTest.java b/src/test/java/utils/FormatUtilsTest.java index 6de4f9de..43f29802 100644 --- a/src/test/java/utils/FormatUtilsTest.java +++ b/src/test/java/utils/FormatUtilsTest.java @@ -1,32 +1,49 @@ package utils; import models.Locale; +import org.junit.Before; import org.junit.Test; +import org.mockito.Mockito; +import play.i18n.MessagesApi; +import play.mvc.Http; import tests.AbstractLocaleTest; import static org.assertj.core.api.Assertions.assertThat; -import static utils.FormatUtils.formatDisplayName; public class FormatUtilsTest extends AbstractLocaleTest { + private FormatUtils formatUtils; + private MessagesApi messagesApi; + + @Before + public void setUp() { + messagesApi = Mockito.mock(MessagesApi.class); + formatUtils = new FormatUtils(messagesApi); + } @Test public void testFormatEnglishDisplayNames() { + // given + Http.Request request = Mockito.mock(Http.Request.class); + java.util.Locale.setDefault(java.util.Locale.forLanguageTag("en")); - assertThat(formatDisplayName(createLocale(null))).isNull(); - assertThat(formatDisplayName(createLocale(""))).isNull(); - assertThat(formatDisplayName(createLocale("de"))).isEqualTo("German"); - assertThat(formatDisplayName(createLocale("en"))).isEqualTo("English"); + assertThat(formatUtils.formatDisplayName(createLocale(null), request)).isNull(); + assertThat(formatUtils.formatDisplayName(createLocale(""), request)).isNull(); + assertThat(formatUtils.formatDisplayName(createLocale("de"), request)).isEqualTo("German"); + assertThat(formatUtils.formatDisplayName(createLocale("en"), request)).isEqualTo("English"); } @Test public void testFormatGermanDisplayNames() { + // given + Http.Request request = Mockito.mock(Http.Request.class); java.util.Locale.setDefault(java.util.Locale.forLanguageTag("de")); - assertThat(formatDisplayName(createLocale(null))).isNull(); - assertThat(formatDisplayName(createLocale(""))).isNull(); - assertThat(formatDisplayName(createLocale("de"))).isEqualTo("Deutsch"); - assertThat(formatDisplayName(createLocale("en"))).isEqualTo("Englisch"); + // when, then + assertThat(formatUtils.formatDisplayName(createLocale(null), request)).isNull(); + assertThat(formatUtils.formatDisplayName(createLocale(""), request)).isNull(); + assertThat(formatUtils.formatDisplayName(createLocale("de"), request)).isEqualTo("Deutsch"); + assertThat(formatUtils.formatDisplayName(createLocale("en"), request)).isEqualTo("Englisch"); } private Locale createLocale(String name) {