<commit_before>package org.vasttrafik.wso2.carbon.apimgt.store.api.clients;

import org.apache.commons.lang3.StringUtils;
import org.vasttrafik.wso2.carbon.apimgt.portal.api.beans.*;
import org.vasttrafik.wso2.carbon.apimgt.portal.api.utils.ResourceBundleAware;
import org.vasttrafik.wso2.carbon.apimgt.store.api.beans.*;
import org.vasttrafik.wso2.carbon.common.api.utils.ResponseUtils;

import javax.ws.rs.BadRequestException;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <NAME> <<EMAIL>>
 */
public final class ProxyClient implements ResourceBundleAware {

    private StoreClient storeClient;

    public ProxyClient(final String username, final String password) {
        storeClient = new StoreClient(username, password);
    }


    /// Security methods

    public OauthData getDefaultApplicationOauthData() {
        //final List<SubscriptionDTO> subscriptionDTOs = storeClient.getAllSubscriptions().subscriptions;
        final List<SubscriptionDTO> subscriptionDTOs = storeClient.getAllSubscriptions().subscriptions.applications;
        for (final SubscriptionDTO subscriptionDTO : subscriptionDTOs) {
            if (Constants.DEFAULT_APPLICATION.equals(subscriptionDTO.name)) {
                return OauthData.valueOf(subscriptionDTO);
            }
        }
        throw new InternalServerErrorException(ResponseUtils.serverError(resourceBundle, 2001L, new Object[][]{{Constants.DEFAULT_APPLICATION}}));
    }

    public OauthData generateDefaultApplicationOauthData(OauthData oauthData) {
        if (oauthData.getToken() != null) {
            final RefreshTokenDTO.Key key = storeClient.refreshToken(
                    oauthData.getToken(),
                    oauthData.getKey(),
                    oauthData.getSecret(),
                    oauthData.getValidityTime()
            ).data.key;
            return oauthData.setToken(key.accessToken).setKey(key.consumerKey).setSecret(key.consumerSecret);
        } else {
            final GenerateApplicationKeyDTO.Key key = storeClient.generateApplicationKey(
                    Constants.DEFAULT_APPLICATION,
                    oauthData.getValidityTime()
            ).data.key;
            return oauthData.setToken(key.accessToken);
        }
    }


    /// Token methods

    public Application generateApplicationToken(final Integer applicationId, final String validityTime) {
        final Application application = getApplication(applicationId);
        if (application.getName().equals(Constants.DEFAULT_APPLICATION)) {
            throw new BadRequestException(ResponseUtils.badRequest(resourceBundle, 2001L, new Object[][]{{Constants.DEFAULT_APPLICATION}}));
        }

        if (application.hasAccessToken()) {
            final RefreshTokenDTO.Key key = storeClient.refreshToken(application.getAccessToken(), application.getConsumerKey(), application.getConsumerSecret(), validityTime).data.key;
            return application.setAccessToken(key.accessToken);
        } else {
            final GenerateApplicationKeyDTO.Key key = storeClient.generateApplicationKey(application.getName(), validityTime).data.key;
            application.setAccessToken(key.accessToken);
            application.setConsumerKey(key.consumerKey);
            application.setConsumerSecret(key.consumerSecret);
            return application;
        }
    }


    /// API methods

    public List<API> getAPIs(final String query) {
        final List<APIDTO> apiDTOs = storeClient.getPaginatedAPIs().apis;

        final List<API> list = new ArrayList<>();
        for (final APIDTO apiDTO : apiDTOs) {
            final API api = API.valueOf(apiDTO);
            if (api.matches(query)) {
                list.add(api);
            }
        }
        return list;
    }

    public API getAPI(final String apiId) {<commit_msg>Added handling for refresh token when access token isn't available.<commit_after>package org.vasttrafik.wso2.carbon.apimgt.store.api.clients;

import org.apache.commons.lang3.StringUtils;
import org.vasttrafik.wso2.carbon.apimgt.portal.api.beans.*;
import org.vasttrafik.wso2.carbon.apimgt.portal.api.utils.ResourceBundleAware;
import org.vasttrafik.wso2.carbon.apimgt.store.api.beans.*;
import org.vasttrafik.wso2.carbon.common.api.utils.ResponseUtils;

import javax.ws.rs.BadRequestException;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.NotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <NAME> <<EMAIL>>
 */
public final class ProxyClient implements ResourceBundleAware {

    private StoreClient storeClient;

    public ProxyClient(final String username, final String password) {
        storeClient = new StoreClient(username, password);
    }


    /// Security methods

    public OauthData getDefaultApplicationOauthData() {
        //final List<SubscriptionDTO> subscriptionDTOs = storeClient.getAllSubscriptions().subscriptions;
        final List<SubscriptionDTO> subscriptionDTOs = storeClient.getAllSubscriptions().subscriptions.applications;
        for (final SubscriptionDTO subscriptionDTO : subscriptionDTOs) {
            if (Constants.DEFAULT_APPLICATION.equals(subscriptionDTO.name)) {
                return OauthData.valueOf(subscriptionDTO);
            }
        }
        throw new InternalServerErrorException(ResponseUtils.serverError(resourceBundle, 2001L, new Object[][]{{Constants.DEFAULT_APPLICATION}}));
    }

    public OauthData generateDefaultApplicationOauthData(OauthData oauthData) {
        if (oauthData.getToken() != null) {
            final RefreshTokenDTO.Key key = storeClient.refreshToken(
                    oauthData.getToken(),
                    oauthData.getKey(),
                    oauthData.getSecret(),
                    oauthData.getValidityTime()
            ).data.key;
            return oauthData.setToken(key.accessToken).setKey(key.consumerKey).setSecret(key.consumerSecret);
        } else {
            final GenerateApplicationKeyDTO.Key key = storeClient.generateApplicationKey(
                    Constants.DEFAULT_APPLICATION,
                    oauthData.getValidityTime()
            ).data.key;
            return oauthData.setToken(key.accessToken);
        }
    }


    /// Token methods

    public Application generateApplicationToken(final Integer applicationId, final String validityTime) {
        final Application application = getApplication(applicationId);
        if (application.getName().equals(Constants.DEFAULT_APPLICATION)) {
            throw new BadRequestException(ResponseUtils.badRequest(resourceBundle, 2001L, new Object[][]{{Constants.DEFAULT_APPLICATION}}));
        }

        if (application.hasAccessToken()) {
            final RefreshTokenDTO.Key key = storeClient.refreshToken(application.getAccessToken(), application.getConsumerKey(), application.getConsumerSecret(), validityTime).data.key;
            return application.setAccessToken(key.accessToken);
        } else if (application.getConsumerKey() != null && application.getConsumerKey() != null) {
        	// Access token has ended up in an erroneous state. Need to refresh it with an empty old access token.
        	final RefreshTokenDTO.Key key = storeClient.refreshToken(null, application.getConsumerKey(), application.getConsumerSecret(), validityTime).data.key;
            return application.setAccessToken(key.accessToken);
        } else {
            final GenerateApplicationKeyDTO.Key key = storeClient.generateApplicationKey(application.getName(), validityTime).data.key;
            application.setAccessToken(key.accessToken);
            application.setConsumerKey(key.consumerKey);
            application.setConsumerSecret(key.consumerSecret);
            return application;
        }
    }


    /// API methods

    public List<API> getAPIs(final String query) {
        final List<APIDTO> apiDTOs = storeClient.getPaginatedAPIs().apis;

        final List<API> list = new ArrayList<>();
        for (final APIDTO apiDTO : apiDTOs) {
            final API api = API.valueOf(apiDTO);
            if (api.matches(query)) {
                list.add(api);
            }
        }
        return list;
    }

    public API getAPI(final String apiId) {
{'fraction_non_alphanumeric': 0.09657469077069458, 'fraction_numerical': 0.003330161750713606, 'mean_word_length': 3.035028790786948, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4631591', 'n_tokens_mistral': 2268, 'n_tokens_neox': 2208, 'n_words': 411}