Example usage for org.apache.commons.lang ArrayUtils isNotEmpty

List of usage examples for org.apache.commons.lang ArrayUtils isNotEmpty

Introduction

In this page you can find the example usage for org.apache.commons.lang ArrayUtils isNotEmpty.

Prototype

public static boolean isNotEmpty(boolean[] array) 

Source Link

Document

Checks if an array of primitive booleans is not empty or not null.

Usage

From source file:org.vulpe.controller.struts.interceptor.VulpeUploadInterceptor.java

@Override
public String intercept(final ActionInvocation invocation) throws Exception {
    final VulpeUpload upload = VulpeConfigHelper.getApplicationConfiguration().upload();
    setMaximumSize(new Long(upload.maximumSize() * 1048576));
    if (!"*".equals(upload.allowedTypes())) {
        setAllowedTypes(upload.allowedTypes());
    }/*from ww  w.  jav a  2  s  .c o  m*/
    final ActionContext actionContext = invocation.getInvocationContext();
    final HttpServletRequest request = (HttpServletRequest) actionContext
            .get(ServletActionContext.HTTP_REQUEST);
    // sets the files in the session to parameters.
    List<Object[]> fileList = (List<Object[]>) actionContext.getSession().get(VulpeConstants.Upload.FILES);
    if (fileList != null) {
        for (Object[] object : fileList) {
            final String inputName = (String) object[0];
            if (!actionContext.getParameters().containsKey(inputName)) {
                actionContext.getParameters().put(inputName, object[1]);
                actionContext.getParameters().put(inputName.concat("ContentType"), object[2]);
                actionContext.getParameters().put(inputName.concat("FileName"), object[3]);
            }
        }
        fileList.clear();
    }

    if (invocation.getAction() instanceof VulpeController
            && !"upload".equals(invocation.getProxy().getMethod())) {
        return super.intercept(invocation);
    }
    if (!(request instanceof MultiPartRequestWrapper)) {
        if (LOG.isDebugEnabled()) {
            final ActionProxy proxy = invocation.getProxy();
            LOG.debug(getText("vulpe.message.bypass.request",
                    new Object[] { proxy.getNamespace(), proxy.getActionName() }));
        }
        return invocation.invoke();
    }

    final Object action = invocation.getAction();
    ValidationAware validation = null;

    if (action instanceof ValidationAware) {
        validation = (ValidationAware) action;
    }

    final MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
    if (multiWrapper.hasErrors()) {
        for (final Iterator errorIterator = multiWrapper.getErrors().iterator(); errorIterator.hasNext();) {
            final String error = (String) errorIterator.next();
            // the request was rejected because its size (9014884) exceeds
            // the configured maximum (2097152)
            if (validation != null) {
                validation.addActionError(error);
            }
            LOG.error(error);
        }
    }

    // Bind allowed Files
    Enumeration fpNames = multiWrapper.getFileParameterNames();
    while (fpNames != null && fpNames.hasMoreElements()) {
        // get the value of this input tag
        final String inputName = (String) fpNames.nextElement();

        // get the content type
        final String[] contentType = multiWrapper.getContentTypes(inputName);

        if (isNotEmpty(contentType)) {
            // get the name of the file from the input tag
            final String[] fileName = multiWrapper.getFileNames(inputName);
            if (isNotEmpty(fileName)) {
                // Get a File object for the uploaded File
                final File[] files = multiWrapper.getFiles(inputName);
                if (ArrayUtils.isNotEmpty(files)) {
                    if (fileList == null) {
                        fileList = new ArrayList();
                    }
                    byte[][] bytes = new byte[files.length][];
                    for (int index = 0; index < files.length; index++) {
                        if (acceptFile(files[index], contentType[index], inputName, validation,
                                actionContext.getLocale())) {
                            bytes[index] = FileUtils.readFileToByteArray(files[index]);
                        }
                    }
                    fileList.add(new Object[] { inputName, (files.length == 1 ? bytes[0] : bytes), contentType,
                            fileName });
                }
            } else {
                LOG.error(getText("vulpe.message.invalid.file", new Object[] { inputName }));
            }
        } else {
            LOG.error(getText("vulpe.message.invalid.content.type", new Object[] { inputName }));
        }
    }

    if (fileList != null && !fileList.isEmpty()) {
        actionContext.getSession().put(VulpeConstants.Upload.FILES, fileList);
    }

    // invoke action
    final String result = invocation.invoke();

    // cleanup
    fpNames = multiWrapper.getFileParameterNames();
    while (fpNames != null && fpNames.hasMoreElements()) {
        final String inputValue = (String) fpNames.nextElement();
        final File[] file = multiWrapper.getFiles(inputValue);
        for (int index = 0; index < file.length; index++) {
            final File currentFile = file[index];
            LOG.info(getText("vulpe.message.removing.file", new Object[] { inputValue, currentFile }));
            if ((currentFile != null) && currentFile.isFile()) {
                currentFile.delete();
            }
        }
    }

    return result;
}

