Bläddra i källkod

Lab Submission

Haysel Santiago 8 år sedan
förälder
incheckning
2923010f12

+ 22
- 0
src/main/java/dtos/OptionCount.java Visa fil

@@ -0,0 +1,22 @@
1
+package dtos;
2
+
3
+public class OptionCount {
4
+    private Long optionId;
5
+    private int count;
6
+
7
+    public Long getOptionId() {
8
+        return optionId;
9
+    }
10
+
11
+    public void setOptionId(Long optionId) {
12
+        this.optionId = optionId;
13
+    }
14
+
15
+    public int getCount() {
16
+        return count;
17
+    }
18
+
19
+    public void setCount(int count) {
20
+        this.count = count;
21
+    }
22
+}

+ 23
- 0
src/main/java/dtos/VoteResult.java Visa fil

@@ -0,0 +1,23 @@
1
+package dtos;
2
+
3
+import java.util.Collection;
4
+public class VoteResult {
5
+    private int totalVotes;
6
+    private Collection<OptionCount> results;
7
+
8
+    public int getTotalVotes() {
9
+        return totalVotes;
10
+    }
11
+
12
+    public void setTotalVotes(int totalVotes) {
13
+        this.totalVotes = totalVotes;
14
+    }
15
+
16
+    public Collection<OptionCount> getResults() {
17
+        return results;
18
+    }
19
+
20
+    public void setResults(Collection<OptionCount> results) {
21
+        this.results = results;
22
+    }
23
+}

+ 50
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/ComputeResultController.java Visa fil

@@ -0,0 +1,50 @@
1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import dtos.OptionCount;
4
+import dtos.VoteResult;
5
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
6
+import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
7
+import org.springframework.beans.factory.annotation.Autowired;
8
+import org.springframework.http.HttpStatus;
9
+import org.springframework.http.ResponseEntity;
10
+import org.springframework.web.bind.annotation.RequestMapping;
11
+import org.springframework.web.bind.annotation.RequestMethod;
12
+import org.springframework.web.bind.annotation.RequestParam;
13
+import org.springframework.web.bind.annotation.RestController;
14
+
15
+import java.util.HashMap;
16
+import java.util.Map;
17
+
18
+@RestController
19
+public class ComputeResultController {
20
+
21
+    private VoteRepository voteRepository;
22
+
23
+    @Autowired
24
+    public ComputeResultController(VoteRepository voteRepository) {
25
+        this.voteRepository = voteRepository;
26
+    }
27
+
28
+    @RequestMapping(value = "/computeresult", method = RequestMethod.GET)
29
+    public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
30
+        VoteResult voteResult = new VoteResult();
31
+        Iterable<Vote> allVotes = voteRepository.findVotesByPoll(pollId);
32
+
33
+        //TODO: Implement algorithm to count votes
34
+        int totalVotes = 0;
35
+        Map<Long, OptionCount> tempMap = new HashMap<Long, OptionCount>();
36
+        for(Vote v : allVotes) {
37
+            totalVotes ++;
38
+            OptionCount optionCount = tempMap.get(v.getOption().getId());
39
+            if(optionCount == null) {
40
+                optionCount = new OptionCount();
41
+                optionCount.setOptionId(v.getOption().getId());
42
+                tempMap.put(v.getOption().getId(), optionCount);
43
+            }
44
+            optionCount.setCount(optionCount.getCount()+1);
45
+        }
46
+        voteResult.setTotalVotes(totalVotes);
47
+        voteResult.setResults(tempMap.values());
48
+        return new ResponseEntity<VoteResult>(voteResult, HttpStatus.OK);
49
+    }
50
+}

+ 73
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/PollController.java Visa fil

