Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * {@code RenewableSpotifyApi} is the wrapper over spotify rest api.
- */
- public class RenewableSpotifyApi implements Supplier<Api> {
- private final Api api;
- private ClientCredentials clientCredentials;
- private Instant timeOfReceipt;
- public RenewableSpotifyApi(Config config) {
- this.api = Api.builder()
- .clientId(config.getString("spotify.client.id"))
- .clientSecret(config.getString("spotify.client.secret"))
- .build();
- }
- synchronized public Api get() {
- if (clientCredentials == null) {
- renewCredentials();
- } else {
- final long passedTime = (Instant.now().toEpochMilli() - timeOfReceipt.toEpochMilli()) / 1000;
- final int expiresIn = clientCredentials.getExpiresIn();
- if (passedTime >= expiresIn) {
- renewCredentials();
- }
- }
- return api;
- }
- private void renewCredentials() {
- try {
- clientCredentials = api.clientCredentialsGrant().build().get();
- timeOfReceipt = Instant.now();
- api.setAccessToken(clientCredentials.getAccessToken());
- } catch (IOException | WebApiException e) {
- throw new RuntimeException(e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement