Created
July 1, 2018 11:47
-
-
Save GrakovNe/1a69ce6d4479b197c0cd232fd7567409 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package org.grakovne.mds.server.rest.converters; | |
| import org.grakovne.mds.server.domain.User; | |
| import org.grakovne.mds.server.rest.responses.ApiResponse; | |
| import org.springframework.data.domain.Page; | |
| import org.springframework.security.core.context.SecurityContextHolder; | |
| import java.util.Collection; | |
| import java.util.List; | |
| import java.util.Optional; | |
| import java.util.stream.Collectors; | |
| public interface MdsConverter<Entity, Response> { | |
| Response feedWith(Entity entity); | |
| default Response feedWithUserData(Entity entity, Response response, User user) { | |
| return response; | |
| } | |
| default ApiResponse<Response> from(Entity entity) { | |
| return null == entity | |
| ? new ApiResponse() | |
| : new ApiResponse<>(toResponse(entity)); | |
| } | |
| default ApiResponse<List<Response>> from(Collection<Entity> collection) { | |
| return new ApiResponse<>(collection.stream().map(this::feedWith).collect(Collectors.toList())); | |
| } | |
| default ApiResponse<Page<Response>> from(Page<Entity> page) { | |
| return new ApiResponse<>(page.map(this::feedWith)); | |
| } | |
| default Response toResponse(Entity entity) { | |
| return findTargetUser() | |
| .map(user -> feedWithUserData(entity, feedWith(entity), user)) | |
| .orElse(feedWith(entity)); | |
| } | |
| default Optional<User> findTargetUser() { | |
| Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); | |
| if (principal instanceof User) { | |
| return Optional.of((User) principal); | |
| } else { | |
| return Optional.empty(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment