Newer
Older
fedex-api / src / main / java / io / ljunggren / fedex / api / service / OauthService.java
package io.ljunggren.fedex.api.service;

import java.util.Arrays;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;

import io.ljunggren.fedex.api.authorization.AuthToken;
import io.ljunggren.fedex.api.model.Debug;

public class OauthService extends BaseService {
    
    public OauthService(String domain) {
        super(domain);
    }

    private final String URI = domain + "/oauth/token";
    
    public AuthToken authorize(String clientId, String clientSecret) throws Exception {
        return authorize(clientId, clientSecret, getHttpClient());
    }
    
    public AuthToken authorize(String clientId, String clientSecret, CloseableHttpClient httpClient) throws Exception {
        HttpPost post = new HttpPost(URI);
        List<NameValuePair> parameters = generateParameters(clientId, clientSecret);
        try {
            post.setEntity(new UrlEncodedFormEntity(parameters));
            try (CloseableHttpResponse response = httpClient.execute(post)) {
                String json = getResult(response);
                return parse(json, AuthToken.class);
            }
        } finally {
            httpClient.close();
        }
    }
    
    public Debug debug(String clientId, String clientSecret) throws Exception {
        return debug(clientId, clientSecret, getHttpClient());
    }
    
    public Debug debug(String clientId, String clientSecret, CloseableHttpClient httpClient) throws Exception {
        HttpPost post = new HttpPost(URI);
        List<NameValuePair> parameters = generateParameters(clientId, clientSecret);
        post.setEntity(new UrlEncodedFormEntity(parameters));
    	return debug(post, httpClient);
    }
    
    private List<NameValuePair> generateParameters(String clientId, String clientSecret) {
        return Arrays.asList(new BasicNameValuePair[] {
                new BasicNameValuePair("grant_type", "client_credentials"),
                new BasicNameValuePair("client_id", clientId),
                new BasicNameValuePair("client_secret", clientSecret)
        });
    }

}