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

com.aeontronix.enhancedmule.tools.emclient.authentication.CredentialsProviderAnypointUsernamePasswordImpl Maven / Gradle / Ivy

There is a newer version: 2.0.0-alpha4
Show newest version
/*
 * Copyright (c) Aeontronix 2023
 */

package com.aeontronix.enhancedmule.tools.emclient.authentication;

import com.aeontronix.commons.URLBuilder;
import com.aeontronix.enhancedmule.tools.anypoint.authentication.AuthenticationProviderUsernamePasswordImpl;
import com.aeontronix.enhancedmule.tools.authentication.AnypointUsernamePasswordCredentials;
import com.aeontronix.enhancedmule.tools.authentication.Credentials;
import com.aeontronix.enhancedmule.tools.emclient.EnhancedMuleClient;
import com.aeontronix.restclient.RESTClient;
import com.aeontronix.restclient.RESTException;
import com.aeontronix.restclient.auth.AuthenticationHandler;
import com.aeontronix.restclient.json.JsonConvertionException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CredentialsProviderAnypointUsernamePasswordImpl implements AnypointBearerTokenCredentialsProvider {
    private String username;
    private String password;

    public CredentialsProviderAnypointUsernamePasswordImpl(String username, String password) {
        this.username = username;
        this.password = password;
    }

    @Override
    public Credentials getCredentials() throws IOException {
        return new AnypointUsernamePasswordCredentials(username, password);
    }

    @Override
    public AuthenticationHandler toAuthenticationHandler(RESTClient restClient, String anypointPlatformUrl) {
        return new AuthenticationProviderUsernamePasswordImpl(username, password);
    }

    @Override
    public String getAnypointBearerToken(EnhancedMuleClient emClient) throws IOException {
        try {
            final String loginUrl = new URLBuilder(emClient.getAnypointPlatformUrl()).path("/accounts/login").toString();
            Map loginReq = new HashMap<>();
            loginReq.put("username", username);
            loginReq.put("password", password);
            final Map response = emClient.getRestClient().post(loginUrl).jsonBody(loginReq).executeAndConvertToObject(Map.class);
            final String accessToken = (String) response.get("access_token");
            if (accessToken == null) {
                throw new IOException("No access token returned by anypoint login");
            }
            return accessToken;
        } catch (RESTException | JsonConvertionException e) {
            throw new IOException(e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy