<commit_before>/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 * <p>
 * WSO2 Inc. licenses this file to you 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 org.wso2.carbon.apimgt.core.impl;

import feign.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.core.api.IdentityProvider;
import org.wso2.carbon.apimgt.core.auth.SCIMServiceStub;
import org.wso2.carbon.apimgt.core.auth.SCIMServiceStubFactory;
import org.wso2.carbon.apimgt.core.auth.dto.SCIMUser;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes;
import org.wso2.carbon.apimgt.core.exception.IdentityProviderException;
import org.wso2.carbon.apimgt.core.exception.KeyManagementException;
import org.wso2.carbon.apimgt.core.models.API;
import org.wso2.carbon.apimgt.core.models.AccessTokenInfo;
import org.wso2.carbon.apimgt.core.models.AccessTokenRequest;
import org.wso2.carbon.apimgt.core.models.KeyManagerConfiguration;
import org.wso2.carbon.apimgt.core.models.OAuthAppRequest;
import org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo;
import org.wso2.carbon.apimgt.core.models.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * API Manager default implementation of {@link IdentityProvider}
 */
public class DefaultIdentityProviderImpl implements IdentityProvider {

    private static final Logger log = LoggerFactory.getLogger(DefaultIdentityProviderImpl.class);

    private SCIMServiceStub scimServiceStub;
    private static final String FILTER_PREFIX = "displayName Eq ";
    private static final String HOME_EMAIL = "home";

    public DefaultIdentityProviderImpl() throws APIManagementException {
        scimServiceStub = SCIMServiceStubFactory.getSCIMServiceStub();
    }

    protected DefaultIdentityProviderImpl(SCIMServiceStub scimServiceStub) {
        this.scimServiceStub = scimServiceStub;
    }

    @Override
    public List<String> getRolesOfUser(String userId) throws IdentityProviderException {
        List<String> roleNames = new ArrayList<>();
        SCIMUser scimUser = scimServiceStub.getUser(userId);
        if (scimUser != null) {
            List<org.wso2.carbon.apimgt.core.auth.dto.SCIMUser.SCIMUserGroups> roles = scimUser.getGroups();
            if (roles != null) {
                roles.forEach(role -> roleNames.add(role.getDisplay()));
            }
        } else {
            String errorMessage = "User id " + userId + " does not exist in the system.";
            log.error(errorMessage);
            throw new IdentityProviderException(errorMessage, ExceptionCodes.USER_DOES_NOT_EXIST);
        }
        return roleNames;
    }

    @Override
    public boolean isValidRole(String roleName) {
        return scimServiceStub.searchGroups(FILTER_PREFIX + roleName).status() == 200;
    }

    @Override
    public void registerUser(User user) throws IdentityProviderException {
        SCIMUser scimUser = new SCIMUser();
        scimUser.setUsername(user.getUsername());
        scimUser.setPassword(<PASSWORD>());
        scimUser.setName(new SCIMUser.SCIMName(user.getFirstName(), user.getLastName()));
        List<SCIMUser.SCIMUserEmails> emails = new ArrayList<>();
        emails.add(new SCIMUser.SCIMUserEmails(user.getEmail(), HOME_EMAIL, true));
        scimUser.setEmails(emails);
        Response response = scimServiceStub.addUser(scimUser);
        if (response == null || response.status() != 201) {
            String errorMessage = "Error occurred while creating user. "
                    + ((response == null) ? "response is null" : "Status Code: " + response.status() + ' '
                    + response.body().toString());
            log.error(errorMessage);
            throw new IdentityProviderException(errorMessage, ExceptionCodes.USER_CREATION_FAILED);
        }
    }

    @Override
    public OAuthApplicationInfo createApplication(OAuthAppRequest oauthAppRequest) throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().createApplication(oauthAppRequest);
    }

    @Override
    public OAuthApplicationInfo updateApplication(OAuthAppRequest appInfoDTO) throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().updateApplication(appInfoDTO);
    }

    @Override
    public void deleteApplication(String consumerKey) throws KeyManagementException {
        APIManagerFactory.getInstance().getKeyManager().deleteApplication(consumerKey);
    }

    @Override
    public OAuthApplicationInfo retrieveApplication(String consumerKey) throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().retrieveApplication(consumerKey);
    }

    @Override
    public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().getNewApplicationAccessToken(tokenRequest);
    }

    @Override
    public AccessTokenInfo getTokenMetaData(String accessToken) throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().getTokenMetaData(accessToken);
    }

    @Override
    public void revokeLogInAccessToken(AccessTokenRequest tokenRequest) throws KeyManagementException {
        APIManagerFactory.getInstance().getKeyManager().revokeLogInAccessToken(tokenRequest);
    }

    @Override
    public KeyManagerConfiguration getKeyManagerConfiguration() throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().getKeyManagerConfiguration();
    }

    @Override
    public OAuthApplicationInfo mapOAuthApplication(OAuthAppRequest appInfoRequest) throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().mapOAuthApplication(appInfoRequest);
    }

    @Override
    public void loadConfiguration(KeyManagerConfiguration configuration) throws KeyManagementException {
        APIManagerFactory.getInstance().getKeyManager().loadConfiguration(configuration);
    }

    @Override
    public boolean registerNewResource(API api, Map resourceAttributes) throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().registerNewResource(api, resourceAttributes);
    }

    @Override
    public Map getResourceByApiId(String apiId) throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().getResourceByApiId(apiId);
    }

    @Override
    public boolean updateRegisteredResource(API api, Map resourceAttributes) throws KeyManagementException {
        return APIManagerFactory.getInstance().getKeyManager().updateRegisteredResource(api, resourceAttributes);
    }

    @Override
    public void deleteRegisteredResourceByAPIId(String apiID) throws KeyManagementException {
        APIManagerFactory.getInstance().getKeyManager().deleteRegisteredResourceByAPIId(apiID);
    }

    @Override
    public void deleteMappedApplication(String consumerKey) throws KeyManagementException {
        APIManagerFactory.getInstance().getKeyManager().deleteMappedApplication(consumerKey);
    }
}<commit_msg>Extended DefaultIdentityProviderImpl by DefaultKeyManagerImpl<commit_after>/*
 * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 * <p>
 * WSO2 Inc. licenses this file to you 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 org.wso2.carbon.apimgt.core.impl;

import feign.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.core.api.IdentityProvider;
import org.wso2.carbon.apimgt.core.auth.SCIMServiceStub;
import org.wso2.carbon.apimgt.core.auth.SCIMServiceStubFactory;
import org.wso2.carbon.apimgt.core.auth.dto.SCIMUser;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes;
import org.wso2.carbon.apimgt.core.exception.IdentityProviderException;
import org.wso2.carbon.apimgt.core.models.User;

import java.util.ArrayList;
import java.util.List;

/**
 * API Manager default implementation of {@link IdentityProvider}
 */
public class DefaultIdentityProviderImpl extends DefaultKeyManagerImpl implements IdentityProvider {

    private static final Logger log = LoggerFactory.getLogger(DefaultIdentityProviderImpl.class);

    private SCIMServiceStub scimServiceStub;
    private static final String FILTER_PREFIX = "displayName Eq ";
    private static final String HOME_EMAIL = "home";

    public DefaultIdentityProviderImpl() throws APIManagementException {
        scimServiceStub = SCIMServiceStubFactory.getSCIMServiceStub();
    }

    protected DefaultIdentityProviderImpl(SCIMServiceStub scimServiceStub) {
        this.scimServiceStub = scimServiceStub;
    }

    @Override
    public List<String> getRolesOfUser(String userId) throws IdentityProviderException {
        List<String> roleNames = new ArrayList<>();
        SCIMUser scimUser = scimServiceStub.getUser(userId);
        if (scimUser != null) {
            List<org.wso2.carbon.apimgt.core.auth.dto.SCIMUser.SCIMUserGroups> roles = scimUser.getGroups();
            if (roles != null) {
                roles.forEach(role -> roleNames.add(role.getDisplay()));
            }
        } else {
            String errorMessage = "User id " + userId + " does not exist in the system.";
            log.error(errorMessage);
            throw new IdentityProviderException(errorMessage, ExceptionCodes.USER_DOES_NOT_EXIST);
        }
        return roleNames;
    }

    @Override
    public boolean isValidRole(String roleName) {
        return scimServiceStub.searchGroups(FILTER_PREFIX + roleName).status() == 200;
    }

    @Override
    public void registerUser(User user) throws IdentityProviderException {
        SCIMUser scimUser = new SCIMUser();
        scimUser.setUsername(user.getUsername());
        scimUser.setPassword(<PASSWORD>());
        scimUser.setName(new SCIMUser.SCIMName(user.getFirstName(), user.getLastName()));
        List<SCIMUser.SCIMUserEmails> emails = new ArrayList<>();
        emails.add(new SCIMUser.SCIMUserEmails(user.getEmail(), HOME_EMAIL, true));
        scimUser.setEmails(emails);
        Response response = scimServiceStub.addUser(scimUser);
        if (response == null || response.status() != 201) {
            String errorMessage = "Error occurred while creating user. "
                    + ((response == null) ? "response is null" : "Status Code: " + response.status() + ' '
                    + response.body().toString());
            log.error(errorMessage);
            throw new IdentityProviderException(errorMessage, ExceptionCodes.USER_CREATION_FAILED);
        }
    }

}
{'fraction_non_alphanumeric': 0.09176251691474967, 'fraction_numerical': 0.005497293640054127, 'mean_word_length': 3.9643157010915195, 'pattern_counts': {'":': 0, '<': 23, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, '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': '6993671', 'n_tokens_mistral': 3224, 'n_tokens_neox': 3232, 'n_words': 710}