Skip to content

Finished lab #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ public Iterable<Vote> getVote(@PathVariable Long pollId) {

* The final piece remaining for us is the implementation of the ComputeResult resource.
* Because we don’t have any domain objects that can directly help generate this resource representation, we implement two Data Transfer Objects or DTOs—OptionCount and VoteResult
* Create a sub package of `java` named `dtos`
* Create a sub package of `java` named `dto`


## Part 4.1 - Create class `OptionCount`
Expand Down
22 changes: 22 additions & 0 deletions src/main/java/dto/OptionCount.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package dto;

public class OptionCount {
private Long optionId;
private int count;

public Long getOptionId() {
return optionId;
}

public void setOptionId(Long optionId) {
this.optionId = optionId;
}

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}
}
24 changes: 24 additions & 0 deletions src/main/java/dto/VoteResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package dto;

import java.util.Collection;

public class VoteResult {
private int totalVotes;
private Collection<OptionCount> results;

public int getTotalVotes() {
return totalVotes;
}

public void setTotalVotes(int totalVotes) {
this.totalVotes = totalVotes;
}

public Collection<OptionCount> getResults() {
return results;
}

public void setResults(Collection<OptionCount> results) {
this.results = results;
}
}
62 changes: 62 additions & 0 deletions src/main/java/dto/error/ErrorDetail.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package dto.error;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ErrorDetail {
private String title;
private int status;
private String detail;
private long timeStamp;
private String developerMessage;
private Map<String, List<ValidationError>> errors = new HashMap<>();

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public int getStatus() {
return status;
}

public void setStatus(int status) {
this.status = status;
}

public String getDetail() {
return detail;
}

public void setDetail(String detail) {
this.detail = detail;
}

public long getTimeStamp() {
return timeStamp;
}

public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}

public String getDeveloperMessage() {
return developerMessage;
}

public void setDeveloperMessage(String developerMessage) {
this.developerMessage = developerMessage;
}

public Map<String, List<ValidationError>> getErrors() {
return errors;
}

public void setErrors(Map<String, List<ValidationError>> errors) {
this.errors = errors;
}
}
73 changes: 73 additions & 0 deletions src/main/java/dto/error/RestExceptionHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package dto.error;

import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@Inject
private MessageSource messageSource;
private Object HttpStatus;

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus
public ResponseEntity<?> handlerResourceNotFoundException(
ResourceNotFoundException rnfe, HttpServletRequest request) {
ErrorDetail errorDetail = new ErrorDetail();
errorDetail.setTimeStamp(new Date().getTime());
errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
errorDetail.setTitle("Resource Not Found");
errorDetail.setDetail(rnfe.getMessage());
errorDetail.setDeveloperMessage(rnfe.getClass().getName());

return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND);
}

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody
ErrorDetail handleValidationError(MethodArgumentNotValidException manve, HttpServletRequest request) {
ErrorDetail errorDetail = new ErrorDetail();
errorDetail.setTitle("Validation Failed");
errorDetail.setStatus(HttpStatus.BAD_REQUEST.value());
errorDetail.setDetail("Input validation failed");
errorDetail.setTimeStamp(new Date().getTime());
errorDetail.setDeveloperMessage(manve.getClass().getName());

String requestPath = (String) request.getAttribute("javax.servlet.error.request_uri");

if (requestPath == null) {
requestPath = request.getRequestURI();
}

List<FieldError> fieldErrors = manve.getBindingResult().getFieldErrors();
for (FieldError fe : fieldErrors) {
List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
if (validationErrorList == null) {
validationErrorList = new ArrayList<ValidationError>();
errorDetail.getErrors().put(fe.getField(), validationErrorList);
}
ValidationError validationError = new ValidationError();
validationError.setCode(fe.getCode());
validationError.setMessage(messageSource.getMessage(fe, null));
validationErrorList.add(validationError);

}
return errorDetail;
}
}
22 changes: 22 additions & 0 deletions src/main/java/dto/error/ValidationError.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package dto.error;

public class ValidationError {
private String code;
private String message;

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package io.zipcoder.tc_spring_poll_application.controller;

import dto.VoteResult;
import io.zipcoder.tc_spring_poll_application.domain.Vote;
import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ComputeResultController {
private VoteRepository voteRepository;

@Autowired
public ComputeResultController(VoteRepository voteRepository) {
this.voteRepository = voteRepository;
}

@RequestMapping(value = "/computeresult", method = RequestMethod.GET)
public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
VoteResult voteResult = new VoteResult();
Iterable<Vote> allVotes = voteRepository.findVotesByPoll(pollId);

//TODO: Implement algorithm to count votes
return new ResponseEntity<VoteResult>(voteResult, HttpStatus.OK);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package io.zipcoder.tc_spring_poll_application.controller;

import io.zipcoder.tc_spring_poll_application.domain.Poll;
import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
import io.zipcoder.tc_spring_poll_application.repositories.PollRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.validation.Valid;
import java.net.URI;

@RestController
public class PollController {
private PollRepository pollRepository;

@Autowired
public PollController(PollRepository pollRepository){
this.pollRepository = pollRepository;
}

@Valid
@RequestMapping(value="/polls", method= RequestMethod.GET)
public ResponseEntity<Iterable<Poll>> getAllPolls() {
Iterable<Poll> allPolls = pollRepository.findAll();
return new ResponseEntity<>(allPolls, HttpStatus.OK);
}

@Valid
@RequestMapping(value="/polls", method=RequestMethod.POST)
public ResponseEntity<?> createPoll(@RequestBody Poll poll) {
poll = pollRepository.save(poll);
URI newPollUri = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(poll.getId())
.toUri();
HttpHeaders httpResult = new HttpHeaders();
httpResult.setLocation(newPollUri);
return new ResponseEntity<>(httpResult, HttpStatus.CREATED);
}

@Valid
@RequestMapping(value="/polls/{pollId}", method=RequestMethod.GET)
public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
Poll p = pollRepository.findOne(pollId);
return new ResponseEntity<> (p, HttpStatus.OK);
}

@Valid
@RequestMapping(value="/polls/{pollId}", method=RequestMethod.PUT)
public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
// Save the entity
Poll p = pollRepository.save(poll);
return new ResponseEntity<>(HttpStatus.OK);
}

@Valid
@RequestMapping(value="/polls/{pollId}", method=RequestMethod.DELETE)
public ResponseEntity<?> deletePoll(@PathVariable Long pollId) {
pollRepository.delete(pollId);
return new ResponseEntity<>(HttpStatus.OK);
}

public void verifyPoll(Long pollId) throws ResourceNotFoundException {
Poll poll = pollRepository.findOne(pollId);
if (poll == null){
throw new ResourceNotFoundException("Poll with id" + pollId + " not found.");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package io.zipcoder.tc_spring_poll_application.controller;

import io.zipcoder.tc_spring_poll_application.domain.Vote;
import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@RestController
public class VoteController {

private VoteRepository voteRepository;

@Autowired
public VoteController(VoteRepository voteRepository) {
this.voteRepository = voteRepository;
}

@RequestMapping(value = "/polls/{pollId}/votes", method = RequestMethod.POST)
public ResponseEntity<?> createVote(@PathVariable Long pollId, @RequestBody Vote
vote) {
vote = voteRepository.save(vote);
// Set the headers for the newly created resource
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setLocation(ServletUriComponentsBuilder.
fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri());
return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
}

@RequestMapping(value="/polls/votes", method=RequestMethod.GET)
public Iterable<Vote> getAllVotes() {
return voteRepository.findAll();
}

@RequestMapping(value="/polls/{pollId}/votes", method=RequestMethod.GET)
public Iterable<Vote> getVote(@PathVariable Long pollId) {
return voteRepository.findVotesByPoll(pollId);
}
}
Loading