Advertisement
NLinker

RenewableSpotifyApi wrapper class

Dec 12th, 2016
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. /**
  2.  * {@code RenewableSpotifyApi} is the wrapper over spotify rest api.
  3.  */
  4. public class RenewableSpotifyApi implements Supplier<Api> {
  5.     private final Api               api;
  6.     private       ClientCredentials clientCredentials;
  7.     private       Instant           timeOfReceipt;
  8.  
  9.     public RenewableSpotifyApi(Config config) {
  10.         this.api = Api.builder()
  11.             .clientId(config.getString("spotify.client.id"))
  12.             .clientSecret(config.getString("spotify.client.secret"))
  13.             .build();
  14.     }
  15.  
  16.     synchronized public Api get() {
  17.         if (clientCredentials == null) {
  18.             renewCredentials();
  19.         } else {
  20.             final long passedTime = (Instant.now().toEpochMilli() - timeOfReceipt.toEpochMilli()) / 1000;
  21.             final int expiresIn = clientCredentials.getExpiresIn();
  22.             if (passedTime >= expiresIn) {
  23.                 renewCredentials();
  24.             }
  25.         }
  26.         return api;
  27.     }
  28.  
  29.     private void renewCredentials() {
  30.         try {
  31.             clientCredentials = api.clientCredentialsGrant().build().get();
  32.             timeOfReceipt = Instant.now();
  33.             api.setAccessToken(clientCredentials.getAccessToken());
  34.         } catch (IOException | WebApiException e) {
  35.             throw new RuntimeException(e);
  36.         }
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement