All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.aeontronix.anypointsdk.auth.AnypointClientCredentialsAuthenticationHandler Maven / Gradle / Ivy

There is a newer version: 1.0.0-beta35
Show newest version
package com.aeontronix.anypointsdk.auth;

import com.aeontronix.commons.URLBuilder;
import com.aeontronix.commons.exception.UnexpectedException;
import com.aeontronix.restclient.RESTClient;
import com.aeontronix.restclient.RESTException;
import com.aeontronix.restclient.RESTResponse;
import com.aeontronix.restclient.ResponseConversionException;
import com.aeontronix.restclient.auth.AuthenticationException;
import com.aeontronix.restclient.json.JsonConvertionException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;

public class AnypointClientCredentialsAuthenticationHandler extends AnypointAuthenticationHandler {
    private String clientId;
    private String clientSecret;
    private LocalDateTime expires;
    private ObjectMapper objectMapper = new ObjectMapper();

    public AnypointClientCredentialsAuthenticationHandler(String clientId, String clientSecret) {
        this.clientId = clientId;
        this.clientSecret = clientSecret;
    }

    @Override
    public boolean isRefreshRequired() {
        return expires == null || LocalDateTime.now().isAfter(expires);
    }

    @Override
    public boolean isRefreshable() {
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void refreshCredential(RESTClient restClient) throws RESTException, AuthenticationException {
        final HashMap payload = new HashMap<>();
        payload.put("grant_type", "client_credentials");
        payload.put("client_id", clientId);
        payload.put("client_secret", clientSecret);
        try (final RESTResponse response = restClient.post(new URLBuilder(anypointBaseUrl)
                        .path("/accounts/api/v2/oauth2/token").toUri())
                .jsonBody(payload).execute()) {
            final Map res = response.toObject(Map.class);
            expires = LocalDateTime.now().plus((Integer) res.get("expires_in"), ChronoUnit.SECONDS);
            setBearerToken((String) res.get("access_token"));
        } catch (IOException e) {
            throw new RESTException(e.getMessage(), e);
        } catch (JsonConvertionException e) {
            throw new UnexpectedException(e);
        } catch (ResponseConversionException e) {
            throw new AuthenticationException("Unable to parse login response: " + e.getMessage(), e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy