<commit_before>/*
 * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * 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
 *
 * 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 org.wso2.carbon.identity.application.mgt.ui;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.consent.mgt.core.model.Purpose;
import org.wso2.carbon.identity.application.common.model.script.xsd.AuthenticationScriptConfig;
import org.wso2.carbon.identity.application.common.model.xsd.ApplicationPermission;
import org.wso2.carbon.identity.application.common.model.xsd.AuthenticationStep;
import org.wso2.carbon.identity.application.common.model.xsd.Claim;
import org.wso2.carbon.identity.application.common.model.xsd.ClaimConfig;
import org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping;
import org.wso2.carbon.identity.application.common.model.xsd.FederatedAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.xsd.IdentityProvider;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.xsd.InboundProvisioningConfig;
import org.wso2.carbon.identity.application.common.model.xsd.JustInTimeProvisioningConfig;
import org.wso2.carbon.identity.application.common.model.xsd.LocalAndOutboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.xsd.LocalAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.xsd.LocalRole;
import org.wso2.carbon.identity.application.common.model.xsd.OutboundProvisioningConfig;
import org.wso2.carbon.identity.application.common.model.xsd.PermissionsAndRoleConfig;
import org.wso2.carbon.identity.application.common.model.xsd.Property;
import org.wso2.carbon.identity.application.common.model.xsd.ProvisioningConnectorConfig;
import org.wso2.carbon.identity.application.common.model.xsd.RequestPathAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.xsd.RoleMapping;
import org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider;
import org.wso2.carbon.identity.application.common.model.xsd.ServiceProviderProperty;
import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants;
import org.wso2.carbon.identity.application.mgt.ui.util.ApplicationMgtUIConstants;
import org.wso2.carbon.identity.base.IdentityConstants;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * UI bean to represent an application.
 */
public class ApplicationBean {

    public static final String AUTH_TYPE_DEFAULT = "default";
    public static final String AUTH_TYPE_LOCAL = "local";
    public static final String AUTH_TYPE_FEDERATED = "federated";
    public static final String AUTH_TYPE_FLOW = "flow";
    public static final String IDP_LOCAL_NAME = "LOCAL";

    public static final String LOCAL_IDP = "wso2carbon-local-idp";
    public static final String DUMB = "dumb";

    private static final String LOGOUT_RETURN_URL = "logoutReturnUrl";

    private ServiceProvider serviceProvider;
    private IdentityProvider[] federatedIdentityProviders;
    private Map<String, IdentityProvider> federatedIdentityProvidersMap = new HashMap<>();
    private List<IdentityProvider> enabledFederatedIdentityProviders;
    private LocalAuthenticatorConfig[] localAuthenticatorConfigs;
    private RequestPathAuthenticatorConfig[] requestPathAuthenticators;
    private Map<String, String> roleMap;
    private Map<String, String> claimMap;
    private Map<String, String> requestedClaims = new HashMap<String, String>();
    private Map<String, String> mandatoryClaims = new HashMap<String, String>();
    private String samlIssuer;
    private String kerberosServiceName;
    private String oauthAppName;
    private String oauthConsumerSecret;
    private String attrConsumServiceIndex;
    private List<String> wstrustEp = new ArrayList<String>(0);
    private String passivests;
    private String passiveSTSWReply;
    private String openid;
    private String[] claimUris;
    private List<String> claimDialectUris;
    private List<InboundAuthenticationRequestConfig> inboundAuthenticationRequestConfigs;
    private List<String> standardInboundAuthTypes;
    private ApplicationPurposes applicationPurposes;
    private Purpose[] sharedPurposes;
    private Map<String, InboundAuthenticationRequestConfig> customInboundAuthenticatorConfigs;

    private static final Log log = LogFactory.getLog(ApplicationBean.class);

    public ApplicationBean() {
        standardInboundAuthTypes = new ArrayList<String>();
        standardInboundAuthTypes.add("oauth2");
        standardInboundAuthTypes.add("wstrust");
        standardInboundAuthTypes.add("samlsso");
        standardInboundAuthTypes.add("openid");
        standardInboundAuthTypes.add("passivests");
    }

    public void reset() {
        serviceProvider = null;
        federatedIdentityProviders = null;
        federatedIdentityProvidersMap.clear();
        localAuthenticatorConfigs = null;
        requestPathAuthenticators = null;
        roleMap = null;
        claimMap = null;
        requestedClaims = new HashMap<String, String>();
        mandatoryClaims = new HashMap<String, String>();
        samlIssuer = null;
        kerberosServiceName = null;
        oauthAppName = null;
        wstrustEp = new ArrayList<String>(0);
        passivests = null;
        passiveSTSWReply = null;
        openid = null;
        oauthConsumerSecret = null;
        attrConsumServiceIndex = null;
        enabledFederatedIdentityProviders = null;
        inboundAuthenticationRequestConfigs = Collections.EMPTY_LIST;
        applicationPurposes = null;
        sharedPurposes = null;
    }

    /**
     * @return
     */
    public ServiceProvider getServiceProvider() {
        return serviceProvider;
    }

    /**
     * @param serviceProvider
     */
    public void setServiceProvider(ServiceProvider serviceProvider) {
        this.serviceProvider = serviceProvider;
    }

    /**
     * @return
     */
    public String getAuthenticationType() {
        return serviceProvider.getLocalAndOutBoundAuthenticationConfig().getAuthenticationType();
    }

    /**
     * @param type
     */
    public void setAuthenticationType(String type) {
        serviceProvider.getLocalAndOutBoundAuthenticationConfig().setAuthenticationType(type);
    }

    /**
     * @param type
     * @return
     */
    public String getStepZeroAuthenticatorName(String type) {
        if (AUTH_TYPE_LOCAL.equalsIgnoreCase(type)) {
            if (serviceProvider.getLocalAndOutBoundAuthenticationConfig().getAuthenticationSteps() != null
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps().length > 0
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getLocalAuthenticatorConfigs() != null
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getLocalAuthenticatorConfigs()[0] != null) {
                return serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                        .getAuthenticationSteps()[0].getLocalAuthenticatorConfigs()[0].getName();
            }
        }

        if (AUTH_TYPE_FEDERATED.equalsIgnoreCase(type)) {
            if (serviceProvider.getLocalAndOutBoundAuthenticationConfig().getAuthenticationSteps() != null
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps().length > 0
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getFederatedIdentityProviders() != null
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getFederatedIdentityProviders().length > 0
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getFederatedIdentityProviders()[0] != null) {
                return serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                        .getAuthenticationSteps()[0].getFederatedIdentityProviders()[0]
                        .getIdentityProviderName();
            }
        }

        return null;
    }

    public void setStepZeroAuthenticatorName(String type, String name) {
        if (AUTH_TYPE_LOCAL.equalsIgnoreCase(type)) {
            LocalAuthenticatorConfig localAuthenticator = new LocalAuthenticatorConfig();
            localAuthenticator.setName(name);
            AuthenticationStep authStep = new AuthenticationStep();
            authStep.setLocalAuthenticatorConfigs(new LocalAuthenticatorConfig[]{localAuthenticator});

        }

    }

    /**
     * @return
     */
    public IdentityProvider[] getFederatedIdentityProviders() {
        return federatedIdentityProviders;
    }

    /**
     * @param federatedIdentityProviders
     */
    public void setFederatedIdentityProviders(IdentityProvider[] federatedIdentityProviders) {
        this.federatedIdentityProviders = federatedIdentityProviders;
        if (federatedIdentityProviders != null) {
            federatedIdentityProvidersMap.clear();
            for (IdentityProvider identityProvider : federatedIdentityProviders) {
                federatedIdentityProvidersMap.put(identityProvider.getIdentityProviderName(), identityProvider);
            }
        }
    }

    public List<IdentityProvider> getEnabledFederatedIdentityProviders() {
        if (enabledFederatedIdentityProviders != null) {
            return enabledFederatedIdentityProviders;
        }
        if (federatedIdentityProviders != null && federatedIdentityProviders.length > 0) {
            enabledFederatedIdentityProviders = new ArrayList<IdentityProvider>();
            for (IdentityProvider idp : federatedIdentityProviders) {
                if (idp.getEnable()) {
                    FederatedAuthenticatorConfig[] fedAuthConfigs = idp.getFederatedAuthenticatorConfigs();
                    if (fedAuthConfigs != null && fedAuthConfigs.length > 0) {
                        for (FederatedAuthenticatorConfig config : fedAuthConfigs) {
                            if (config.getEnabled()) {
                                enabledFederatedIdentityProviders.add(idp);
                                break;
                            }
                        }
                    }
                }
            }
        }
        return enabledFederatedIdentityProviders;
    }

    /**
     * @return
     */
    public LocalAuthenticatorConfig[] getLocalAuthenticatorConfigs() {
        return localAuthenticatorConfigs;
    }

    /**
     * @param localAuthenticatorConfigs
     */
    public void setLocalAuthenticatorConfigs(LocalAuthenticatorConfig[] localAuthenticatorConfigs) {
        this.localAuthenticatorConfigs = localAuthenticatorConfigs;
    }

    /**
     * @return
     */
    public RequestPathAuthenticatorConfig[] getRequestPathAuthenticators() {
        return requestPathAuthenticators;
    }

    /**
     * @param requestPathAuthenticators
     */
    public void setRequestPathAuthenticators(
            RequestPathAuthenticatorConfig[] requestPathAuthenticators) {
        this.requestPathAuthenticators = requestPathAuthenticators;
    }

    /**
     * @return
     */
    public List<String> getPermissions() {

        List<String> permList = new ArrayList<String>();

        if (serviceProvider != null && serviceProvider.getPermissionAndRoleConfig() != null) {
            PermissionsAndRoleConfig permissionAndRoleConfig = serviceProvider
                    .getPermissionAndRoleConfig();
            if (permissionAndRoleConfig != null) {
                ApplicationPermission[] permissions = permissionAndRoleConfig.getPermissions();
                if (permissions != null && permissions.length > 0) {
                    for (int i = 0; i < permissions.length; i++) {
                        if (permissions[i] != null) {
                            permList.add(permissions[i].getValue());
                        }
                    }
                }
            }

        }

        return permList;
    }

    /**
     * @param permissions
     */
    public void setPermissions(String[] permissions) {
        ApplicationPermission[] applicationPermission = new ApplicationPermission[permissions.length];
        for (int i = 0; i < permissions.length; i++) {
            ApplicationPermission appPermission = new ApplicationPermission();
            appPermission.setValue(permissions[i]);
        }
        serviceProvider.getPermissionAndRoleConfig().setPermissions(applicationPermission);
    }

    /**
     * @return
     */
    public String getRoleClaimUri() {
        if (serviceProvider.getClaimConfig() != null) {
            return serviceProvider.getClaimConfig().getRoleClaimURI();
        } else {
            return null;
        }
    }

    /**
     * @param roleClaimUri
     */
    public void setRoleClaimUri(String roleClaimUri) {

        if (roleClaimUri != null) {
            if (serviceProvider.getClaimConfig() != null) {
                serviceProvider.getClaimConfig().setRoleClaimURI(roleClaimUri);
            } else {
                ClaimConfig claimConfig = new ClaimConfig();
                claimConfig.setRoleClaimURI(roleClaimUri);
                serviceProvider.setClaimConfig(claimConfig);
            }
        }
    }

    /**
     * @return
     */
    public String getUserClaimUri() {
        if (serviceProvider.getClaimConfig() != null) {
            return serviceProvider.getClaimConfig().getUserClaimURI();
        } else {
            return null;
        }
    }

    /**
     * @param userClaimUri
     */
    public void setUserClaimUri(String userClaimUri) {

        if (userClaimUri != null) {
            if (serviceProvider.getClaimConfig() != null) {
                serviceProvider.getClaimConfig().setUserClaimURI(userClaimUri);
            } else {
                ClaimConfig claimConfig = new ClaimConfig();
                claimConfig.setUserClaimURI(userClaimUri);
                serviceProvider.setClaimConfig(claimConfig);
            }
        }
    }

    /**
     * @return
     */
    public Map<String, String> getRoleMapping() {

        if (serviceProvider.getPermissionAndRoleConfig() == null) {
            return new HashMap<String, String>();
        }

        RoleMapping[] roleMapping = serviceProvider.getPermissionAndRoleConfig().getRoleMappings();

        if (roleMap != null && roleMapping != null && (roleMapping.length == roleMap.size())) {
            return roleMap;
        }

        roleMap = new HashMap<String, String>();

        if (roleMapping != null) {
            for (int i = 0; i < roleMapping.length; i++) {
                roleMap.put(roleMapping[i].getLocalRole().getLocalRoleName(),
                        roleMapping[i].getRemoteRole());
            }
        }

        return roleMap;
    }

    /**
     * @param spRole
     * @param localRole
     */
    public void addRoleMapping(String spRole, String localRole) {
        roleMap.put(localRole, spRole);
    }

    /**
     * @return
     */
    public Map<String, String> getClaimMapping() {

        if (serviceProvider.getClaimConfig() == null) {
            return new HashMap<String, String>();
        }

        ClaimMapping[] claimMapping = serviceProvider.getClaimConfig().getClaimMappings();

        if (claimMap != null && claimMapping != null && (claimMapping.length == claimMap.size())) {
            return claimMap;
        }

        claimMap = new HashMap<String, String>();

        if (claimMapping != null) {
            for (int i = 0; i < claimMapping.length; i++) {
                if (claimMapping[i] != null && claimMapping[i].getRemoteClaim() != null
                        && claimMapping[i].getLocalClaim() != null) {
                    claimMap.put(claimMapping[i].getLocalClaim().getClaimUri(), claimMapping[i]
                            .getRemoteClaim().getClaimUri());
                    if (claimMapping[i].getRequested()) {
                        requestedClaims.put(claimMapping[i].getRemoteClaim().getClaimUri(), "true");
                    } else {
                        requestedClaims
                                .put(claimMapping[i].getRemoteClaim().getClaimUri(), "false");
                    }

                    if (claimMapping[i].getMandatory()) {
                        mandatoryClaims.put(claimMapping[i].getRemoteClaim().getClaimUri(), "true");
                    } else {
                        mandatoryClaims
                                .put(claimMapping[i].getRemoteClaim().getClaimUri(), "false");
                    }
                }
            }
        }

        return claimMap;
    }

    /**
     * Is Local Claims Selected
     *
     * @return
     */
    public boolean isLocalClaimsSelected() {
        if (serviceProvider.getClaimConfig() != null) {
            return serviceProvider.getClaimConfig().getLocalClaimDialect();
        }
        return true;
    }

    public boolean isAlwaysSendMappedLocalSubjectId() {
        if (serviceProvider.getClaimConfig() != null) {
            return serviceProvider.getClaimConfig().getAlwaysSendMappedLocalSubjectId();
        }
        return false;
    }

    public boolean isAlwaysSendBackAuthenticatedListOfIdPs() {
        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().
                    getAlwaysSendBackAuthenticatedListOfIdPs();
        }
        return false;
    }

    public boolean isUseTenantDomainInLocalSubjectIdentifier() {
        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().
                    getUseTenantDomainInLocalSubjectIdentifier();
        }
        return false;
    }

    public boolean isUseUserstoreDomainInLocalSubjectIdentifier() {
        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().
                    getUseUserstoreDomainInLocalSubjectIdentifier();
        }
        return false;
    }

    /**
     * Returns whether consent needs to be skipped for this service provider.
     *
     * @return true of consent is skipped, false otherwise.
     */
    public boolean isSkipConsent() {

        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSkipConsent();
        }
        return false;
    }

    /**
     * Returns whether logout consent needs to be skipped for this service provider.
     *
     * @return true of logout consent is skipped, false otherwise.
     */
    public boolean isSkipLogoutConsent() {

        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSkipLogoutConsent();
        }
        return false;
    }

    public boolean isEnableAuthorization() {

        return serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null &&
               serviceProvider.getLocalAndOutBoundAuthenticationConfig().getEnableAuthorization();

    }

    public String getSubjectClaimUri() {
        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSubjectClaimUri();
        }
        return null;
    }

    public String getAttributeConsumingServiceIndex() {
        if (attrConsumServiceIndex != null) {
            return attrConsumServiceIndex;
        }

        InboundAuthenticationRequestConfig[] authRequests = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();
        if (authRequests != null) {
            for (InboundAuthenticationRequestConfig request : authRequests) {
                if ("samlsso".equalsIgnoreCase(request.getInboundAuthType())) {
                    if (request.getProperties() != null) {
                        for (Property property : request.getProperties()) {
                            if ("attrConsumServiceIndex".equalsIgnoreCase(property.getName())) {
                                attrConsumServiceIndex = property.getValue();
                                return attrConsumServiceIndex;
                            }
                        }
                    }
                    return null;
                }
            }
        }
        return null;
    }

    public void setAttributeConsumingServiceIndex(String attrConsumServiceIndex) {
        this.attrConsumServiceIndex = attrConsumServiceIndex;
    }

    public String getOauthConsumerSecret() {
        if (oauthConsumerSecret != null) {
            return oauthConsumerSecret;
        }

        InboundAuthenticationRequestConfig[] authRequests = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();
        if (authRequests != null) {
            for (InboundAuthenticationRequestConfig request : authRequests) {
                if ("oauth2".equalsIgnoreCase(request.getInboundAuthType())) {
                    if (request.getProperties() != null) {
                        for (Property property : request.getProperties()) {
                            if ("oauthConsumerSecret".equalsIgnoreCase(property.getName())) {
                                oauthConsumerSecret = property.getValue();
                                return oauthConsumerSecret;
                            }
                        }
                    }
                    return null;
                }
            }
        }
        return null;
    }

    public void setOauthConsumerSecret(String oauthConsumerSecret) {
        this.oauthConsumerSecret = oauthConsumerSecret;
    }

    /**
     * @return
     */
    public String getSAMLIssuer() {

        if (samlIssuer != null) {
            return samlIssuer;
        }

        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {
                if ("samlsso".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    samlIssuer = authRequest[i].getInboundAuthKey();
                    break;
                }
            }
        }

        return samlIssuer;
    }

    public String getKerberosServiceName() {
        if (kerberosServiceName != null) {
            return kerberosServiceName;
        }
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {
                if ("kerberos".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    kerberosServiceName = authRequest[i].getInboundAuthKey();
                    break;
                }
            }
        }
        return kerberosServiceName;
    }

    public void setKerberosServiceName(String kerberosServiceName) {
        this.kerberosServiceName = kerberosServiceName;
    }

    /**
     * @param issuerName
     */
    public void setSAMLIssuer(String issuerName) {
        this.samlIssuer = issuerName;
    }

    public void deleteSAMLIssuer() {
        this.samlIssuer = null;
        this.attrConsumServiceIndex = null;
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null && authRequest.length > 0) {
            List<InboundAuthenticationRequestConfig> tempAuthRequest =
                    new ArrayList<InboundAuthenticationRequestConfig>();
            for (int i = 0; i < authRequest.length; i++) {
                if ("samlsso".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    continue;
                }
                tempAuthRequest.add(authRequest[i]);
            }
            if (CollectionUtils.isNotEmpty(tempAuthRequest)) {
                serviceProvider
                        .getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(
                                tempAuthRequest
                                        .toArray(new InboundAuthenticationRequestConfig[tempAuthRequest
                                                .size()]));
            } else {
                serviceProvider.getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(null);
            }
        }
    }

    /**
     * @param oauthAppName
     */
    public void setOIDCAppName(String oauthAppName) {
        this.oauthAppName = oauthAppName;
    }

    public void deleteOauthApp() {
        this.oauthAppName = null;
        this.oauthConsumerSecret = null;
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null && authRequest.length > 0) {
            List<InboundAuthenticationRequestConfig> tempAuthRequest =
                    new ArrayList<InboundAuthenticationRequestConfig>();
            for (int i = 0; i < authRequest.length; i++) {
                if ("oauth2".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    continue;
                }
                tempAuthRequest.add(authRequest[i]);
            }
            if (CollectionUtils.isNotEmpty(tempAuthRequest)) {
                serviceProvider
                        .getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(
                                tempAuthRequest
                                        .toArray(new InboundAuthenticationRequestConfig[tempAuthRequest
                                                .size()]));
            } else {
                serviceProvider.getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(null);
            }
        }
    }

    public void deleteKerberosApp() {
        this.kerberosServiceName = null;
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null && authRequest.length > 0) {
            List<InboundAuthenticationRequestConfig> tempAuthRequest =
                    new ArrayList<InboundAuthenticationRequestConfig>();
            for (int i = 0; i < authRequest.length; i++) {
                if ("kerberos".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    continue;
                }
                tempAuthRequest.add(authRequest[i]);
            }
            if (CollectionUtils.isNotEmpty(tempAuthRequest)) {
                serviceProvider
                        .getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(
                                tempAuthRequest
                                        .toArray(new InboundAuthenticationRequestConfig[tempAuthRequest
                                                .size()]));
            } else {
                serviceProvider.getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(null);
            }
        }
    }

    public void deleteWstrustEp() {
        this.wstrustEp = null;
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null && authRequest.length > 0) {
            List<InboundAuthenticationRequestConfig> tempAuthRequest =
                    new ArrayList<InboundAuthenticationRequestConfig>();
            for (int i = 0; i < authRequest.length; i++) {
                if ("wstrust".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    continue;
                }
                tempAuthRequest.add(authRequest[i]);
            }
            if (CollectionUtils.isNotEmpty(tempAuthRequest)) {
                serviceProvider
                        .getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(
                                tempAuthRequest
                                        .toArray(new InboundAuthenticationRequestConfig[tempAuthRequest
                                                .size()]));
            } else {
                serviceProvider.getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(null);
            }
        }
    }

    /**
     * @return
     */
    public String getOIDCClientId() {

        if (oauthAppName != null) {
            return oauthAppName;
        }

        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {
                if ("oauth2".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    oauthAppName = authRequest[i].getInboundAuthKey();
                    break;
                }
            }
        }

        return oauthAppName;
    }

    /**
     * @return
     */
    public String getOpenIDRealm() {

        if (openid != null) {
            return openid;
        }

        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();
        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {
                if ("openid".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    openid = authRequest[i].getInboundAuthKey();
                    break;
                }
            }
        }
        return openid;
    }

    /**
     * @return
     */
    public String getWstrustSP() {
        List<String> wsTrustEps = getAllWsTrustSPs();
        if (CollectionUtils.isNotEmpty(wsTrustEps)) {
            return getAllWsTrustSPs().get(0);
        }
        else {
            return null;
        }
    }

    /**
     * @return
     */
    public List<String> getAllWsTrustSPs() {
        if (CollectionUtils.isNotEmpty(wstrustEp)) {
            return wstrustEp;
        }
        else {
            wstrustEp = new ArrayList<>(0);
        }

        InboundAuthenticationRequestConfig[] authRequests = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();
        if (authRequests != null) {
            Arrays.stream(authRequests).filter(authRequest ->
                    (authRequest.getInboundAuthType() != null && !authRequest.getInboundAuthType().isEmpty()
                            && "wstrust".equalsIgnoreCase(authRequest.getInboundAuthType())))
                    .forEach(authRequest -> wstrustEp.add(authRequest.getInboundAuthKey()));
        }

        return wstrustEp;
    }

    /**
     * @return
     */
    public String getPassiveSTSRealm() {

        if (passivests != null) {
            return passivests;
        }

        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {<commit_msg>Corrected styling issues<commit_after>/*
 * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * 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
 *
 * 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 org.wso2.carbon.identity.application.mgt.ui;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.consent.mgt.core.model.Purpose;
import org.wso2.carbon.identity.application.common.model.script.xsd.AuthenticationScriptConfig;
import org.wso2.carbon.identity.application.common.model.xsd.ApplicationPermission;
import org.wso2.carbon.identity.application.common.model.xsd.AuthenticationStep;
import org.wso2.carbon.identity.application.common.model.xsd.Claim;
import org.wso2.carbon.identity.application.common.model.xsd.ClaimConfig;
import org.wso2.carbon.identity.application.common.model.xsd.ClaimMapping;
import org.wso2.carbon.identity.application.common.model.xsd.FederatedAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.xsd.IdentityProvider;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.xsd.InboundProvisioningConfig;
import org.wso2.carbon.identity.application.common.model.xsd.JustInTimeProvisioningConfig;
import org.wso2.carbon.identity.application.common.model.xsd.LocalAndOutboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.xsd.LocalAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.xsd.LocalRole;
import org.wso2.carbon.identity.application.common.model.xsd.OutboundProvisioningConfig;
import org.wso2.carbon.identity.application.common.model.xsd.PermissionsAndRoleConfig;
import org.wso2.carbon.identity.application.common.model.xsd.Property;
import org.wso2.carbon.identity.application.common.model.xsd.ProvisioningConnectorConfig;
import org.wso2.carbon.identity.application.common.model.xsd.RequestPathAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.xsd.RoleMapping;
import org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider;
import org.wso2.carbon.identity.application.common.model.xsd.ServiceProviderProperty;
import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants;
import org.wso2.carbon.identity.application.mgt.ui.util.ApplicationMgtUIConstants;
import org.wso2.carbon.identity.base.IdentityConstants;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * UI bean to represent an application.
 */
public class ApplicationBean {

    public static final String AUTH_TYPE_DEFAULT = "default";
    public static final String AUTH_TYPE_LOCAL = "local";
    public static final String AUTH_TYPE_FEDERATED = "federated";
    public static final String AUTH_TYPE_FLOW = "flow";
    public static final String IDP_LOCAL_NAME = "LOCAL";

    public static final String LOCAL_IDP = "wso2carbon-local-idp";
    public static final String DUMB = "dumb";

    private static final String LOGOUT_RETURN_URL = "logoutReturnUrl";

    private ServiceProvider serviceProvider;
    private IdentityProvider[] federatedIdentityProviders;
    private Map<String, IdentityProvider> federatedIdentityProvidersMap = new HashMap<>();
    private List<IdentityProvider> enabledFederatedIdentityProviders;
    private LocalAuthenticatorConfig[] localAuthenticatorConfigs;
    private RequestPathAuthenticatorConfig[] requestPathAuthenticators;
    private Map<String, String> roleMap;
    private Map<String, String> claimMap;
    private Map<String, String> requestedClaims = new HashMap<String, String>();
    private Map<String, String> mandatoryClaims = new HashMap<String, String>();
    private String samlIssuer;
    private String kerberosServiceName;
    private String oauthAppName;
    private String oauthConsumerSecret;
    private String attrConsumServiceIndex;
    private List<String> wstrustEp = new ArrayList<String>(0);
    private String passivests;
    private String passiveSTSWReply;
    private String openid;
    private String[] claimUris;
    private List<String> claimDialectUris;
    private List<InboundAuthenticationRequestConfig> inboundAuthenticationRequestConfigs;
    private List<String> standardInboundAuthTypes;
    private ApplicationPurposes applicationPurposes;
    private Purpose[] sharedPurposes;
    private Map<String, InboundAuthenticationRequestConfig> customInboundAuthenticatorConfigs;

    private static final Log log = LogFactory.getLog(ApplicationBean.class);

    public ApplicationBean() {
        standardInboundAuthTypes = new ArrayList<String>();
        standardInboundAuthTypes.add("oauth2");
        standardInboundAuthTypes.add("wstrust");
        standardInboundAuthTypes.add("samlsso");
        standardInboundAuthTypes.add("openid");
        standardInboundAuthTypes.add("passivests");
    }

    public void reset() {
        serviceProvider = null;
        federatedIdentityProviders = null;
        federatedIdentityProvidersMap.clear();
        localAuthenticatorConfigs = null;
        requestPathAuthenticators = null;
        roleMap = null;
        claimMap = null;
        requestedClaims = new HashMap<String, String>();
        mandatoryClaims = new HashMap<String, String>();
        samlIssuer = null;
        kerberosServiceName = null;
        oauthAppName = null;
        wstrustEp = new ArrayList<String>(0);
        passivests = null;
        passiveSTSWReply = null;
        openid = null;
        oauthConsumerSecret = null;
        attrConsumServiceIndex = null;
        enabledFederatedIdentityProviders = null;
        inboundAuthenticationRequestConfigs = Collections.EMPTY_LIST;
        applicationPurposes = null;
        sharedPurposes = null;
    }

    /**
     * @return
     */
    public ServiceProvider getServiceProvider() {
        return serviceProvider;
    }

    /**
     * @param serviceProvider
     */
    public void setServiceProvider(ServiceProvider serviceProvider) {
        this.serviceProvider = serviceProvider;
    }

    /**
     * @return
     */
    public String getAuthenticationType() {
        return serviceProvider.getLocalAndOutBoundAuthenticationConfig().getAuthenticationType();
    }

    /**
     * @param type
     */
    public void setAuthenticationType(String type) {
        serviceProvider.getLocalAndOutBoundAuthenticationConfig().setAuthenticationType(type);
    }

    /**
     * @param type
     * @return
     */
    public String getStepZeroAuthenticatorName(String type) {
        if (AUTH_TYPE_LOCAL.equalsIgnoreCase(type)) {
            if (serviceProvider.getLocalAndOutBoundAuthenticationConfig().getAuthenticationSteps() != null
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps().length > 0
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getLocalAuthenticatorConfigs() != null
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getLocalAuthenticatorConfigs()[0] != null) {
                return serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                        .getAuthenticationSteps()[0].getLocalAuthenticatorConfigs()[0].getName();
            }
        }

        if (AUTH_TYPE_FEDERATED.equalsIgnoreCase(type)) {
            if (serviceProvider.getLocalAndOutBoundAuthenticationConfig().getAuthenticationSteps() != null
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps().length > 0
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getFederatedIdentityProviders() != null
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getFederatedIdentityProviders().length > 0
                    && serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                    .getAuthenticationSteps()[0].getFederatedIdentityProviders()[0] != null) {
                return serviceProvider.getLocalAndOutBoundAuthenticationConfig()
                        .getAuthenticationSteps()[0].getFederatedIdentityProviders()[0]
                        .getIdentityProviderName();
            }
        }

        return null;
    }

    public void setStepZeroAuthenticatorName(String type, String name) {
        if (AUTH_TYPE_LOCAL.equalsIgnoreCase(type)) {
            LocalAuthenticatorConfig localAuthenticator = new LocalAuthenticatorConfig();
            localAuthenticator.setName(name);
            AuthenticationStep authStep = new AuthenticationStep();
            authStep.setLocalAuthenticatorConfigs(new LocalAuthenticatorConfig[]{localAuthenticator});

        }

    }

    /**
     * @return
     */
    public IdentityProvider[] getFederatedIdentityProviders() {
        return federatedIdentityProviders;
    }

    /**
     * @param federatedIdentityProviders
     */
    public void setFederatedIdentityProviders(IdentityProvider[] federatedIdentityProviders) {
        this.federatedIdentityProviders = federatedIdentityProviders;
        if (federatedIdentityProviders != null) {
            federatedIdentityProvidersMap.clear();
            for (IdentityProvider identityProvider : federatedIdentityProviders) {
                federatedIdentityProvidersMap.put(identityProvider.getIdentityProviderName(), identityProvider);
            }
        }
    }

    public List<IdentityProvider> getEnabledFederatedIdentityProviders() {
        if (enabledFederatedIdentityProviders != null) {
            return enabledFederatedIdentityProviders;
        }
        if (federatedIdentityProviders != null && federatedIdentityProviders.length > 0) {
            enabledFederatedIdentityProviders = new ArrayList<IdentityProvider>();
            for (IdentityProvider idp : federatedIdentityProviders) {
                if (idp.getEnable()) {
                    FederatedAuthenticatorConfig[] fedAuthConfigs = idp.getFederatedAuthenticatorConfigs();
                    if (fedAuthConfigs != null && fedAuthConfigs.length > 0) {
                        for (FederatedAuthenticatorConfig config : fedAuthConfigs) {
                            if (config.getEnabled()) {
                                enabledFederatedIdentityProviders.add(idp);
                                break;
                            }
                        }
                    }
                }
            }
        }
        return enabledFederatedIdentityProviders;
    }

    /**
     * @return
     */
    public LocalAuthenticatorConfig[] getLocalAuthenticatorConfigs() {
        return localAuthenticatorConfigs;
    }

    /**
     * @param localAuthenticatorConfigs
     */
    public void setLocalAuthenticatorConfigs(LocalAuthenticatorConfig[] localAuthenticatorConfigs) {
        this.localAuthenticatorConfigs = localAuthenticatorConfigs;
    }

    /**
     * @return
     */
    public RequestPathAuthenticatorConfig[] getRequestPathAuthenticators() {
        return requestPathAuthenticators;
    }

    /**
     * @param requestPathAuthenticators
     */
    public void setRequestPathAuthenticators(
            RequestPathAuthenticatorConfig[] requestPathAuthenticators) {
        this.requestPathAuthenticators = requestPathAuthenticators;
    }

    /**
     * @return
     */
    public List<String> getPermissions() {

        List<String> permList = new ArrayList<String>();

        if (serviceProvider != null && serviceProvider.getPermissionAndRoleConfig() != null) {
            PermissionsAndRoleConfig permissionAndRoleConfig = serviceProvider
                    .getPermissionAndRoleConfig();
            if (permissionAndRoleConfig != null) {
                ApplicationPermission[] permissions = permissionAndRoleConfig.getPermissions();
                if (permissions != null && permissions.length > 0) {
                    for (int i = 0; i < permissions.length; i++) {
                        if (permissions[i] != null) {
                            permList.add(permissions[i].getValue());
                        }
                    }
                }
            }

        }

        return permList;
    }

    /**
     * @param permissions
     */
    public void setPermissions(String[] permissions) {
        ApplicationPermission[] applicationPermission = new ApplicationPermission[permissions.length];
        for (int i = 0; i < permissions.length; i++) {
            ApplicationPermission appPermission = new ApplicationPermission();
            appPermission.setValue(permissions[i]);
        }
        serviceProvider.getPermissionAndRoleConfig().setPermissions(applicationPermission);
    }

    /**
     * @return
     */
    public String getRoleClaimUri() {
        if (serviceProvider.getClaimConfig() != null) {
            return serviceProvider.getClaimConfig().getRoleClaimURI();
        } else {
            return null;
        }
    }

    /**
     * @param roleClaimUri
     */
    public void setRoleClaimUri(String roleClaimUri) {

        if (roleClaimUri != null) {
            if (serviceProvider.getClaimConfig() != null) {
                serviceProvider.getClaimConfig().setRoleClaimURI(roleClaimUri);
            } else {
                ClaimConfig claimConfig = new ClaimConfig();
                claimConfig.setRoleClaimURI(roleClaimUri);
                serviceProvider.setClaimConfig(claimConfig);
            }
        }
    }

    /**
     * @return
     */
    public String getUserClaimUri() {
        if (serviceProvider.getClaimConfig() != null) {
            return serviceProvider.getClaimConfig().getUserClaimURI();
        } else {
            return null;
        }
    }

    /**
     * @param userClaimUri
     */
    public void setUserClaimUri(String userClaimUri) {

        if (userClaimUri != null) {
            if (serviceProvider.getClaimConfig() != null) {
                serviceProvider.getClaimConfig().setUserClaimURI(userClaimUri);
            } else {
                ClaimConfig claimConfig = new ClaimConfig();
                claimConfig.setUserClaimURI(userClaimUri);
                serviceProvider.setClaimConfig(claimConfig);
            }
        }
    }

    /**
     * @return
     */
    public Map<String, String> getRoleMapping() {

        if (serviceProvider.getPermissionAndRoleConfig() == null) {
            return new HashMap<String, String>();
        }

        RoleMapping[] roleMapping = serviceProvider.getPermissionAndRoleConfig().getRoleMappings();

        if (roleMap != null && roleMapping != null && (roleMapping.length == roleMap.size())) {
            return roleMap;
        }

        roleMap = new HashMap<String, String>();

        if (roleMapping != null) {
            for (int i = 0; i < roleMapping.length; i++) {
                roleMap.put(roleMapping[i].getLocalRole().getLocalRoleName(),
                        roleMapping[i].getRemoteRole());
            }
        }

        return roleMap;
    }

    /**
     * @param spRole
     * @param localRole
     */
    public void addRoleMapping(String spRole, String localRole) {
        roleMap.put(localRole, spRole);
    }

    /**
     * @return
     */
    public Map<String, String> getClaimMapping() {

        if (serviceProvider.getClaimConfig() == null) {
            return new HashMap<String, String>();
        }

        ClaimMapping[] claimMapping = serviceProvider.getClaimConfig().getClaimMappings();

        if (claimMap != null && claimMapping != null && (claimMapping.length == claimMap.size())) {
            return claimMap;
        }

        claimMap = new HashMap<String, String>();

        if (claimMapping != null) {
            for (int i = 0; i < claimMapping.length; i++) {
                if (claimMapping[i] != null && claimMapping[i].getRemoteClaim() != null
                        && claimMapping[i].getLocalClaim() != null) {
                    claimMap.put(claimMapping[i].getLocalClaim().getClaimUri(), claimMapping[i]
                            .getRemoteClaim().getClaimUri());
                    if (claimMapping[i].getRequested()) {
                        requestedClaims.put(claimMapping[i].getRemoteClaim().getClaimUri(), "true");
                    } else {
                        requestedClaims
                                .put(claimMapping[i].getRemoteClaim().getClaimUri(), "false");
                    }

                    if (claimMapping[i].getMandatory()) {
                        mandatoryClaims.put(claimMapping[i].getRemoteClaim().getClaimUri(), "true");
                    } else {
                        mandatoryClaims
                                .put(claimMapping[i].getRemoteClaim().getClaimUri(), "false");
                    }
                }
            }
        }

        return claimMap;
    }

    /**
     * Is Local Claims Selected
     *
     * @return
     */
    public boolean isLocalClaimsSelected() {
        if (serviceProvider.getClaimConfig() != null) {
            return serviceProvider.getClaimConfig().getLocalClaimDialect();
        }
        return true;
    }

    public boolean isAlwaysSendMappedLocalSubjectId() {
        if (serviceProvider.getClaimConfig() != null) {
            return serviceProvider.getClaimConfig().getAlwaysSendMappedLocalSubjectId();
        }
        return false;
    }

    public boolean isAlwaysSendBackAuthenticatedListOfIdPs() {
        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().
                    getAlwaysSendBackAuthenticatedListOfIdPs();
        }
        return false;
    }

    public boolean isUseTenantDomainInLocalSubjectIdentifier() {
        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().
                    getUseTenantDomainInLocalSubjectIdentifier();
        }
        return false;
    }

    public boolean isUseUserstoreDomainInLocalSubjectIdentifier() {
        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().
                    getUseUserstoreDomainInLocalSubjectIdentifier();
        }
        return false;
    }

    /**
     * Returns whether consent needs to be skipped for this service provider.
     *
     * @return true of consent is skipped, false otherwise.
     */
    public boolean isSkipConsent() {

        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSkipConsent();
        }
        return false;
    }

    /**
     * Returns whether logout consent needs to be skipped for this service provider.
     *
     * @return true of logout consent is skipped, false otherwise.
     */
    public boolean isSkipLogoutConsent() {

        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSkipLogoutConsent();
        }
        return false;
    }

    public boolean isEnableAuthorization() {

        return serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null &&
               serviceProvider.getLocalAndOutBoundAuthenticationConfig().getEnableAuthorization();

    }

    public String getSubjectClaimUri() {
        if (serviceProvider.getLocalAndOutBoundAuthenticationConfig() != null) {
            return serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSubjectClaimUri();
        }
        return null;
    }

    public String getAttributeConsumingServiceIndex() {
        if (attrConsumServiceIndex != null) {
            return attrConsumServiceIndex;
        }

        InboundAuthenticationRequestConfig[] authRequests = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();
        if (authRequests != null) {
            for (InboundAuthenticationRequestConfig request : authRequests) {
                if ("samlsso".equalsIgnoreCase(request.getInboundAuthType())) {
                    if (request.getProperties() != null) {
                        for (Property property : request.getProperties()) {
                            if ("attrConsumServiceIndex".equalsIgnoreCase(property.getName())) {
                                attrConsumServiceIndex = property.getValue();
                                return attrConsumServiceIndex;
                            }
                        }
                    }
                    return null;
                }
            }
        }
        return null;
    }

    public void setAttributeConsumingServiceIndex(String attrConsumServiceIndex) {
        this.attrConsumServiceIndex = attrConsumServiceIndex;
    }

    public String getOauthConsumerSecret() {
        if (oauthConsumerSecret != null) {
            return oauthConsumerSecret;
        }

        InboundAuthenticationRequestConfig[] authRequests = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();
        if (authRequests != null) {
            for (InboundAuthenticationRequestConfig request : authRequests) {
                if ("oauth2".equalsIgnoreCase(request.getInboundAuthType())) {
                    if (request.getProperties() != null) {
                        for (Property property : request.getProperties()) {
                            if ("oauthConsumerSecret".equalsIgnoreCase(property.getName())) {
                                oauthConsumerSecret = property.getValue();
                                return oauthConsumerSecret;
                            }
                        }
                    }
                    return null;
                }
            }
        }
        return null;
    }

    public void setOauthConsumerSecret(String oauthConsumerSecret) {
        this.oauthConsumerSecret = oauthConsumerSecret;
    }

    /**
     * @return
     */
    public String getSAMLIssuer() {

        if (samlIssuer != null) {
            return samlIssuer;
        }

        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {
                if ("samlsso".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    samlIssuer = authRequest[i].getInboundAuthKey();
                    break;
                }
            }
        }

        return samlIssuer;
    }

    public String getKerberosServiceName() {
        if (kerberosServiceName != null) {
            return kerberosServiceName;
        }
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {
                if ("kerberos".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    kerberosServiceName = authRequest[i].getInboundAuthKey();
                    break;
                }
            }
        }
        return kerberosServiceName;
    }

    public void setKerberosServiceName(String kerberosServiceName) {
        this.kerberosServiceName = kerberosServiceName;
    }

    /**
     * @param issuerName
     */
    public void setSAMLIssuer(String issuerName) {
        this.samlIssuer = issuerName;
    }

    public void deleteSAMLIssuer() {
        this.samlIssuer = null;
        this.attrConsumServiceIndex = null;
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null && authRequest.length > 0) {
            List<InboundAuthenticationRequestConfig> tempAuthRequest =
                    new ArrayList<InboundAuthenticationRequestConfig>();
            for (int i = 0; i < authRequest.length; i++) {
                if ("samlsso".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    continue;
                }
                tempAuthRequest.add(authRequest[i]);
            }
            if (CollectionUtils.isNotEmpty(tempAuthRequest)) {
                serviceProvider
                        .getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(
                                tempAuthRequest
                                        .toArray(new InboundAuthenticationRequestConfig[tempAuthRequest
                                                .size()]));
            } else {
                serviceProvider.getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(null);
            }
        }
    }

    /**
     * @param oauthAppName
     */
    public void setOIDCAppName(String oauthAppName) {
        this.oauthAppName = oauthAppName;
    }

    public void deleteOauthApp() {
        this.oauthAppName = null;
        this.oauthConsumerSecret = null;
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null && authRequest.length > 0) {
            List<InboundAuthenticationRequestConfig> tempAuthRequest =
                    new ArrayList<InboundAuthenticationRequestConfig>();
            for (int i = 0; i < authRequest.length; i++) {
                if ("oauth2".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    continue;
                }
                tempAuthRequest.add(authRequest[i]);
            }
            if (CollectionUtils.isNotEmpty(tempAuthRequest)) {
                serviceProvider
                        .getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(
                                tempAuthRequest
                                        .toArray(new InboundAuthenticationRequestConfig[tempAuthRequest
                                                .size()]));
            } else {
                serviceProvider.getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(null);
            }
        }
    }

    public void deleteKerberosApp() {
        this.kerberosServiceName = null;
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null && authRequest.length > 0) {
            List<InboundAuthenticationRequestConfig> tempAuthRequest =
                    new ArrayList<InboundAuthenticationRequestConfig>();
            for (int i = 0; i < authRequest.length; i++) {
                if ("kerberos".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    continue;
                }
                tempAuthRequest.add(authRequest[i]);
            }
            if (CollectionUtils.isNotEmpty(tempAuthRequest)) {
                serviceProvider
                        .getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(
                                tempAuthRequest
                                        .toArray(new InboundAuthenticationRequestConfig[tempAuthRequest
                                                .size()]));
            } else {
                serviceProvider.getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(null);
            }
        }
    }

    public void deleteWstrustEp() {
        this.wstrustEp = null;
        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null && authRequest.length > 0) {
            List<InboundAuthenticationRequestConfig> tempAuthRequest =
                    new ArrayList<InboundAuthenticationRequestConfig>();
            for (int i = 0; i < authRequest.length; i++) {
                if ("wstrust".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    continue;
                }
                tempAuthRequest.add(authRequest[i]);
            }
            if (CollectionUtils.isNotEmpty(tempAuthRequest)) {
                serviceProvider
                        .getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(
                                tempAuthRequest
                                        .toArray(new InboundAuthenticationRequestConfig[tempAuthRequest
                                                .size()]));
            } else {
                serviceProvider.getInboundAuthenticationConfig()
                        .setInboundAuthenticationRequestConfigs(null);
            }
        }
    }

    /**
     * @return
     */
    public String getOIDCClientId() {

        if (oauthAppName != null) {
            return oauthAppName;
        }

        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {
                if ("oauth2".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    oauthAppName = authRequest[i].getInboundAuthKey();
                    break;
                }
            }
        }

        return oauthAppName;
    }

    /**
     * @return
     */
    public String getOpenIDRealm() {

        if (openid != null) {
            return openid;
        }

        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();
        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {
                if ("openid".equalsIgnoreCase(authRequest[i].getInboundAuthType())) {
                    openid = authRequest[i].getInboundAuthKey();
                    break;
                }
            }
        }
        return openid;
    }

    /**
     * @return
     */
    public String getWstrustSP() {
        List<String> wsTrustEps = getAllWsTrustSPs();
        if (CollectionUtils.isNotEmpty(wsTrustEps)) {
            return getAllWsTrustSPs().get(0);
        } else {
            return null;
        }
    }

    /**
     * @return
     */
    public List<String> getAllWsTrustSPs() {
        if (CollectionUtils.isNotEmpty(wstrustEp)) {
            return wstrustEp;
        } else {
            wstrustEp = new ArrayList<>(0);
        }

        InboundAuthenticationRequestConfig[] authRequests = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();
        if (authRequests != null) {
            Arrays.stream(authRequests).filter(authRequest ->
                    (authRequest.getInboundAuthType() != null && !authRequest.getInboundAuthType().isEmpty()
                            && "wstrust".equalsIgnoreCase(authRequest.getInboundAuthType())))
                    .forEach(authRequest -> wstrustEp.add(authRequest.getInboundAuthKey()));
        }

        return wstrustEp;
    }

    /**
     * @return
     */
    public String getPassiveSTSRealm() {

        if (passivests != null) {
            return passivests;
        }

        InboundAuthenticationRequestConfig[] authRequest = serviceProvider
                .getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs();

        if (authRequest != null) {
            for (int i = 0; i < authRequest.length; i++) {
{'fraction_non_alphanumeric': 0.08875908892468425, 'fraction_numerical': 0.002468875607810077, 'mean_word_length': 2.2204392301352596, 'pattern_counts': {'":': 0, '<': 111, '<?xml version=': 0, '>': 109, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 24, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3116642', 'n_tokens_mistral': 16588, 'n_tokens_neox': 15837, 'n_words': 2848}