Created
July 1, 2018 12:11
-
-
Save GrakovNe/08f9f4dd9332d532f205a2b1f9598af6 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, Response response); | |
| Response getBlankResponse(); | |
| 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::toResponse).collect(Collectors.toList())); | |
| } | |
| default ApiResponse<Page<Response>> from(Page<Entity> page) { | |
| return new ApiResponse<>(page.map(this::toResponse)); | |
| } | |
| private Response toResponse(Entity entity) { | |
| return findTargetUser() | |
| .map(user -> feedWithUserData(entity, feedWith(entity, getBlankResponse()), user)) | |
| .orElse(feedWith(entity, getBlankResponse())); | |
| } | |
| private 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