@@ -0,0 +1,73 @@
1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Poll;
4
+import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
5
+import io.zipcoder.tc_spring_poll_application.repositories.PollRepository;
6
+import org.springframework.beans.factory.annotation.Autowired;
7
+import org.springframework.http.HttpHeaders;
8
+import org.springframework.http.HttpStatus;
9
+import org.springframework.http.ResponseEntity;
10
+import org.springframework.web.bind.annotation.*;
11
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
12
+
13
+import javax.inject.Inject;
14
+import javax.validation.Valid;
15
+import java.net.URI;
16
+
17
+
18
+@RestController
19
+public class PollController {
20
+
21
+
22
+    private PollRepository pollRepository;
23
+
24
+    @Autowired
25
+    public PollController(PollRepository pollRepository) {
26
+        this.pollRepository = pollRepository;
27
+    }
28
+
29
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.GET)
30
+    public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
31
+        Poll p = pollRepository.findOne(pollId);
32
+        return new ResponseEntity<> (p, HttpStatus.OK);
33
+    }
34
+
35
+    @RequestMapping(value="/polls", method= RequestMethod.GET)
36
+    public ResponseEntity<Iterable<Poll>> getAllPolls() {
37
+        Iterable<Poll> allPolls = pollRepository.findAll();
38
+        return new ResponseEntity<>(allPolls, HttpStatus.OK);
39
+    }
40
+
41
+    @RequestMapping(value="/polls", method=RequestMethod.POST)
42
+    public ResponseEntity<?> createPoll(@Valid @RequestBody Poll poll) {
43
+        poll = pollRepository.save(poll);
44
+        HttpHeaders responseHeaders = new HttpHeaders();
45
+        URI newPollUri = ServletUriComponentsBuilder
46
+                .fromCurrentRequest()
47
+                .path("/{id}")
48
+                .buildAndExpand(poll.getId())
49
+                .toUri();
50
+        responseHeaders.setLocation(newPollUri);
51
+        return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
52
+    }
53
+
54
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.PUT)
55
+    public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
56
+        // Save the entity
57
+        Poll p = pollRepository.save(poll);
58
+        return new ResponseEntity<>(HttpStatus.OK);
59
+    }
60
+
61
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.DELETE)
62
+    public ResponseEntity<?> deletePoll(@PathVariable Long pollId) {
63
+        pollRepository.delete(pollId);
64
+        return new ResponseEntity<>(HttpStatus.OK);
65
+    }
66
+
67
+    protected void verifyPoll(Long pollId) throws ResourceNotFoundException {
68
+        Poll poll = pollRepository.findOne(pollId);
69
+        if (poll == null) {
70
+            throw new ResourceNotFoundException("Poll with id " + pollId + " not found");
71
+        }
72
+    }
73
+}

+ 46
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/VoteController.java Visa fil

@@ -0,0 +1,46 @@
1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
4
+import io.zipcoder.tc_spring_poll_application.repositories.VoteRepository;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.data.jpa.repository.Query;
7
+import org.springframework.data.repository.CrudRepository;
8
+import org.springframework.http.HttpHeaders;
9
+import org.springframework.http.HttpStatus;
10
+import org.springframework.http.ResponseEntity;
11
+import org.springframework.web.bind.annotation.*;
12
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
13
+
14
+import javax.inject.Inject;
15
+
16
+@RestController
17
+public class VoteController {
18
+
19
+    private VoteRepository voteRepository;
20
+
21
+    @Autowired
22
+    public VoteController(VoteRepository voteRepository) {
23
+        this.voteRepository = voteRepository;
24
+    }
25
+
26
+    @RequestMapping(value = "/polls/{pollId}/votes", method = RequestMethod.POST)
27
+    public ResponseEntity<?> createVote(@PathVariable Long pollId, @RequestBody Vote
28
+            vote) {
29
+        vote = voteRepository.save(vote);
30
+        // Set the headers for the newly created resource
31
+        HttpHeaders responseHeaders = new HttpHeaders();
32
+        responseHeaders.setLocation(ServletUriComponentsBuilder.
33
+                fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri());
34
+        return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
35
+    }
36
+
37
+    @RequestMapping(value="/polls/votes", method=RequestMethod.GET)
38
+    public Iterable<Vote> getAllVotes() {
39
+        return voteRepository.findAll();
40
+    }
41
+
42
+    @RequestMapping(value="/polls/{pollId}/votes", method=RequestMethod.GET)
43
+    public Iterable<Vote> getVote(@PathVariable Long pollId) {
44
+        return voteRepository.findById(pollId);
45
+    }
46
+}

+ 35
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Option.java Visa fil

@@ -0,0 +1,35 @@
1
+package io.zipcoder.tc_spring_poll_application.domain;
2
+
3
+import javax.persistence.Column;
4
+import javax.persistence.Entity;
5
+import javax.persistence.GeneratedValue;
6
+import javax.persistence.Id;
7
+
8
+@Entity
9
+public class Option {
10
+
11
+    @Id
12
+    @GeneratedValue
13
+    @Column(name = "OPTION_ID")
14
+    private Long id;
15
+
16
+    @Column(name = "OPTION_VALUE")
17
+    private String value;
18
+
19
+
20
+    public Long getId() {
21
+        return id;
22
+    }
23
+
24
+    public void setId(Long id) {
25
+        this.id = id;
26
+    }
27
+
28
+    public String getValue() {
29
+        return value;
30
+    }
31
+
32
+    public void setValue(String value) {
33
+        this.value = value;
34
+    }
35
+}

+ 51
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Poll.java Visa fil

@@ -0,0 +1,51 @@
1
+package io.zipcoder.tc_spring_poll_application.domain;
2
+
3
+import org.hibernate.validator.constraints.NotEmpty;
4
+
5
+import javax.persistence.*;
6
+import javax.validation.constraints.Size;
7
+import java.util.Set;
8
+
9
+@Entity
10
+public class Poll {
11
+
12
+    @Id
13
+    @GeneratedValue
14
+    @Column (name = "POLL_ID")
15
+    private long id;
16
+
17
+    @Column (name = "QUESTION")
18
+    @NotEmpty
19
+    private String question;
20
+
21
+    @OneToMany (cascade = CascadeType.ALL)
22
+    @JoinColumn (name = "POLL_ID")
23
+    @OrderBy
24
+    @Size (min = 2, max = 6)
25
+    private Set<Option> options;
26
+
27
+
28
+    public long getId() {
29
+        return id;
30
+    }
31
+
32
+    public void setId(long id) {
33
+        this.id = id;
34
+    }
35
+
36
+    public String getQuestion() {
37
+        return question;
38
+    }
39
+
40
+    public void setQuestion(String question) {
41
+        this.question = question;
42
+    }
43
+
44
+    public Set getOptions() {
45
+        return options;
46
+    }
47
+
48
+    public void setOptions(Set<Option> options) {
49
+        this.options = options;
50
+    }
51
+}

+ 32
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Vote.java Visa fil

@@ -0,0 +1,32 @@
1
+package io.zipcoder.tc_spring_poll_application.domain;
2
+
3
+import javax.persistence.*;
4
+
5
+@Entity
6
+public class Vote {
7
+    @Id
8
+    @GeneratedValue
9
+    @Column(name="VOTE_ID")
10
+    private Long id;
11
+
12
+
13
+    @ManyToOne
14
+    @JoinColumn(name="OPTION_ID")
15
+    private Option option;
16
+
17
+    public Long getId() {
18
+        return id;
19
+    }
20
+
21
+    public void setId(Long id) {
22
+        this.id = id;
23
+    }
24
+
25
+    public Option getOption() {
26
+        return option;
27
+    }
28
+
29
+    public void setOption(Option option) {
30
+        this.option = option;
31
+    }
32
+}

+ 59
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dto/error/ErrorDetail.java Visa fil

@@ -0,0 +1,59 @@
1
+package io.zipcoder.tc_spring_poll_application.dto.error;
2
+
3
+import java.util.HashMap;
4
+import java.util.List;
5
+import java.util.Map;
6
+
7
+public class ErrorDetail {
8
+
9
+    private String title;
10
+    private int status;
11
+    private String detail;
12
+    private long timeStamp;
13
+    private String developerMessage;
14
+    private Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
15
+
16
+    public String getTitle() {
17
+        return title;
18
+    }
19
+
20
+    public void setTitle(String title) {
21
+        this.title = title;
22
+    }
23
+
24
+    public int getStatus() {
25
+        return status;
26
+    }
27
+
28
+    public void setStatus(int status) {
29
+        this.status = status;
30
+    }
31
+
32
+    public String getDetail() {
33
+        return detail;
34
+    }
35
+
36
+    public void setDetail(String detail) {
37
+        this.detail = detail;
38
+    }
39
+
40
+    public long getTimeStamp() {
41
+        return timeStamp;
42
+    }
43
+
44
+    public void setTimeStamp(long timeStamp) {
45
+        this.timeStamp = timeStamp;
46
+    }
47
+
48
+    public String getDeveloperMessage() {
49
+        return developerMessage;
50
+    }
51
+
52
+    public void setDeveloperMessage(String developerMessage) {
53
+        this.developerMessage = developerMessage;
54
+    }
55
+
56
+    public Map<String, List<ValidationError>> getErrors() {
57
+        return errors;
58
+    }
59
+}

+ 22
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dto/error/ValidationError.java Visa fil

@@ -0,0 +1,22 @@
1
+package io.zipcoder.tc_spring_poll_application.dto.error;
2
+
3
+public class ValidationError {
4
+    private String code;
5
+    private String message;
6
+
7
+    public String getCode() {
8
+        return code;
9
+    }
10
+
11
+    public void setCode(String code) {
12
+        this.code = code;
13
+    }
14
+
15
+    public String getMessage() {
16
+        return message;
17
+    }
18
+
19
+    public void setMessage(String message) {
20
+        this.message = message;
21
+    }
22
+}

+ 19
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/exception/ResourceNotFoundException.java Visa fil

@@ -0,0 +1,19 @@
1
+package io.zipcoder.tc_spring_poll_application.exception;
2
+
3
+import org.springframework.http.HttpStatus;
4
+import org.springframework.web.bind.annotation.ResponseStatus;
5
+
6
+@ResponseStatus(HttpStatus.NOT_FOUND)
7
+public class ResourceNotFoundException extends RuntimeException {
8
+
9
+    public ResourceNotFoundException() {
10
+    }
11
+
12
+    public ResourceNotFoundException(String message) {
13
+        super(message);
14
+    }
15
+
16
+    public ResourceNotFoundException(String message, Throwable cause) {
17
+        super(message, cause);
18
+    }
19
+}

+ 68
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/handler/RestExceptionHandler.java Visa fil

@@ -0,0 +1,68 @@
1
+package io.zipcoder.tc_spring_poll_application.handler;
2
+
3
+import io.zipcoder.tc_spring_poll_application.dto.error.ErrorDetail;
4
+import io.zipcoder.tc_spring_poll_application.dto.error.ValidationError;
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.context.MessageSource;
7
+import org.springframework.http.HttpStatus;
8
+import org.springframework.http.ResponseEntity;
9
+import org.springframework.validation.FieldError;
10
+import org.springframework.web.bind.MethodArgumentNotValidException;
11
+import org.springframework.web.bind.annotation.ControllerAdvice;
12
+import org.springframework.web.bind.annotation.ExceptionHandler;
13
+
14
+import javax.inject.Inject;
15
+import javax.servlet.http.HttpServletRequest;
16
+import java.util.ArrayList;
17
+import java.util.Date;
18
+import java.util.List;
19
+
20
+@ControllerAdvice
21
+public class RestExceptionHandler {
22
+
23
+    private MessageSource messageSource;
24
+
25
+    @Autowired
26
+    public RestExceptionHandler(MessageSource messageSource) {
27
+        this.messageSource = messageSource;
28
+    }
29
+
30
+    @ExceptionHandler(io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException.class)
31
+    public ResponseEntity<?> handleResourceNotFoundException(io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException rnfe, HttpServletRequest request) {
32
+        ErrorDetail errorDetail = new ErrorDetail();
33
+        errorDetail.setTitle("Resource Not Found");
34
+        errorDetail.setDetail(rnfe.getMessage());
35
+        errorDetail.setDeveloperMessage(rnfe.getClass().getName());
36
+        errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
37
+        errorDetail.setTimeStamp(new Date().getTime());
38
+
39
+        return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND);
40
+    }
41
+
42
+    @ExceptionHandler(MethodArgumentNotValidException.class)
43
+    public ResponseEntity<?>
44
+    handleValidationError(  MethodArgumentNotValidException manve,
45
+                            HttpServletRequest request){
46
+        ErrorDetail errorDetail = new ErrorDetail();
47
+        errorDetail.setTitle("Bad Request");
48
+        errorDetail.setDetail(manve.getMessage());
49
+        errorDetail.setDeveloperMessage(manve.getClass().getName());
50
+        errorDetail.setStatus(HttpStatus.BAD_REQUEST.value());
51
+        errorDetail.setTimeStamp(new Date().getTime());
52
+
53
+        List<FieldError> fieldErrors =  manve.getBindingResult().getFieldErrors();
54
+        for(FieldError fe : fieldErrors) {
55
+
56
+            List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
57
+            if(validationErrorList == null) {
58
+                validationErrorList = new ArrayList<>();
59
+                errorDetail.getErrors().put(fe.getField(), validationErrorList);
60
+            }
61
+            ValidationError validationError = new ValidationError();
62
+            validationError.setCode(fe.getCode());
63
+            validationError.setMessage(messageSource.getMessage(fe, null));
64
+            validationErrorList.add(validationError);
65
+        }
66
+        return new ResponseEntity<>(errorDetail, null, HttpStatus.BAD_REQUEST);
67
+    }
68
+}

+ 7
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/OptionRepository.java Visa fil

@@ -0,0 +1,7 @@
1
+package io.zipcoder.tc_spring_poll_application.repositories;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Option;
4
+import org.springframework.data.repository.CrudRepository;
5
+
6
+public interface OptionRepository extends CrudRepository<Option, Long> {
7
+}

+ 7
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/PollRepository.java Visa fil

@@ -0,0 +1,7 @@
1
+package io.zipcoder.tc_spring_poll_application.repositories;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Poll;
4
+import org.springframework.data.repository.CrudRepository;
5
+
6
+public interface PollRepository extends CrudRepository<Poll, Long> {
7
+}

+ 15
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/VoteRepository.java Visa fil

@@ -0,0 +1,15 @@
1
+package io.zipcoder.tc_spring_poll_application.repositories;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Vote;
4
+import org.springframework.data.jpa.repository.Query;
5
+import org.springframework.data.repository.CrudRepository;
6
+
7
+public interface VoteRepository extends CrudRepository<Vote, Long> {
8
+    @Query(value = "SELECT v.* " +
9
+            "FROM Option o, Vote v " +
10
+            "WHERE o.POLL_ID = ?1 " +
11
+            "AND v.OPTION_ID = o.OPTION_ID", nativeQuery = true)
12
+    public Iterable<Vote> findVotesByPoll(Long pollId);
13
+
14
+    Iterable<Vote> findById(Long pollId);
15
+}