Skip to content

Instantly share code, notes, and snippets.

@acdcjunior
Created August 3, 2019 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acdcjunior/7beba90486748ee83012a90955a0446b to your computer and use it in GitHub Desktop.
Save acdcjunior/7beba90486748ee83012a90955a0446b to your computer and use it in GitHub Desktop.
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;
}
}
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