From source file:org.wso2.carbon.appfactory.application.mgt.service.ApplicationInfoService.java

/**
 * Gets application creation status of the {@code applicationKeys}.
 *
 * @param applicationKeys application keys
 * @return Map as applicationKey and {@link org.wso2.carbon.appfactory.core.util.Constants
 * .ApplicationCreationStatus} as key-value pairs.
 * e.g//from  w ww  .  j a va2s  .c o m
 * appKey1 : {@link org.wso2.carbon.appfactory.core.util.Constants.ApplicationCreationStatus#COMPLETED}
 * appKey2 : {@link org.wso2.carbon.appfactory.core.util.Constants.ApplicationCreationStatus#PENDING}
 * appKey3 : {@link org.wso2.carbon.appfactory.core.util.Constants.ApplicationCreationStatus#FAULTY}
 * @throws AppFactoryException
 */
public Map<String, Constants.ApplicationCreationStatus> getAppCreationStatus(String[] applicationKeys)
        throws AppFactoryException {
    Map<String, Constants.ApplicationCreationStatus> applicationCreationStatus = null;
    try {
        if (ArrayUtils.isNotEmpty(applicationKeys)) {
            applicationCreationStatus = JDBCApplicationDAO.getInstance()
                    .getApplicationCreationStatusByKeys(applicationKeys);
        }
    } catch (AppFactoryException e) {
        String errMsg = "Error while getting application creation status of applications "
                + StringUtils.join(applicationKeys, ",");
        log.error(errMsg, e);
        throw new AppFactoryException(errMsg, e);
    }
    return applicationCreationStatus;
}

From source file:org.wso2.carbon.appfactory.repository.mgt.client.SCMAgent.java

/**
 * Method to add files to the given svn repository.
 * Note that this method adds all the sub files and folders to the repo as well.
 *
 * @param url/*from   ww w .j a  v a  2s  .c om*/
 *            the svn repository url
 * @param currentFile
 *            the file that needs to be added to the svn repository
 * @return processResult Result in executing command
 * @throws RepositoryMgtException
 *             if add operation fails
 */
@Override
public boolean addRecursively(String url, File currentFile) throws RepositoryMgtException {

    url = getSCMURL(url);
    ScmRepository repository = getRepository(url);

    boolean outcome = true;

    if (currentFile.isDirectory()) {

        File[] onlySubDirectries = currentFile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory() && isValidName(pathname.getName());
            }
        });

        File[] onlyFiles = currentFile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isFile() && isValidName(pathname.getName());
            }
        });

        try {
            List<File> allChildren = new ArrayList<File>();
            Collections.addAll(allChildren, onlySubDirectries);
            Collections.addAll(allChildren, onlyFiles);

            if (!allChildren.isEmpty()) {
                ScmFileSet allFilesInCurrentLevel = new ScmFileSet(currentFile, allChildren);
                AddScmResult addScmResult = scmManager.add(repository, allFilesInCurrentLevel);
                outcome = processResult(addScmResult, null);
            }

            if (ArrayUtils.isNotEmpty(onlySubDirectries)) {
                for (File subDir : onlySubDirectries) {
                    outcome = outcome && addRecursively(url, subDir.getAbsolutePath());
                }
            }

        } catch (ScmException e) {
            String msg = "Error in executing add operation on " + url;
            log.error(msg, e);
            throw new RepositoryMgtException(msg, e);
        }

    }

    return outcome;

}

From source file:org.wso2.carbon.identity.application.mgt.ApplicationManagementServiceImpl.java

@Override
public void updateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
        throws IdentityApplicationManagementException {

    // invoking the listeners
    Collection<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent
            .getApplicationMgtListeners();
    for (ApplicationMgtListener listener : listeners) {
        if (!listener.doPreUpdateApplication(serviceProvider, tenantDomain, userName)) {
            return;
        }//from   w w w . j ava2  s.  c o  m
    }

    try {
        startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);

        IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(tenantDomain,
                serviceProvider.getApplicationName());

        IdentityServiceProviderCache.getInstance().clearCacheEntry(cacheKey);

    } finally {
        endTenantFlow();
        startTenantFlow(tenantDomain, userName);
    }

    // check whether use is authorized to update the application.
    if (!ApplicationConstants.LOCAL_SP.equals(serviceProvider.getApplicationName()) && !ApplicationMgtUtil
            .isUserAuthorized(serviceProvider.getApplicationName(), serviceProvider.getApplicationID())) {
        log.warn("Illegal Access! User " + CarbonContext.getThreadLocalCarbonContext().getUsername()
                + " does not have access to the application " + serviceProvider.getApplicationName());
        throw new IdentityApplicationManagementException("User not authorized");
    }

    try {
        ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
        String storedAppName = appDAO.getApplicationName(serviceProvider.getApplicationID());
        appDAO.updateApplication(serviceProvider);

        ApplicationPermission[] permissions = serviceProvider.getPermissionAndRoleConfig().getPermissions();
        String applicationNode = ApplicationMgtUtil.getApplicationPermissionPath()
                + RegistryConstants.PATH_SEPARATOR + storedAppName;
        org.wso2.carbon.registry.api.Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext()
                .getRegistry(RegistryType.USER_GOVERNANCE);

        boolean exist = tenantGovReg.resourceExists(applicationNode);
        if (exist && !StringUtils.equals(storedAppName, serviceProvider.getApplicationName())) {
            ApplicationMgtUtil.renameAppPermissionPathNode(storedAppName, serviceProvider.getApplicationName());
        }

        if (ArrayUtils.isNotEmpty(permissions)) {
            ApplicationMgtUtil.updatePermissions(serviceProvider.getApplicationName(), permissions);
        }
    } catch (Exception e) {
        String error = "Error occurred while updating the application";
        log.error(error, e);
        throw new IdentityApplicationManagementException(error, e);
    } finally {
        endTenantFlow();
    }

    for (ApplicationMgtListener listener : listeners) {
        if (!listener.doPostUpdateApplication(serviceProvider, tenantDomain, userName)) {
            return;
        }
    }
}

From source file:org.wso2.carbon.identity.application.mgt.ApplicationManagementServiceImpl.java

@Override
public String[] getAllLocalClaimUris(String tenantDomain) throws IdentityApplicationManagementException {
    try {/*w w w  .  j  a  va  2s  . c  o  m*/
        startTenantFlow(tenantDomain);
        String claimDialect = ApplicationMgtSystemConfig.getInstance().getClaimDialect();
        ClaimMapping[] claimMappings = CarbonContext.getThreadLocalCarbonContext().getUserRealm()
                .getClaimManager().getAllClaimMappings(claimDialect);
        List<String> claimUris = new ArrayList<>();
        for (ClaimMapping claimMap : claimMappings) {
            claimUris.add(claimMap.getClaim().getClaimUri());
        }
        String[] allLocalClaimUris = (claimUris.toArray(new String[claimUris.size()]));
        if (ArrayUtils.isNotEmpty(allLocalClaimUris)) {
            Arrays.sort(allLocalClaimUris);
        }
        return allLocalClaimUris;
    } catch (Exception e) {
        String error = "Error while reading system claims";
        log.error(error, e);
        throw new IdentityApplicationManagementException(error, e);
    } finally {
        endTenantFlow();
    }
}

From source file:org.wso2.carbon.identity.oauth.callback.DefaultCallbackHandler.java

@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    if (ArrayUtils.isNotEmpty(callbacks)) {
        OAuthCallback oauthCallback = (OAuthCallback) callbacks[0];
        // TODO : This needs to be implemented in XACML.
        // TODO : For the moment, let's approve everything.
        if (OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_AUTHZ.equals(oauthCallback.getCallbackType())) {
            oauthCallback.setAuthorized(true);
        }//from   w w w . j  a  va2 s  . c o  m
        if (OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_TOKEN.equals(oauthCallback.getCallbackType())) {
            oauthCallback.setAuthorized(true);
        }
        if (OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_AUTHZ.equals(oauthCallback.getCallbackType())) {
            oauthCallback.setApprovedScope(oauthCallback.getRequestedScope());
            oauthCallback.setValidScope(true);
        }
        if (OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_TOKEN.equals(oauthCallback.getCallbackType())) {
            oauthCallback.setApprovedScope(oauthCallback.getRequestedScope());
            oauthCallback.setValidScope(true);
        }
    }
}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint.java

private void addUserAttributesToCache(SessionDataCacheEntry sessionDataCacheEntry, String code, String codeId) {
    AuthorizationGrantCacheKey authorizationGrantCacheKey = new AuthorizationGrantCacheKey(code);
    AuthorizationGrantCacheEntry authorizationGrantCacheEntry = new AuthorizationGrantCacheEntry(
            sessionDataCacheEntry.getLoggedInUser().getUserAttributes());

    ClaimMapping key = new ClaimMapping();
    Claim claimOfKey = new Claim();
    claimOfKey.setClaimUri(OAuth2Util.SUB);
    key.setRemoteClaim(claimOfKey);/*from  w w w .  j a va 2 s  .  c o m*/
    String sub = sessionDataCacheEntry.getLoggedInUser().getUserAttributes().get(key);

    if (StringUtils.isBlank(sub)) {
        sub = sessionDataCacheEntry.getLoggedInUser().getAuthenticatedSubjectIdentifier();
    }
    if (StringUtils.isNotBlank(sub)) {
        sessionDataCacheEntry.getLoggedInUser().getUserAttributes().put(key, sub);
    }
    //PKCE
    String[] pkceCodeChallengeArray = sessionDataCacheEntry.getParamMap()
            .get(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE);
    String[] pkceCodeChallengeMethodArray = sessionDataCacheEntry.getParamMap()
            .get(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE_METHOD);
    String pkceCodeChallenge = null;
    String pkceCodeChallengeMethod = null;

    if (ArrayUtils.isNotEmpty(pkceCodeChallengeArray)) {
        pkceCodeChallenge = pkceCodeChallengeArray[0];
    }
    if (ArrayUtils.isNotEmpty(pkceCodeChallengeMethodArray)) {
        pkceCodeChallengeMethod = pkceCodeChallengeMethodArray[0];
    }
    authorizationGrantCacheEntry.setAcrValue(sessionDataCacheEntry.getoAuth2Parameters().getACRValues());
    authorizationGrantCacheEntry.setNonceValue(sessionDataCacheEntry.getoAuth2Parameters().getNonce());
    authorizationGrantCacheEntry.setCodeId(codeId);
    authorizationGrantCacheEntry.setPkceCodeChallenge(pkceCodeChallenge);
    authorizationGrantCacheEntry.setPkceCodeChallengeMethod(pkceCodeChallengeMethod);
    authorizationGrantCacheEntry
            .setEssentialClaims(sessionDataCacheEntry.getoAuth2Parameters().getEssentialClaims());
    authorizationGrantCacheEntry.setAuthTime(sessionDataCacheEntry.getAuthTime());
    AuthorizationGrantCache.getInstance().addToCacheByCode(authorizationGrantCacheKey,
            authorizationGrantCacheEntry);
}

From source file:org.wso2.carbon.identity.oauth2.dao.TokenManagementDAOImpl.java

@Override
public void updateAppAndRevokeTokensAndAuthzCodes(String consumerKey, Properties properties,
        String[] authorizationCodes, String[] accessTokens)
        throws IdentityOAuth2Exception, IdentityApplicationManagementException {

    if (log.isDebugEnabled()) {
        log.debug("Updating state of client: " + consumerKey + " and revoking all access tokens and "
                + "authorization codes.");
    }//from  w w  w. j a  v a 2s. co  m

    String action;
    if (properties.containsKey(OAuthConstants.ACTION_PROPERTY_KEY)) {
        action = properties.getProperty(OAuthConstants.ACTION_PROPERTY_KEY);
    } else {
        throw new IdentityOAuth2Exception("Invalid operation.");
    }

    Connection connection = null;
    PreparedStatement updateStateStatement = null;
    PreparedStatement revokeActiveTokensStatement = null;
    PreparedStatement deactivateActiveCodesStatement = null;
    try {
        connection = IdentityDatabaseUtil.getDBConnection();
        connection.setAutoCommit(false);
        if (OAuthConstants.ACTION_REVOKE.equals(action)) {
            String newAppState;
            if (properties.containsKey(OAuthConstants.OAUTH_APP_NEW_STATE)) {
                newAppState = properties.getProperty(OAuthConstants.OAUTH_APP_NEW_STATE);
            } else {
                throw new IdentityOAuth2Exception("New App State is not specified.");
            }

            if (log.isDebugEnabled()) {
                log.debug(
                        "Changing the state of the client: " + consumerKey + " to " + newAppState + " state.");
            }

            // update application state of the oauth app
            updateStateStatement = connection.prepareStatement(
                    org.wso2.carbon.identity.oauth.dao.SQLQueries.OAuthAppDAOSQLQueries.UPDATE_APPLICATION_STATE);
            updateStateStatement.setString(1, newAppState);
            updateStateStatement.setString(2, consumerKey);
            updateStateStatement.execute();

        } else if (OAuthConstants.ACTION_REGENERATE.equals(action)) {
            String newSecretKey;
            if (properties.containsKey(OAuthConstants.OAUTH_APP_NEW_SECRET_KEY)) {
                newSecretKey = properties.getProperty(OAuthConstants.OAUTH_APP_NEW_SECRET_KEY);
            } else {
                throw new IdentityOAuth2Exception("New Consumer Secret is not specified.");
            }

            if (log.isDebugEnabled()) {
                log.debug("Regenerating the client secret of: " + consumerKey);
            }

            // update consumer secret of the oauth app
            updateStateStatement = connection.prepareStatement(
                    org.wso2.carbon.identity.oauth.dao.SQLQueries.OAuthAppDAOSQLQueries.UPDATE_OAUTH_SECRET_KEY);
            updateStateStatement.setString(1, getPersistenceProcessor().getProcessedClientSecret(newSecretKey));
            updateStateStatement.setString(2, consumerKey);
            updateStateStatement.execute();
        }

        //Revoke all active access tokens
        if (ArrayUtils.isNotEmpty(accessTokens)) {
            String accessTokenStoreTable = OAuthConstants.ACCESS_TOKEN_STORE_TABLE;
            if (OAuth2Util.checkAccessTokenPartitioningEnabled()
                    && OAuth2Util.checkUserNameAssertionEnabled()) {
                for (String token : accessTokens) {
                    String sqlQuery = OAuth2Util
                            .getTokenPartitionedSqlByToken(SQLQueries.REVOKE_APP_ACCESS_TOKEN, token);

                    revokeActiveTokensStatement = connection.prepareStatement(sqlQuery);
                    revokeActiveTokensStatement.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED);
                    revokeActiveTokensStatement.setString(2, UUID.randomUUID().toString());
                    revokeActiveTokensStatement.setString(3, consumerKey);
                    int count = revokeActiveTokensStatement.executeUpdate();
                    if (log.isDebugEnabled()) {
                        log.debug("Number of rows being updated : " + count);
                    }
                }
            } else {
                String sqlQuery = SQLQueries.REVOKE_APP_ACCESS_TOKEN.replace(IDN_OAUTH2_ACCESS_TOKEN,
                        accessTokenStoreTable);
                revokeActiveTokensStatement = connection.prepareStatement(sqlQuery);
                revokeActiveTokensStatement.setString(1, OAuthConstants.TokenStates.TOKEN_STATE_REVOKED);
                revokeActiveTokensStatement.setString(2, UUID.randomUUID().toString());
                revokeActiveTokensStatement.setString(3, consumerKey);
                revokeActiveTokensStatement.setString(4, OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE);
                revokeActiveTokensStatement.execute();
            }
        }

        //Deactivate all active authorization codes
        String sqlQuery = SQLQueries.UPDATE_AUTHORIZATION_CODE_STATE_FOR_CONSUMER_KEY;
        deactivateActiveCodesStatement = connection.prepareStatement(sqlQuery);
        deactivateActiveCodesStatement.setString(1, OAuthConstants.AuthorizationCodeState.REVOKED);
        deactivateActiveCodesStatement.setString(2, consumerKey);
        deactivateActiveCodesStatement.executeUpdate();

        connection.commit();

    } catch (SQLException e) {
        throw new IdentityApplicationManagementException("Error while executing the SQL statement.", e);
    } finally {
        IdentityDatabaseUtil.closeStatement(updateStateStatement);
        IdentityDatabaseUtil.closeStatement(revokeActiveTokensStatement);
        IdentityDatabaseUtil.closeAllConnections(connection, null, deactivateActiveCodesStatement);
    }
}

From source file:org.wso2.carbon.identity.oauth2.token.JWTTokenIssuer.java

/**
 * To get the scope of the token to be added to the JWT claims.
 *
 * @param authAuthzReqMessageContext Auth Request Message Context.
 * @param tokenReqMessageContext     Token Request Message Context.
 * @return scope of token./* w  ww  .  jav a 2s  . com*/
 */
private String getScope(OAuthAuthzReqMessageContext authAuthzReqMessageContext,
        OAuthTokenReqMessageContext tokenReqMessageContext) throws IdentityOAuth2Exception {

    String[] scope;
    String scopeString = null;
    if (tokenReqMessageContext != null) {
        scope = tokenReqMessageContext.getScope();
    } else {
        scope = authAuthzReqMessageContext.getApprovedScope();
    }
    if (ArrayUtils.isNotEmpty(scope)) {
        scopeString = OAuth2Util.buildScopeString(scope);
        if (log.isDebugEnabled()) {
            log.debug("Scope exist for the jwt access token with subject "
                    + getAuthenticatedSubjectIdentifier(authAuthzReqMessageContext, tokenReqMessageContext)
                    + " and the scope is " + scopeString);
        }
    }
    return scopeString;
}

From source file:org.wso2.carbon.identity.oauth2.util.ClaimsUtil.java

/**
 * Handle claims from identity provider based on claim configurations.
 *
 * @param identityProvider Identity Provider
 * @param attributes       Relevant Claims coming from IDP
 * @param tenantDomain     Tenant Domain.
 * @param tokenReqMsgCtx   Token request message context.
 * @return mapped local claims.//w  ww .j  a v a  2  s  .c  o  m
 * @throws IdentityOAuth2Exception Identity Oauth2 Exception.
 */
public static Map<String, String> handleClaimMapping(IdentityProvider identityProvider,
        Map<String, String> attributes, String tenantDomain, OAuthTokenReqMessageContext tokenReqMsgCtx)
        throws IdentityException, IdentityApplicationManagementException {

    boolean proxyUserAttributes = !OAuthServerConfiguration.getInstance()
            .isConvertOriginalClaimsFromAssertionsToOIDCDialect();

    if (proxyUserAttributes) {
        setHasNonOIDCClaimsProperty(tokenReqMsgCtx);
        return attributes;
    }

    ClaimMapping[] idPClaimMappings = identityProvider.getClaimConfig().getClaimMappings();
    Map<String, String> claimsAfterIdpMapping;
    Map<String, String> claimsAfterSPMapping = new HashMap<>();
    ServiceProvider serviceProvider = getServiceProvider(tokenReqMsgCtx);

    if (ArrayUtils.isNotEmpty(idPClaimMappings)) {
        if (log.isDebugEnabled()) {
            log.debug(
                    "Claim mappings exist for identity provider " + identityProvider.getIdentityProviderName());
        }
        claimsAfterIdpMapping = handleClaimsForIDP(attributes, tenantDomain, identityProvider, false,
                idPClaimMappings);
        if (isUserClaimsInTokenLoggable()) {
            if (log.isDebugEnabled()) {
                log.debug("Claims of user : " + tokenReqMsgCtx.getAuthorizedUser() + " after IDP "
                        + " claim mapping " + claimsAfterIdpMapping.toString());
            }
        }
        if (isSPRequestedClaimsExist(tokenReqMsgCtx)) {
            claimsAfterSPMapping = ClaimsUtil.convertClaimsToOIDCDialect(tokenReqMsgCtx, claimsAfterIdpMapping);
            claimsAfterSPMapping = handleUnMappedClaims(tokenReqMsgCtx, attributes, claimsAfterSPMapping,
                    idPClaimMappings);
        } else {
            if (isUserClaimsInTokenLoggable()) {
                if (log.isDebugEnabled()) {
                    log.debug("IDP claims exists, SP claims does not exist, for the identity provider "
                            + identityProvider.getIdentityProviderName() + ", service provider "
                            + serviceProvider.getApplicationName() + ", hence cannot do claim mapping");
                }
            }
        }
    } else {
        claimsAfterIdpMapping = attributes;

        if (isUserClaimsInTokenLoggable()) {
            if (log.isDebugEnabled()) {
                log.debug("IDP claims do not exist for, identity provider, "
                        + identityProvider.getIdentityProviderName()
                        + ", hence directly copying custom claims, " + claimsAfterIdpMapping.toString());
            }
        }
        if (isSPRequestedClaimsExist(tokenReqMsgCtx)) {
            claimsAfterSPMapping = ClaimsUtil.convertClaimsToOIDCDialect(tokenReqMsgCtx, claimsAfterIdpMapping);
            if (isUserClaimsInTokenLoggable()) {
                if (log.isDebugEnabled()) {
                    log.debug("IDP claims do not exist but SP Claim mappings exists for, identity provider, "
                            + identityProvider.getIdentityProviderName() + ", and Service Provider, "
                            + serviceProvider.getApplicationName() + ", claims after SP mapping, "
                            + claimsAfterSPMapping.toString());
                }
            }
            claimsAfterSPMapping = handleUnMappedClaims(tokenReqMsgCtx, attributes, claimsAfterSPMapping,
                    idPClaimMappings);
        } else {
            setHasNonOIDCClaimsProperty(tokenReqMsgCtx);
            claimsAfterSPMapping = attributes;
            if (isUserClaimsInTokenLoggable()) {
                if (log.isDebugEnabled()) {
                    log.debug("IDP claims and SP Claim mappings do not exists for, identity provider, "
                            + identityProvider.getIdentityProviderName() + ", and Service Provider, "
                            + serviceProvider.getApplicationName() + ", hence claims are proxied, "
                            + claimsAfterSPMapping.toString());
                }
            }
        }
    }
    return claimsAfterSPMapping;
}