Skip to content

Instantly share code, notes, and snippets.

@rponte
Last active March 26, 2021 23:11
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 rponte/6ff504a793028274395dd6657efa049d to your computer and use it in GitHub Desktop.
Save rponte/6ff504a793028274395dd6657efa049d to your computer and use it in GitHub Desktop.
Decorator simples para cuidar da segurança de forma transparente
public class HowToUse {
public static void main(String[] args) {
MercadoLivreHttpClient client = new MercadoLivreHttpClient();
MercadoLivreHttpClient securedClient = new MercadoLivreSecuredHttpClient(client);
HttpResponse<?> response = securedClient.post(null);
}
}
package br.com.zup.edu;
public class MercadoLivreHttpClient {
public HttpResponse<?> post(HttpRequest<?> request) {
// TODO: consome recurso aqui usando algum HTTP client da vida
// a idéia aqui é que seu código não se preocupe com autorização, com token etc
return null;
}
}
package br.com.zup.edu;
public class MercadoLivreSecuredHttpClient extends MercadoLivreHttpClient { // decorator
private final MercadoLivreHttpClient delegate;
public MercadoLivreSecuredHttpClient(MercadoLivreHttpClient delegate) {
this.delegate = delegate;
}
@Override
public HttpResponse<?> post(HttpRequest<?> request) {
int attemps = 3; // TODO: vc decide aqui
while (attemps != 0) {
try {
request.addHeader("authorization", token()); // adiciona token valido na requisição
return delegate.post(request); // invoca objeto original
} catch(ExpiredTokenException e) {
attemps--;
// TODO: revalida token aqui, substitui e tenta de novo
}
}
throw new ExpiredTokenException("Impossivel concluir a requisição pois token inválido");
}
private String token() {
// TODO: faz tua magica aqui
return "<token-gerado-ou-extraido-do-banco>";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment