Created
August 3, 2019 00:35
-
-
Save acdcjunior/7beba90486748ee83012a90955a0446b to your computer and use it in GitHub Desktop.
This file contains 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
import com.fasterxml.jackson.annotation.JsonUnwrapped; | |
import org.springframework.expression.spel.standard.SpelExpressionParser; | |
import java.util.HashMap; | |
import java.util.Map; | |
@SuppressWarnings({"unused", "FieldCanBeLocal"}) | |
public class LinkedResource<T> { | |
private static final SpelExpressionParser SPEL_EXPRESSION_PARSER = new SpelExpressionParser(); | |
@JsonUnwrapped | |
private final T payload; | |
private Map<String, Map<String, String>> _links; | |
public LinkedResource(T payload, String href) { | |
this.payload = payload; | |
this._links = gerarSelfHref(payload, href); | |
} | |
private HashMap<String, Map<String, String>> gerarSelfHref(T payload, String href) { | |
HashMap<String, Map<String, String>> links = new HashMap<>(); | |
HashMap<String, String> self = new HashMap<>(); | |
self.put("href", SPEL_EXPRESSION_PARSER.parseExpression(href).getValue(payload, String.class)); | |
links.put("self", self); | |
return links; | |
} | |
public Map<String, Map<String, String>> get_links() { | |
return _links; | |
} | |
} |
This file contains 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
import org.junit.jupiter.api.DisplayName; | |
import org.junit.jupiter.api.Test; | |
class LinkedResourceTest { | |
@Test | |
@DisplayName("Serializacao do LinkedResource inclui link") | |
void linkedResource() { | |
@SuppressWarnings("unused") | |
class ExemploC { | |
private final String nome; | |
private final int idade; | |
private ExemploC(String nome, int idade) { this.nome = nome; this.idade = idade; } | |
public String getNome() { return nome; } | |
public int getIdade() { return idade; } | |
} | |
LinkedResource<ExemploC> linkedResource = new LinkedResource<>(new ExemploC("BobNelson", 47), "'http://example.com/'+nome+'/'+idade"); | |
TestUtils.assertEqualsJson("{\n" + | |
" \"nome\": \"BobNelson\",\n" + | |
" \"idade\": 47,\n" + | |
" \"_links\": {\n" + | |
" \"self\": {\n" + | |
" \"href\": \"http://example.com/BobNelson/47\"\n" + | |
" }\n" + | |
" }\n" + | |
"}", linkedResource); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment