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

com.gettyimages.api.Credentials Maven / Gradle / Ivy

package com.gettyimages.api;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class Credentials {
    private String ClientIdKey = "client_id";
    private String ClientSecretKey = "client_secret";
    private String UsernameKey = "username";
    private String PasswordKey = "password";
    private String ClientCredentialsValue = "client_credentials";
    private String GrantTypeKey = "grant_type";
    private String Oauth2TokenPath = "/oauth2/token";
    private String RefreshTokenKey = "refresh_token";

    private String baseUrl;
    private Token accessToken;

    public String ApiKey;
    public String ApiSecret;
    public CredentialType CredentialType;
    public String RefreshToken;
    public String UserName;
    public String UserPassword;

    private Credentials(String apiKey, String apiSecret, String baseUrl) {
        this.baseUrl = baseUrl;
        CredentialType = CredentialType.ClientCredentials;
        ApiKey = apiKey;
        ApiSecret = apiSecret;
    }

    private Credentials(String apiKey, String apiSecret, String refreshToken, String baseUrl) {
        this.baseUrl = baseUrl;
        CredentialType = CredentialType.RefreshToken;
        ApiKey = apiKey;
        ApiSecret = apiSecret;
        RefreshToken = refreshToken;
    }

    private Credentials(String apiKey, String apiSecret, String userName, String userPassword, String baseUrl) {
        this.baseUrl = baseUrl;
        CredentialType = CredentialType.ResourceOwner;
        ApiKey = apiKey;
        ApiSecret = apiSecret;
        UserName = userName;
        UserPassword = userPassword;
    }

    public static Credentials GetInstance(String apiKey, String apiSecret, String baseUrl) {
        return new Credentials(apiKey, apiSecret, baseUrl);
    }

    public static Credentials GetInstance(String apiKey, String apiSecret, String refreshToken, String baseUrl) {
        return new Credentials(apiKey, apiSecret, refreshToken, baseUrl); //TODO change to accept refresh token
    }

    public static Credentials GetInstance(String apiKey, String apiSecret, String userName, String userPassword,
                                          String baseUrl) {
        return new Credentials(apiKey, apiSecret, userName, userPassword, baseUrl);
    }

    public Token GetAccessToken() throws SdkException {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, -5);

        if (CredentialType != CredentialType.ClientCredentials && CredentialType != CredentialType.ResourceOwner && CredentialType != CredentialType.RefreshToken
                ||
                (accessToken != null && accessToken.getExpiration().compareTo(now.getTime()) >= 0)) {
            return accessToken;
        }

        WebHelper helper = new WebHelper(this, baseUrl);
        String response = PostForm(GetCredentialsDictionary(), Oauth2TokenPath);
        try {
            JSONObject json = (JSONObject) new JSONObject(response);

            accessToken = new Token();

            accessToken.setTokenString(json.getString("access_token"));

            if (CredentialType == CredentialType.ResourceOwner)
                accessToken.setRefreshTokenString(json.getString("refresh_token"));

            Calendar expiration = Calendar.getInstance();
            expiration.add(Calendar.SECOND, json.getInt("expires_in"));
            accessToken.setExpiration(expiration.getTime());

            return accessToken;
        } catch (JSONException e) {
            e.printStackTrace();
            throw new SdkException("Unable to get access token. Probably invalid credentials.");
        }
    }

    public Map GetCredentialsDictionary()
    {
        Map dict = new Hashtable();

        if (!StringHelper.isNullOrEmpty(ApiKey))
        {
            dict.put(ClientIdKey, ApiKey);
        }

        if (!StringHelper.isNullOrEmpty(ApiSecret))
        {
            dict.put(ClientSecretKey, ApiSecret);
        }

        if (!StringHelper.isNullOrEmpty(UserName))
        {
            dict.put(UsernameKey, UserName);
        }

        if (!StringHelper.isNullOrEmpty(UserPassword))
        {
            dict.put(PasswordKey, UserPassword);
        }

        if (!StringHelper.isNullOrEmpty(RefreshToken))
        {
            dict.put(RefreshTokenKey, RefreshToken);
        }

        switch (CredentialType)
        {
            case ClientCredentials:
                dict.put(GrantTypeKey, ClientCredentialsValue);
                break;
            case ResourceOwner:
                dict.put(GrantTypeKey, PasswordKey);
                break;
            case RefreshToken:
                dict.put(GrantTypeKey, RefreshTokenKey);
                break;
        }

        return dict;
    }

    public String PostForm(Map formParameters, String path) {
        try {
            URL url = new URL(baseUrl + path);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url.toString());

            List params = new ArrayList();
            for (Map.Entry entry : formParameters.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            String content = EntityUtils.toString(responseEntity);

            return content;
        } catch (MalformedURLException ex) {
            String s = ex.toString();
        } catch (IOException ex) {
            String s = ex.toString();
        }
        return null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy