Просмотр исходного кода

Merge 63b0ddee50fae4d0df1b498d74fb3c425a1d4867 into f91a622cc731197181dd1b1e4b17c9bcb450ae8a

Patrick Glavin 8 лет назад
Родитель
Сommit
3b93c29298
Аккаунт пользователя с таким Email не найден

+ 22
- 0
src/main/java/dtos/OptionCount.java Просмотреть файл

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 Просмотреть файл

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
+}

+ 44
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/ComputeResultController.java Просмотреть файл

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.http.HttpStatus;
8
+import org.springframework.http.ResponseEntity;
9
+import org.springframework.web.bind.annotation.RequestMapping;
10
+import org.springframework.web.bind.annotation.RequestMethod;
11
+import org.springframework.web.bind.annotation.RequestParam;
12
+import org.springframework.web.bind.annotation.RestController;
13
+
14
+import javax.inject.Inject;
15
+import java.util.Collection;
16
+import java.util.HashMap;
17
+import java.util.Map;
18
+
19
+@RestController
20
+public class ComputeResultController {
21
+    @Inject
22
+    private VoteRepository voteRepository;
23
+
24
+    @RequestMapping(value = "/computeresult", method = RequestMethod.GET)
25
+    public ResponseEntity<?> computeResult(@RequestParam Long pollId) {
26
+        VoteResult voteResult = new VoteResult();
27
+        Iterable<Vote> allVotes = voteRepository.findById(pollId);
28
+        int totalVotes = 0;
29
+        Map<Long, OptionCount> tempMap = new HashMap<>();
30
+        for(Vote v : allVotes) {
31
+            totalVotes ++;
32
+            OptionCount optionCount = tempMap.get(v.getOption().getId());
33
+            if(optionCount == null) {
34
+                optionCount = new OptionCount();
35
+                optionCount.setOptionId(v.getOption().getId());
36
+                tempMap.put(v.getOption().getId(), optionCount);
37
+            }
38
+            optionCount.setCount(optionCount.getCount() + 1);
39
+        }
40
+        voteResult.setTotalVotes(totalVotes);
41
+        voteResult.setResults(tempMap.values());
42
+        return new ResponseEntity<>(voteResult, HttpStatus.OK);
43
+    }
44
+}

+ 73
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/PollController.java Просмотреть файл

1
+package io.zipcoder.tc_spring_poll_application.controller;
2
+
3
+import io.zipcoder.tc_spring_poll_application.domain.Option;
4
+import io.zipcoder.tc_spring_poll_application.domain.Poll;
5
+import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
6
+import io.zipcoder.tc_spring_poll_application.repositories.PollRepository;
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 java.net.URI;
15
+
16
+@RestController
17
+public class PollController {
18
+
19
+    @Inject
20
+    private PollRepository pollRepository;
21
+
22
+    @RequestMapping(value="/polls", method= RequestMethod.GET)
23
+    public ResponseEntity<Iterable<Poll>> getAllPolls() {
24
+        Iterable<Poll> allPolls = pollRepository.findAll();
25
+        return new ResponseEntity<>(allPolls, HttpStatus.OK);
26
+    }
27
+
28
+    @RequestMapping(value="/polls", method=RequestMethod.POST)
29
+    public ResponseEntity<?> createPoll(@RequestBody Poll poll) {
30
+        URI newPollUri = ServletUriComponentsBuilder
31
+                .fromCurrentRequest()
32
+                .path("/{id}")
33
+                .buildAndExpand(poll.getId())
34
+                .toUri();
35
+        HttpHeaders responseHeaders = new HttpHeaders();
36
+        responseHeaders.setLocation(newPollUri);
37
+        for (Option option:poll.getOptions()) {
38
+            System.out.println(option.toString());
39
+        }
40
+        poll = pollRepository.save(poll);
41
+        return new ResponseEntity<>(poll, responseHeaders, HttpStatus.CREATED);
42
+    }
43
+
44
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.GET)
45
+    public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
46
+        verifyPoll(pollId);
47
+        Poll p = pollRepository.findOne(pollId);
48
+        return new ResponseEntity<> (p, HttpStatus.OK);
49
+    }
50
+
51
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.PUT)
52
+    public ResponseEntity<?> updatePoll(@RequestBody Poll poll, @PathVariable Long pollId) {
53
+        verifyPoll(pollId);
54
+        // Save the entity
55
+        Poll p = pollRepository.save(poll);
56
+        return new ResponseEntity<>(p, HttpStatus.OK);
57
+    }
58
+
59
+    @RequestMapping(value="/polls/{pollId}", method=RequestMethod.DELETE)
60
+    public ResponseEntity<?> deletePoll(@PathVariable Long pollId) {
61
+        verifyPoll(pollId);
62
+        pollRepository.delete(pollId);
63
+        return new ResponseEntity<>(HttpStatus.OK);
64
+    }
65
+
66
+    public void verifyPoll(Long pollid){
67
+        Poll poll = pollRepository.findOne(pollid);
68
+        if (poll == null){
69
+            throw new ResourceNotFoundException("Unable to verify poll");
70
+        }
71
+    }
72
+
73
+}

+ 39
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/controller/VoteController.java Просмотреть файл

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.http.HttpHeaders;
6
+import org.springframework.http.HttpStatus;
7
+import org.springframework.http.ResponseEntity;
8
+import org.springframework.web.bind.annotation.*;
9
+import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
10
+
11
+import javax.inject.Inject;
12
+
13
+@RestController
14
+public class VoteController {
15
+    @Inject
16
+    private VoteRepository voteRepository;
17
+
18
+    @RequestMapping(value = "/polls/{pollId}/votes", method = RequestMethod.POST)
19
+    public ResponseEntity<?> createVote(@PathVariable Long pollId, @RequestBody Vote
20
+            vote) {
21
+        vote = voteRepository.save(vote);
22
+        // Set the headers for the newly created resource
23
+        HttpHeaders responseHeaders = new HttpHeaders();
24
+        responseHeaders.setLocation(ServletUriComponentsBuilder.
25
+                fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri());
26
+        return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
27
+    }
28
+
29
+    @RequestMapping(value="/polls/votes", method=RequestMethod.GET)
30
+    public Iterable<Vote> getAllVotes() {
31
+        return voteRepository.findAll();
32
+    }
33
+
34
+    @RequestMapping(value="/polls/{pollId}/votes", method=RequestMethod.GET)
35
+    public Iterable<Vote> getVote(@PathVariable Long pollId) {
36
+        return voteRepository.findById(pollId);
37
+    }
38
+
39
+}

+ 39
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Option.java Просмотреть файл

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
+    public Long getId() {
20
+        return id;
21
+    }
22
+
23
+    public void setId(Long id) {
24
+        this.id = id;
25
+    }
26
+
27
+    public String getValue() {
28
+        return value;
29
+    }
30
+
31
+    public void setValue(String value) {
32
+        this.value = value;
33
+    }
34
+
35
+    @Override
36
+    public String toString() {
37
+        return getId() + "," + getValue();
38
+    }
39
+}

+ 55
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Poll.java Просмотреть файл

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
+    public Long getId() {
28
+        return id;
29
+    }
30
+
31
+    public void setId(Long id) {
32
+        this.id = id;
33
+    }
34
+
35
+    public String getQuestion() {
36
+        return question;
37
+    }
38
+
39
+    public void setQuestion(String question) {
40
+        this.question = question;
41
+    }
42
+
43
+    public Set<Option> getOptions() {
44
+        return options;
45
+    }
46
+
47
+    public void setOptions(Set<Option> options) {
48
+        this.options = options;
49
+    }
50
+
51
+    @Override
52
+    public String toString() {
53
+        return getId() + ", " + getQuestion() + ", " + getOptions();
54
+    }
55
+}

+ 37
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/domain/Vote.java Просмотреть файл

1
+package io.zipcoder.tc_spring_poll_application.domain;
2
+
3
+import javax.persistence.*;
4
+
5
+@Entity
6
+public class Vote {
7
+
8
+    @Id
9
+    @GeneratedValue
10
+    @Column(name = "VOTE_ID")
11
+    private Long id;
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
+
33
+    @Override
34
+    public String toString() {
35
+        return getId() + ", " + getOption();
36
+    }
37
+}

+ 62
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/exception/ErrorDetail.java Просмотреть файл

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

+ 18
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/exception/ResourceNotFoundException.java Просмотреть файл

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
+    public ResourceNotFoundException() {
9
+    }
10
+
11
+    public ResourceNotFoundException(String message) {
12
+        super(message);
13
+    }
14
+
15
+    public ResourceNotFoundException(String message, Throwable cause) {
16
+        super(message, cause);
17
+    }
18
+}

+ 53
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/exception/RestExceptionHandler.java Просмотреть файл

1
+package io.zipcoder.tc_spring_poll_application.exception;
2
+
3
+import org.springframework.http.HttpStatus;
4
+import org.springframework.http.ResponseEntity;
5
+import org.springframework.validation.FieldError;
6
+import org.springframework.context.MessageSource;
7
+import org.springframework.web.bind.MethodArgumentNotValidException;
8
+import org.springframework.web.bind.annotation.ControllerAdvice;
9
+import org.springframework.web.bind.annotation.ExceptionHandler;
10
+import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
11
+
12
+import javax.inject.Inject;
13
+import javax.servlet.http.HttpServletRequest;
14
+import java.util.ArrayList;
15
+import java.util.Date;
16
+import java.util.List;
17
+
18
+@ControllerAdvice
19
+public class RestExceptionHandler extends ResponseEntityExceptionHandler {
20
+
21
+    @Inject
22
+    private MessageSource messageSource;
23
+
24
+    @ExceptionHandler(ResourceNotFoundException.class)
25
+    public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request) {
26
+        ErrorDetail errorDetail = new ErrorDetail();
27
+        errorDetail.setDetail(rnfe.getMessage());
28
+        errorDetail.setDeveloperMessage(rnfe.getLocalizedMessage());
29
+        errorDetail.setTitle(rnfe.getClass().toString());
30
+        errorDetail.setTimeStamp(new Date().getTime());
31
+        return new ResponseEntity<>(errorDetail, HttpStatus.NOT_FOUND);
32
+    }
33
+
34
+    @ExceptionHandler(MethodArgumentNotValidException.class)
35
+    public ResponseEntity<?> handleValidationError(MethodArgumentNotValidException manve, HttpServletRequest request) {
36
+        ErrorDetail errorDetail = new ErrorDetail();
37
+        List<FieldError> fieldErrors = manve.getBindingResult().getFieldErrors();
38
+        for (FieldError fe : fieldErrors) {
39
+
40
+            List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
41
+            if (validationErrorList == null) {
42
+                validationErrorList = new ArrayList<>();
43
+                errorDetail.getErrors().put(fe.getField(), validationErrorList);
44
+            }
45
+            ValidationError validationError = new ValidationError();
46
+            validationError.setCode(fe.getCode());
47
+            validationError.setMessage(messageSource.getMessage(fe, null));
48
+            validationErrorList.add(validationError);
49
+        }
50
+        return new ResponseEntity(errorDetail, HttpStatus.BAD_REQUEST);
51
+    }
52
+
53
+}

+ 22
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/exception/ValidationError.java Просмотреть файл

1
+package io.zipcoder.tc_spring_poll_application.exception;
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
+}

+ 8
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/OptionRepository.java Просмотреть файл

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
+
8
+}

+ 7
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/PollRepository.java Просмотреть файл

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
+}

+ 13
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/repositories/VoteRepository.java Просмотреть файл

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> findById(Long pollId);
13
+}

+ 2
- 0
src/main/resources/messages.properties Просмотреть файл

1
+NotEmpty.poll.question=Question is a required field
2
+Size.poll.options=Options must be greater than {2} and less than {1}