Skip to content

Commit

Permalink
Merge Space Settings Review - Meeds-io/MIPs#147 (#168)
Browse files Browse the repository at this point in the history
  • Loading branch information
boubaker authored Sep 26, 2024
2 parents b8d5da9 + 3ff7c73 commit 3bf8d06
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 55 deletions.
96 changes: 45 additions & 51 deletions poll-services/src/main/java/io/meeds/poll/rest/PollRest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,17 @@
*/
package io.meeds.poll.rest;

import java.util.ArrayList;
import static io.meeds.poll.utils.RestEntityBuilder.fromPoll;

import java.util.List;

import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -38,6 +39,7 @@
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import org.exoplatform.common.http.HTTPStatus;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.security.ConversationState;
Expand All @@ -46,7 +48,6 @@
import io.meeds.poll.model.Poll;
import io.meeds.poll.model.PollOption;
import io.meeds.poll.model.PollVote;
import io.meeds.poll.rest.model.PollOptionRestEntity;
import io.meeds.poll.rest.model.PollRestEntity;
import io.meeds.poll.service.PollService;
import io.meeds.poll.utils.RestEntityBuilder;
Expand All @@ -72,34 +73,38 @@ public class PollRest extends Application {
@Operation(summary = "Create a new poll", method = "POST", description = "Create a new poll")
@ApiResponses(value = { @ApiResponse(responseCode = "401", description = "Unauthorized operation"),
@ApiResponse(responseCode = "50", description = "Internal server error"), })
public Response createPoll(
@Parameter(description = "space identifier")
@RequestParam("spaceId")
String spaceId,
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "Poll object to create", required = true)
@RequestBody
PollRestEntity pollRestEntity) {
public ResponseEntity<PollRestEntity> createPoll(
@Parameter(description = "space identifier")
@RequestParam("spaceId")
String spaceId,
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "Poll object to create",
required = true)
@RequestBody
PollRestEntity pollRestEntity) {
if (pollRestEntity == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
return ResponseEntity.badRequest().build();
}
Identity currentIdentity = ConversationState.getCurrent().getIdentity();
try {
Poll poll = RestEntityBuilder.toPoll(pollRestEntity);
List<PollOption> pollOptions = RestEntityBuilder.toPollOptions(pollRestEntity.getOptions());
poll = pollService.createPoll(poll, pollOptions, spaceId, pollRestEntity.getMessage(), currentIdentity, pollRestEntity.getFiles());
return Response.ok(poll).build();
poll = pollService.createPoll(poll,
pollOptions,
spaceId,
pollRestEntity.getMessage(),
currentIdentity,
pollRestEntity.getFiles());
return ResponseEntity.ok(fromPoll(pollService, poll, currentIdentity));
} catch (IllegalAccessException e) {
LOG.warn("User '{}' attempts to create a non authorized poll", currentIdentity.getUserId(), e);
return Response.status(Response.Status.UNAUTHORIZED).build();
} catch (Exception e) {
LOG.error("Error when creating a poll ", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
return ResponseEntity.status(HTTPStatus.UNAUTHORIZED).build();
}
}

@GetMapping(path = "{id}", produces = MediaType.APPLICATION_JSON)
@Secured("users")
@Operation(summary = "Get a poll", method = "GET", description = "This gets the poll with the given id if the authenticated user is a member of the space.")
@Operation(summary = "Get a poll", method = "GET",
description = "This gets the poll with the given id if the authenticated user is a member of the space.")
@ApiResponses(value = { @ApiResponse(responseCode = "400", description = "Invalid query input"),
@ApiResponse(responseCode = "404", description = "Poll not found"),
@ApiResponse(responseCode = "401", description = "Unauthorized operation"),
Expand All @@ -115,60 +120,49 @@ public ResponseEntity<PollRestEntity> getPollById(
}
Poll poll = pollService.getPollById(Long.parseLong(pollId), currentIdentity);
if (poll == null) {
return ResponseEntity.badRequest().build();
return ResponseEntity.notFound().build();
} else {
PollRestEntity pollRestEntity = fromPoll(pollService, poll, currentIdentity);
return ResponseEntity.ok(pollRestEntity);
}
List<PollOption> pollOptions = pollService.getPollOptionsByPollId(Long.parseLong(pollId), currentIdentity);
List<PollOptionRestEntity> pollOptionRestEntities = new ArrayList<>();
for (PollOption pollOption : pollOptions) {
int pollOptionVotes = pollService.getPollOptionTotalVotes(pollOption.getId(), String.valueOf(poll.getSpaceId()), currentIdentity);
boolean isPollOptionVoted = pollService.isPollOptionVoted(pollOption.getId(), String.valueOf(poll.getSpaceId()), currentIdentity);
PollOptionRestEntity pollOptionRestEntity = RestEntityBuilder.fromPollOption(pollOption, pollOptionVotes, isPollOptionVoted);
pollOptionRestEntities.add(pollOptionRestEntity);
}
PollRestEntity pollRestEntity = RestEntityBuilder.fromPoll(poll, pollOptionRestEntities);
return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(pollRestEntity);
} catch (IllegalAccessException e) {
LOG.warn("User '{}' attempts to get a non authorized poll with id {}", currentIdentity.getUserId(), pollId, e);
return ResponseEntity.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (Exception e) {
LOG.error("Error when getting a poll by id {} ", pollId, e);
return ResponseEntity.internalServerError().build();
return ResponseEntity.status(HTTPStatus.UNAUTHORIZED).build();
}
}

@PostMapping(path="/vote/{optionId}", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON)
@PostMapping(path = "/vote/{optionId}", consumes = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON)
@Secured("users")
@Operation(summary = "Vote in a poll", method = "POST", description = "Vote in a poll")
@ApiResponses(value = { @ApiResponse(responseCode = "400", description = "Invalid query input"),
@ApiResponse(responseCode = "404", description = "Poll option not found"),
@ApiResponse(responseCode = "401", description = "Unauthorized operation"),
@ApiResponse(responseCode = "500", description = "Internal server error"), })
public Response vote(
@Parameter(description = "Poll option id", required = true)
@PathVariable("optionId")
String optionId) {
public ResponseEntity<PollVote> vote(
@Parameter(description = "Poll option id", required = true)
@PathVariable("optionId")
String optionId) {
Identity currentIdentity = ConversationState.getCurrent().getIdentity();
try {
PollOption pollOption = pollService.getPollOptionById(Long.parseLong(optionId), currentIdentity);
if (pollOption == null) {
return Response.status(Response.Status.NOT_FOUND).build();
return ResponseEntity.notFound().build();
}
Poll poll = pollService.getPollById(pollOption.getPollId(), currentIdentity);
if (poll == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
if(pollService.didVote(currentIdentity, pollOption.getPollId())) {
return Response.status(Response.Status.FORBIDDEN).entity("User did already vote an option in this poll").build();
return ResponseEntity.notFound().build();
} else if (pollService.didVote(currentIdentity, pollOption.getPollId())) {
return ResponseEntity.of(ProblemDetail.forStatusAndDetail(HttpStatus.FORBIDDEN,
"User did already vote an option in this poll"))
.build();
} else {
PollVote pollVote = pollService.vote(optionId, String.valueOf(poll.getSpaceId()), currentIdentity);
return ResponseEntity.ok(pollVote);
}
PollVote pollVote = pollService.vote(optionId, String.valueOf(poll.getSpaceId()), currentIdentity);
return Response.ok(pollVote).build();
} catch (IllegalAccessException e) {
LOG.warn("User '{}' attempts to vote in a non authorized poll option with id {}", currentIdentity.getUserId(), optionId, e);
return Response.status(Response.Status.UNAUTHORIZED).build();
} catch (Exception e) {
LOG.error("Error when voting in the poll option id {}", optionId, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
return ResponseEntity.status(HTTPStatus.UNAUTHORIZED).build();
}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,20 @@

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.exoplatform.commons.utils.CommonsUtils;
import org.exoplatform.services.security.Identity;
import org.exoplatform.social.core.manager.IdentityManager;

import io.meeds.poll.model.Poll;
import io.meeds.poll.model.PollOption;
import io.meeds.poll.rest.model.PollOptionRestEntity;
import io.meeds.poll.rest.model.PollRestEntity;
import io.meeds.poll.service.PollService;

public class RestEntityBuilder {

Expand All @@ -44,7 +47,27 @@ public class RestEntityBuilder {

private RestEntityBuilder() {
}


public static PollRestEntity fromPoll(PollService pollService,
Poll poll,
Identity currentUserIdentity) throws IllegalAccessException {
List<PollOption> pollOptions = pollService.getPollOptionsByPollId(poll.getId(), currentUserIdentity);
List<PollOptionRestEntity> pollOptionRestEntities = new ArrayList<>();
for (PollOption pollOption : pollOptions) {
int pollOptionVotes = pollService.getPollOptionTotalVotes(pollOption.getId(),
String.valueOf(poll.getSpaceId()),
currentUserIdentity);
boolean isPollOptionVoted = pollService.isPollOptionVoted(pollOption.getId(),
String.valueOf(poll.getSpaceId()),
currentUserIdentity);
PollOptionRestEntity pollOptionRestEntity = fromPollOption(pollOption,
pollOptionVotes,
isPollOptionVoted);
pollOptionRestEntities.add(pollOptionRestEntity);
}
return fromPoll(poll, pollOptionRestEntities);
}

public static final PollRestEntity fromPoll(Poll poll,
List<PollOptionRestEntity> pollOptionRestEntities) {
PollRestEntity pollRestEntity = new PollRestEntity();
Expand Down Expand Up @@ -100,6 +123,6 @@ public static final List<PollOption> toPollOptions(List<PollOptionRestEntity> po
PollOption pollOption = new PollOption();
pollOption.setDescription(pollOptionEntity.getDescription());
return pollOption;
}).collect(Collectors.toList());
}).toList();
}
}
3 changes: 1 addition & 2 deletions poll-webapp/src/main/java/io/meeds/poll/PollApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@
AvailableIntegration.KERNEL_MODULE,
AvailableIntegration.JPA_MODULE,
AvailableIntegration.LIQUIBASE_MODULE,
AvailableIntegration.WEB_SECURITY_MODULE,
AvailableIntegration.WEB_TRANSACTION_MODULE,
AvailableIntegration.WEB_MODULE,
})
@EnableJpaRepositories(basePackages = PollApplication.MODULE_NAME)
@PropertySource("classpath:application.properties")
Expand Down

0 comments on commit 3bf8d06

Please sign in to comment.