Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 767931cc

Přidáno uživatelem Jakub Danek před více než 5 roky(ů)

re #37 unify user profile endpoints under single controller and namespace

Zobrazit rozdíly:

server/src/main/java/org/danekja/ymanager/ws/rest/ApiController.java
5 5
import org.danekja.ymanager.business.Manager;
6 6
import org.danekja.ymanager.dto.*;
7 7
import org.danekja.ymanager.util.localization.Language;
8
import org.danekja.ymanager.util.localization.Message;
9
import org.slf4j.Logger;
10
import org.slf4j.LoggerFactory;
11 8
import org.springframework.beans.factory.annotation.Autowired;
12 9
import org.springframework.http.HttpHeaders;
13
import org.springframework.http.MediaType;
14 10
import org.springframework.http.ResponseEntity;
15 11
import org.springframework.web.bind.annotation.*;
16 12
import org.springframework.web.multipart.MultipartFile;
17 13

  
18 14
import java.time.LocalDate;
19 15
import java.time.format.DateTimeFormatter;
20
import java.util.Arrays;
21
import java.util.HashMap;
22
import java.util.Map;
23
import java.util.function.Function;
24 16

  
25
import static org.springframework.http.HttpStatus.OK;
26
import static org.springframework.http.ResponseEntity.ok;
27 17
import static org.springframework.web.bind.annotation.RequestMethod.*;
28 18

  
29 19
@RestController
30
public class ApiController {
31

  
32
    private static final Logger log = LoggerFactory.getLogger(ApiController.class);
20
public class ApiController extends BaseController {
33 21

  
34 22
    private final Manager manager;
35 23

  
......
41 29
        this.fileService = fileService;
42 30
    }
43 31

  
44
    private ResponseEntity sendError(Integer errorCode, String messageKey, Language language) {
45
        String localizedMessage = Message.getString(language, messageKey);
46
        Map<String, String> result = new HashMap<>();
47
        result.put("error", errorCode.toString());
48
        result.put("message", localizedMessage);
49
        return ResponseEntity.status(errorCode).contentType(MediaType.APPLICATION_JSON).body(result);
50
    }
51

  
52
    private <T> ResponseEntity handle(Language language, RESTInvokeHandler<T> handler) {
53
        try {
54
            handler.invoke();
55
            return ok(OK);
56
        } catch (RESTFullException e) {
57
            log.error(e.getMessage());
58
            return sendError(400, e.getLocalizedMessage(), language);
59
        } catch (Exception e) {
60
            log.error(e.getMessage());
61
            return sendError(401, e.getMessage(), language);
62
        }
63
    }
64

  
65
    private <T> ResponseEntity handle(Language language, RESTGetHandler<T> handler) {
66
        return handle(language, handler, null, null);
67
    }
68

  
69
    private <T> ResponseEntity handle(Language language, RESTGetHandler<T> handler, Function<T, String[]> header, Function<T, Object> bodyValue) {
70
        try {
71
            T result = handler.get();
72

  
73
            ResponseEntity.BodyBuilder response = ResponseEntity.ok();
74

  
75
            if (header != null) {
76
                String[] headers = header.apply(result);
77

  
78
                if (headers.length > 1) {
79
                    response.header(headers[0], Arrays.copyOfRange(headers, 1, headers.length - 1));
80
                } else if (headers.length == 1) {
81
                    response.header(headers[0]);
82
                }
83
            }
84

  
85
            return response.body(bodyValue != null ? bodyValue.apply(result) : result);
86

  
87
        } catch (RESTFullException e) {
88
            log.error(e.getMessage());
89
            return sendError(400, e.getLocalizedMessage(), language);
90
        } catch (Exception e) {
91
            log.error(e.getMessage());
92
            return sendError(401, "rest.exception.generic", language);
93
        }
94
    }
95

  
96 32
    private Long getUserId(String id) {
97 33
        // TODO verify permission
98 34
        if (id.toLowerCase().equals("me")) {
......
140 76
         );
141 77
    }
142 78

  
143
    @RequestMapping(value = "/user/{id}/profile", method=GET)
144
    public ResponseEntity userProfile(
145
            @PathVariable("id") String id,
146
            @RequestParam(value = "lang", required = false) String lang)
147
    {
148
        return handle(Language.getLanguage(lang), () ->
149
                manager.getUserProfile(getUserId(id))
150
        );
151
    }
152

  
153 79
    @RequestMapping(value = "/user/{id}/calendar", method=GET)
154 80
    public ResponseEntity userCalendar(
155 81
            @PathVariable("id") String id,
server/src/main/java/org/danekja/ymanager/ws/rest/BaseController.java
1
package org.danekja.ymanager.ws.rest;
2

  
3
import org.danekja.ymanager.util.localization.Language;
4
import org.danekja.ymanager.util.localization.Message;
5
import org.slf4j.Logger;
6
import org.slf4j.LoggerFactory;
7
import org.springframework.http.MediaType;
8
import org.springframework.http.ResponseEntity;
9

  
10
import java.util.Arrays;
11
import java.util.HashMap;
12
import java.util.Map;
13
import java.util.function.Function;
14

  
15
import static org.springframework.http.HttpStatus.OK;
16
import static org.springframework.http.ResponseEntity.ok;
17

  
18
public abstract class BaseController {
19

  
20
    protected final Logger LOG = LoggerFactory.getLogger(this.getClass());
21

  
22
    protected <T> ResponseEntity handle(Language language, RESTGetHandler<T> handler) {
23
        return handle(language, handler, null, null);
24
    }
25

  
26
    protected <T> ResponseEntity handle(Language language, RESTGetHandler<T> handler, Function<T, String[]> header, Function<T, Object> bodyValue) {
27
        try {
28
            T result = handler.get();
29

  
30
            ResponseEntity.BodyBuilder response = ResponseEntity.ok();
31

  
32
            if (header != null) {
33
                String[] headers = header.apply(result);
34

  
35
                if (headers.length > 1) {
36
                    response.header(headers[0], Arrays.copyOfRange(headers, 1, headers.length - 1));
37
                } else if (headers.length == 1) {
38
                    response.header(headers[0]);
39
                }
40
            }
41

  
42
            return response.body(bodyValue != null ? bodyValue.apply(result) : result);
43

  
44
        } catch (RESTFullException e) {
45
            LOG.error(e.getMessage());
46
            return sendError(400, e.getLocalizedMessage(), language);
47
        } catch (Exception e) {
48
            LOG.error(e.getMessage());
49
            return sendError(401, "rest.exception.generic", language);
50
        }
51
    }
52

  
53
    protected ResponseEntity sendError(Integer errorCode, String messageKey, Language language) {
54
        String localizedMessage = Message.getString(language, messageKey);
55
        Map<String, String> result = new HashMap<>();
56
        result.put("error", errorCode.toString());
57
        result.put("message", localizedMessage);
58
        return ResponseEntity.status(errorCode).contentType(MediaType.APPLICATION_JSON).body(result);
59
    }
60

  
61
    protected <T> ResponseEntity handle(Language language, RESTInvokeHandler<T> handler) {
62
        try {
63
            handler.invoke();
64
            return ok(OK);
65
        } catch (RESTFullException e) {
66
            LOG.error(e.getMessage());
67
            return sendError(400, e.getLocalizedMessage(), language);
68
        } catch (Exception e) {
69
            LOG.error(e.getMessage());
70
            return sendError(401, e.getMessage(), language);
71
        }
72
    }
73
}
server/src/main/java/org/danekja/ymanager/ws/rest/UserController.java
1 1
package org.danekja.ymanager.ws.rest;
2 2

  
3
import org.danekja.ymanager.business.UserManager;
3
import org.danekja.ymanager.business.Manager;
4 4
import org.danekja.ymanager.domain.User;
5
import org.danekja.ymanager.dto.FullUserProfile;
5
import org.danekja.ymanager.util.localization.Language;
6 6
import org.springframework.beans.factory.annotation.Autowired;
7
import org.springframework.http.ResponseEntity;
7 8
import org.springframework.security.authentication.AnonymousAuthenticationToken;
8 9
import org.springframework.security.core.Authentication;
9
import org.springframework.web.bind.annotation.GetMapping;
10
import org.springframework.web.bind.annotation.RestController;
10
import org.springframework.web.bind.annotation.*;
11 11

  
12 12
/**
13 13
 * Controller for Users collection of WS API.
14 14
 */
15
@RestController("/users")
16
public class UserController {
15
@RestController
16
@RequestMapping("/users")
17
public class UserController extends BaseController {
17 18

  
18
    private final UserManager manager;
19
    private final Manager manager;
19 20

  
20 21
    @Autowired
21
    public UserController(UserManager manager) {
22
    public UserController(Manager manager) {
22 23
        this.manager = manager;
23 24
    }
24 25

  
......
29 30
     * @return user information object
30 31
     */
31 32
    @GetMapping("/current/profile")
32
    public FullUserProfile getCurrentUser(Authentication auth) {
33
    public ResponseEntity getCurrentUser(Authentication auth) {
33 34

  
34
        if (auth instanceof AnonymousAuthenticationToken) {
35
        if (auth instanceof AnonymousAuthenticationToken
36
                || auth.getPrincipal() == null
37
                || !(auth.getPrincipal() instanceof User)) {
35 38
            return null;
36 39
        }
37 40

  
38
        User user = manager.getUser(auth.getName());
39
        return user != null ? new FullUserProfile(user) : null;
41
        return getUserProfile(((User) auth.getPrincipal()).getId(), null);
42
    }
43

  
44
    @GetMapping("/{id}/profile")
45
    public ResponseEntity getUserProfile(
46
            @PathVariable("id") Long id,
47
            @RequestParam(value = "lang", required = false) String lang) {
48
        return handle(Language.getLanguage(lang), () ->
49
                manager.getUserProfile(id)
50
        );
40 51
    }
41 52
}

Také k dispozici: Unified diff