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

com.covisint.platform.oauth.client.token.TokenClientImpl Maven / Gradle / Ivy

/* 
 * Copyright 2015 Covisint
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.covisint.platform.oauth.client.token;

import static com.covisint.platform.oauth.core.Constants.CERTIFICATE;
import static com.covisint.platform.oauth.core.Constants.CLIENT_ID;
import static com.covisint.platform.oauth.core.Constants.GRANT_TYPE;
import static com.covisint.platform.oauth.core.Constants.PUBLIC_KEY;
import static com.covisint.platform.oauth.core.Constants.X509_REQUEST_ATTRIBUTE_NAME;
import static com.covisint.platform.oauth.core.SupportedMediaType.TOKEN_MT;

import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.HttpContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.covisint.core.http.service.client.BaseResourceClient;
import com.covisint.core.http.service.client.ClientException;
import com.covisint.core.http.service.core.Page;
import com.covisint.core.http.service.core.ServiceException;
import com.covisint.core.http.service.core.SortCriteria;
import com.covisint.core.support.constraint.Nonnull;
import com.covisint.core.support.constraint.NotEmpty;
import com.covisint.core.support.constraint.Nullable;
import com.covisint.core.support.primitive.StringSupport;
import com.covisint.platform.oauth.core.token.Token;
import com.damnhandy.uri.template.UriTemplate;
import com.damnhandy.uri.template.VariableExpansionException;
import com.google.common.base.Charsets;
import com.google.common.collect.Multimap;
import com.google.common.net.MediaType;
import com.google.common.util.concurrent.CheckedFuture;

/** Client for reading and updating information about token. */
public class TokenClientImpl extends BaseResourceClient implements TokenClient {

    /** Application id header name. */
    private static final String APPLICATION_ID_HEADER = "application-id";

    /** Media type for the client secret grant type resource. */
    private static final MediaType TOKEN_V1_MEDIA_TYPE = MediaType.parse(TOKEN_MT.value());;

    /** UTF encoding. */
    private static final Charset UTF8 = Charsets.UTF_8;

    /** basic. */
    private static final String BASIC = "Basic ";

    /** Authorization header key. */
    private static final String AUTHORIZATION = "Authorization";

    /** Class logger. */
    private final Logger log = LoggerFactory.getLogger(TokenClientImpl.class);

    /** Collection URI template for the get token end point. */
    private UriTemplate getTokenUriTemplate;

    /** Collection URI template for the get token end point. */
    private UriTemplate postTokenUriTemplate;

    /** The id of the application that will need to authorize calls with these tokens. */
    private String appId;

    /**
     * Sets the URI template for the get token end point.
     * 
     * @param uriTemplate The URI template for the get token end point.
     */
    public void setGetTokenUriTemplate(UriTemplate uriTemplate) {
        getTokenUriTemplate = uriTemplate;
    }

    /**
     * Sets the URI template for the post token end point.
     * 
     * @param uriTemplate The URI template for the post token end point.
     */
    public void setPostTokenUriTemplate(UriTemplate uriTemplate) {
        postTokenUriTemplate = uriTemplate;
    }

    /**
     * Sets the id of the application that will need to authorize calls with these tokens.
     * 
     * @param newAppId The application id to set.
     */
    public void setApplicationId(@Nonnull @NotEmpty String newAppId) {
        appId = newAppId;
    }

    /**
     * create authorization string.
     * 
     * @param clientId the client id.
     * @param clientSecret the client secret.
     * @return authorization string.
     */
    @Nonnull @NotEmpty private String getAuthorization(@Nonnull @NotEmpty String clientId,
            @Nonnull @NotEmpty String clientSecret) {
        String credentials = MessageFormat.format("{0}:{1}", clientId, clientSecret);
        byte[] autorizationBytes = credentials.getBytes(UTF8);
        String authorization = BASIC.concat(new String(Base64.encodeBase64(autorizationBytes), UTF8));

        return authorization;
    }

    /** {@inheritDoc} */
    @Nonnull public CheckedFuture getToken(@Nonnull @NotEmpty String clientId,
            String clientSecret, @Nonnull HttpContext httpContext) {
        return postAccessToken(clientId, clientSecret, httpContext);
    }

    /** {@inheritDoc} */
    @Nonnull public CheckedFuture postAccessToken(@Nonnull @NotEmpty String clientId,
            @Nonnull @NotEmpty String clientSecret, @Nonnull HttpContext httpContext) {
        try {
            final String url = postTokenUriTemplate.expand();
            HttpPost post = new HttpPost(url);
            post.setHeader(AUTHORIZATION, getAuthorization(clientId, clientSecret));
            post.setHeader(GRANT_TYPE, "client_credentials");
            
            if (StringSupport.trimOrNull(appId) != null) {
                post.setHeader(APPLICATION_ID_HEADER, appId);
            }

            return execute(post, TOKEN_V1_MEDIA_TYPE, httpContext);
        } catch (final VariableExpansionException e) {
            log.error("Error occurred while expanding URL template.", e);
            throw new ClientException("Error occurred while expanding URL template.");
        }
    }

    /** {@inheritDoc} */
    @Nonnull public CheckedFuture getToken(@Nonnull @NotEmpty String clientId,
            @Nullable String certificate, @Nullable String publickey, @Nullable String x509RequestAttributeName,
            @Nonnull HttpContext httpContext) {
        try {
            final String url = getTokenUriTemplate.expand();
            HttpGet get = new HttpGet(url);
            get.setHeader(CLIENT_ID, clientId);
            get.setHeader(CERTIFICATE, certificate);
            get.setHeader(PUBLIC_KEY, publickey);
            get.setHeader(X509_REQUEST_ATTRIBUTE_NAME, x509RequestAttributeName);
            get.setHeader(GRANT_TYPE, "certificate");
            return execute(get, TOKEN_V1_MEDIA_TYPE, httpContext);
        } catch (final VariableExpansionException e) {
            log.error("Error occurred while expanding URL template.", e);
            throw new ClientException("Error occurred while expanding URL template.");
        }
    }

    /** {@inheritDoc} */
    @Nonnull public CheckedFuture postAccessToken(@Nonnull @NotEmpty String clientId,
            @Nullable String certificate, @Nullable String publickey, @Nullable String x509RequestAttributeName,
            @Nonnull HttpContext httpContext) {
        try {
            final String url = getTokenUriTemplate.expand();
            HttpPost post = new HttpPost(url);
            post.setHeader(CLIENT_ID, clientId);
            post.setHeader(CERTIFICATE, certificate);
            post.setHeader(PUBLIC_KEY, publickey);
            post.setHeader(X509_REQUEST_ATTRIBUTE_NAME, x509RequestAttributeName);
            post.setHeader(GRANT_TYPE, "certificate");
            return execute(post, TOKEN_V1_MEDIA_TYPE, httpContext);
        } catch (final VariableExpansionException e) {
            log.error("Error occurred while expanding URL template.", e);
            throw new ClientException("Error occurred while expanding URL template.");
        }
    }

    /** {@inheritDoc} */
    public CheckedFuture add(Token resource, HttpContext httpContext) {
        throw new UnsupportedOperationException();
    }

    /** {@inheritDoc} */
    public CheckedFuture delete(String id, HttpContext httpContext) {
        throw new UnsupportedOperationException();
    }

    /** {@inheritDoc} */
    public CheckedFuture get(String id, HttpContext httpContext) {
        throw new UnsupportedOperationException();
    }

    /** {@inheritDoc} */
    public CheckedFuture get(Token resource, HttpContext httpContext) {
        throw new UnsupportedOperationException();
    }

    /** {@inheritDoc} */
    public CheckedFuture persist(Token resource, HttpContext httpContext) {
        throw new UnsupportedOperationException();
    }

    /** {@inheritDoc} */
    public CheckedFuture, ServiceException> search(Multimap searchCriteria,
            SortCriteria sortCriteria, Page page, HttpContext httpContext) {
        throw new UnsupportedOperationException();
    }

    /** {@inheritDoc} */
    public CheckedFuture, ServiceException> search(Multimap searchCriteria,
            SortCriteria sortCriteria, Page page, HttpContext httpContext, MediaType mediaType,
            String searchResourcesEndPoint) {
        throw new UnsupportedOperationException();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy