Example usage for org.apache.commons.lang StringUtils containsIgnoreCase

List of usage examples for org.apache.commons.lang StringUtils containsIgnoreCase

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils containsIgnoreCase.

Prototype

public static boolean containsIgnoreCase(String str, String searchStr) 

Source Link

Document

Checks if String contains a search String irrespective of case, handling null.

Usage

From source file:org.trancecode.xproc.step.RequestParser.java

private String getContentString(final XdmNode node, final ContentType contentType, final String encoding,
        final Processor processor) {
    if (!StringUtils.isEmpty(encoding) && !StringUtils.equalsIgnoreCase(encoding, Steps.ENCODING_BASE64)) {
        throw XProcExceptions.xc0052(SaxonLocation.of(node));
    }/*from   w  w w .j  a  va 2  s .c o  m*/
    final StringBuilder contentBuilder = new StringBuilder();
    if (!StringUtils.containsIgnoreCase(contentType.getSubType(), "xml")
            || StringUtils.equalsIgnoreCase(encoding, Steps.ENCODING_BASE64)) {
        final Iterable<XdmItem> children = SaxonAxis.axis(node, Axis.CHILD);
        for (final XdmItem aNode : children) {
            if (!XdmNodeKind.TEXT.equals(((XdmNode) aNode).getNodeKind())) {
                throw XProcExceptions.xc0028(SaxonLocation.of(node));
            } else {
                contentBuilder.append(StringEscapeUtils.unescapeHtml(aNode.toString()));
            }
        }
    } else {
        final Iterable<XdmItem> children = SaxonAxis.axis(node, Axis.CHILD);
        boolean oneElement = false;
        for (final XdmItem aNode : children) {
            final XdmNodeKind kind = ((XdmNode) aNode).getNodeKind();
            if (XdmNodeKind.TEXT.equals(kind) && !StringUtils.isEmpty(aNode.getStringValue().trim())) {
                throw XProcExceptions.xc0022(node);
            } else if (XdmNodeKind.ELEMENT.equals(kind)) {
                if (oneElement) {
                    throw XProcExceptions.xc0022(node);
                } else {
                    oneElement = true;
                }
            }
        }
    }
    if (StringUtils.equalsIgnoreCase("xml", contentType.getSubType())) {
        final ByteArrayOutputStream targetOutputStream = new ByteArrayOutputStream();
        final Serializer serializer = Steps.getSerializer(targetOutputStream, serializationOptions, processor);
        serializer.setOutputProperty(Serializer.Property.MEDIA_TYPE, contentType.toString());
        try {
            processor.writeXdmValue(SaxonAxis.childElement(node), serializer);
        } catch (final Exception e) {
            throw new PipelineException("Error while trying to write document", e);
        } finally {
            Closeables.closeQuietly(targetOutputStream);
        }
        contentBuilder.append(targetOutputStream.toString());
    }
    final String id = node.getAttributeValue(XProcXmlModel.Attributes.ID);
    verifyHeader(id, "Content-ID", node);
    final String description = node.getAttributeValue(XProcXmlModel.Attributes.DESCRIPTION);
    verifyHeader(description, "Content-Description", node);
    final String disposition = node.getAttributeValue(XProcXmlModel.Attributes.DISPOSITION);
    verifyHeader(disposition, "Content-Disposition", node);
    return contentBuilder.toString();
}

From source file:org.unitedinternet.cosmo.dav.acl.report.PrincipalPropertySearchReport.java

private boolean matchText(String test, String match) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Matching " + test + " against " + match);
    }//from  ww  w .  j a v  a  2  s .co  m
    return StringUtils.containsIgnoreCase(test, match);
}

From source file:org.webguitoolkit.ui.controls.form.Text.java

/**
 * This method determines the time mode.<br>
 * It is checked if a 24 or a 12 (am/pm) hour mode is used by the locale
 * //from w w  w . j  a  v a2 s . c om
 * @return true if the hour mode is 24
 */
private boolean is24HourMode() {
    // A bit a dirty way to check the hour mode...a Date is converted an checked...
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, TextService.getLocale());
    String testDate = df.format(new Date());
    if (StringUtils.containsIgnoreCase(testDate, "am") || StringUtils.containsIgnoreCase(testDate, "pm")) {
        return false;
    } else {
        return true;
    }
}

From source file:org.wso2.andes.configuration.modules.JKSStore.java

public JKSStore(String rootXPath) throws ConfigurationException {

    String locationXPath = rootXPath + relativeXPathForLocation;
    String passwordXPath = rootXPath + relativeXPathForPassword;
    String storeAlgorithmXPath = rootXPath + relativeXPathForStoreAlgorithm;

    String defaultStoreLocation = null;
    String defaultStoreAlgorithm = null;

    if (StringUtils.containsIgnoreCase(rootXPath, "trustStore")) {
        defaultStoreLocation = JKS_BASE_PATH + "wso2carbon.jks";
        defaultStoreAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    } else {/*w w  w .  j a  v a2  s . c o m*/
        defaultStoreAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        defaultStoreLocation = JKS_BASE_PATH + "client-truststore.jks";
    }

    // After deriving the full xpaths, the AndesConfigurationManager is used to extract the values for each
    // property.
    storeLocation = AndesConfigurationManager.deriveValidConfigurationValue(locationXPath, String.class,
            defaultStoreLocation);
    password = AndesConfigurationManager.deriveValidConfigurationValue(passwordXPath, String.class,
            DEFAULT_STORE_PASSWORD);
    storeAlgorithm = AndesConfigurationManager.deriveValidConfigurationValue(storeAlgorithmXPath, String.class,
            defaultStoreAlgorithm);
}

From source file:org.wso2.andes.kernel.subscription.AndesSubscriptionManager.java

/**
 * Get inactive subscriptions filtered by identifier pattern and tokenized binding key.
 *
 * @param bindingKeyPattern regex to match with binding key of subscriber
 * @return Set of subscriptions filtered according to search criteria
 * @throws AndesException/*from   ww w .j  a  v  a 2s .  com*/
 */
private Set<AndesSubscription> getInactiveSubscriptionsByTokenizedBindingKeyMatch(String bindingKeyPattern)
        throws AndesException {

    Set<AndesSubscription> filteredSubscriptions = new HashSet<>();

    List<AndesSubscription> allInactiveSubscriptions = getInactiveSubscriberRepresentations();

    for (AndesSubscription inactiveSubscription : allInactiveSubscriptions) {
        if (StringUtils.containsIgnoreCase(inactiveSubscription.getStorageQueue().getMessageRouterBindingKey(),
                bindingKeyPattern)) {
            filteredSubscriptions.add(inactiveSubscription);
        }
    }
    return filteredSubscriptions;
}

From source file:org.wso2.andes.kernel.subscription.AndesSubscriptionManager.java

/**
 * Filter inactive subscriptions./*w  w w .  j a v  a  2s .c o  m*/
 *
 * @param subscriptions subscription list for further filtering
 * @param protocolType protocol of the subscription
 * @param destinationType type of subscription (QUEUE/TOPIC/DURABLE_TOPIC)
 * @param subscriptionIdPattern regex to match with ID of the subscriber
 * @param isExactMatchSubscriptionId exact match of subscription id or not
 * @return Set of subscriptions filtered according to search criteria
 */
private Set<AndesSubscription> filterInactiveSubscriptionsBySubscriptionId(Set<AndesSubscription> subscriptions,
        ProtocolType protocolType, DestinationType destinationType, String subscriptionIdPattern,
        boolean isExactMatchSubscriptionId) {

    Set<AndesSubscription> filteredSubscriptions = new HashSet<>();
    String messageRouter = destinationType.getAndesMessageRouter();

    if (isExactMatchSubscriptionId) {
        for (AndesSubscription inactiveSubscription : subscriptions) {
            if (inactiveSubscription.getStorageQueue().getMessageRouter().getName().equals(messageRouter)
                    && inactiveSubscription.getProtocolType().equals(protocolType)
                    && inactiveSubscription.getSubscriptionId().equalsIgnoreCase(subscriptionIdPattern)) {
                filteredSubscriptions.add(inactiveSubscription);
            }
        }
    } else {
        for (AndesSubscription inactiveSubscription : subscriptions) {
            if (inactiveSubscription.getStorageQueue().getMessageRouter().getName().equals(messageRouter)
                    && inactiveSubscription.getProtocolType().equals(protocolType)
                    && StringUtils.containsIgnoreCase(inactiveSubscription.getSubscriptionId(),
                            subscriptionIdPattern)) {
                filteredSubscriptions.add(inactiveSubscription);
            }
        }
    }
    return filteredSubscriptions;
}

From source file:org.wso2.andes.kernel.subscription.AndesSubscriptionManager.java

/**
 * Filter active subscriptions by subscription id.
 *
 * @param subscriptions subscription list for further filtering
 * @param subscriptionIdPattern regex to match with ID of the subscriber
 * @param isExactMatchSubscriptionId exact match of subscription id or not
 * @return Set of subscriptions filtered according to search criteria
 *//* ww w.  jav  a2 s.c o  m*/
private Set<AndesSubscription> filterActiveSubscriptionsBySubscriptionId(Set<AndesSubscription> subscriptions,
        String subscriptionIdPattern, boolean isExactMatchSubscriptionId) {

    Set<AndesSubscription> filteredSubscriptions = new HashSet<>();

    if (isExactMatchSubscriptionId) {
        for (AndesSubscription subscription : subscriptions) {
            if (subscriptionIdPattern.equalsIgnoreCase(subscription.getSubscriptionId())) {
                filteredSubscriptions.add(subscription);
            } else if (subscription.isDurable() && subscription.getStorageQueue().getMessageRouter().getName()
                    .equals(AMQPUtils.TOPIC_EXCHANGE_NAME)) {
                if (subscriptionIdPattern.equalsIgnoreCase(subscription.getStorageQueue().getName())) {
                    filteredSubscriptions.add(subscription);
                }
            }
        }
    } else {
        for (AndesSubscription subscription : subscriptions) {
            if (StringUtils.containsIgnoreCase(subscription.getSubscriptionId(), subscriptionIdPattern)) {
                filteredSubscriptions.add(subscription);
            } else if (subscription.isDurable() && subscription.getStorageQueue().getMessageRouter().getName()
                    .equals(AMQPUtils.TOPIC_EXCHANGE_NAME)) {
                if (StringUtils.containsIgnoreCase(subscription.getStorageQueue().getName(),
                        subscriptionIdPattern)) {
                    filteredSubscriptions.add(subscription);
                }
            }
        }
    }
    return filteredSubscriptions;
}

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

private void insertAccessToken(String accessToken, String consumerKey, AccessTokenDO accessTokenDO,
        Connection connection, String userStoreDomain, int retryAttemptCounter) throws IdentityOAuth2Exception {

    if (!isPersistenceEnabled()) {
        return;/*  w w w.ja va  2s . com*/
    }

    if (accessTokenDO == null) {
        throw new IdentityOAuth2Exception(
                "Access token data object should be available for further execution.");
    }

    if (accessTokenDO.getAuthzUser() == null) {
        throw new IdentityOAuth2Exception("Authorized user should be available for further execution.");
    }

    try {
        OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey);
        //check for persist alias for the token type
        if (oauthTokenIssuer.usePersistedAccessTokenAlias()) {
            accessToken = oauthTokenIssuer.getAccessTokenHash(accessToken);
        }
    } catch (OAuthSystemException e) {
        if (log.isDebugEnabled()
                && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Error while getting access token hash for token(hashed): "
                    + DigestUtils.sha256Hex(accessToken));
        }
        throw new IdentityOAuth2Exception("Error while getting access token hash.");
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception(
                "Error while retrieving oauth issuer for the app with clientId: " + consumerKey, e);
    }

    if (log.isDebugEnabled()) {
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Persisting access token(hashed): " + DigestUtils.sha256Hex(accessToken) + " for client: "
                    + consumerKey + " user: " + accessTokenDO.getAuthzUser().toString() + " scope: "
                    + Arrays.toString(accessTokenDO.getScope()));
        } else {
            log.debug("Persisting access token for client: " + consumerKey + " user: "
                    + accessTokenDO.getAuthzUser().toString() + " scope: "
                    + Arrays.toString(accessTokenDO.getScope()));
        }
    }
    userStoreDomain = OAuth2Util.getSanitizedUserStoreDomain(userStoreDomain);
    String userDomain = accessTokenDO.getAuthzUser().getUserStoreDomain();
    String authenticatedIDP = accessTokenDO.getAuthzUser().getFederatedIdPName();
    PreparedStatement insertTokenPrepStmt = null;
    PreparedStatement addScopePrepStmt = null;

    if (!OAuthServerConfiguration.getInstance().isMapFederatedUsersToLocal()
            && accessTokenDO.getAuthzUser().isFederatedUser()) {
        if (log.isDebugEnabled()) {
            log.debug("Adding federated domain to user store domain to user "
                    + accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier());
        }
        userDomain = OAuth2Util.getFederatedUserDomain(authenticatedIDP);
    }

    if (log.isDebugEnabled()) {
        log.debug("Userstore domain for user "
                + accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier() + " is :" + userDomain);
    }

    String sql = OAuth2Util.getTokenPartitionedSqlByUserStore(SQLQueries.INSERT_OAUTH2_ACCESS_TOKEN,
            userDomain);
    String sqlAddScopes = OAuth2Util.getTokenPartitionedSqlByUserStore(SQLQueries.INSERT_OAUTH2_TOKEN_SCOPE,
            userDomain);

    try {
        insertTokenPrepStmt = connection.prepareStatement(sql);
        insertTokenPrepStmt.setString(1,
                getPersistenceProcessor().getProcessedAccessTokenIdentifier(accessToken));

        if (accessTokenDO.getRefreshToken() != null) {
            insertTokenPrepStmt.setString(2,
                    getPersistenceProcessor().getProcessedRefreshToken(accessTokenDO.getRefreshToken()));
        } else {
            insertTokenPrepStmt.setString(2, accessTokenDO.getRefreshToken());
        }

        insertTokenPrepStmt.setString(3, accessTokenDO.getAuthzUser().getUserName());
        int tenantId = OAuth2Util.getTenantId(accessTokenDO.getAuthzUser().getTenantDomain());
        insertTokenPrepStmt.setInt(4, tenantId);
        insertTokenPrepStmt.setString(5, OAuth2Util.getSanitizedUserStoreDomain(userDomain));
        insertTokenPrepStmt.setTimestamp(6, accessTokenDO.getIssuedTime(),
                Calendar.getInstance(TimeZone.getTimeZone(UTC)));
        insertTokenPrepStmt.setTimestamp(7, accessTokenDO.getRefreshTokenIssuedTime(),
                Calendar.getInstance(TimeZone.getTimeZone(UTC)));
        insertTokenPrepStmt.setLong(8, accessTokenDO.getValidityPeriodInMillis());
        insertTokenPrepStmt.setLong(9, accessTokenDO.getRefreshTokenValidityPeriodInMillis());
        insertTokenPrepStmt.setString(10, OAuth2Util.hashScopes(accessTokenDO.getScope()));
        insertTokenPrepStmt.setString(11, accessTokenDO.getTokenState());
        insertTokenPrepStmt.setString(12, accessTokenDO.getTokenType());
        insertTokenPrepStmt.setString(13, accessTokenDO.getTokenId());
        insertTokenPrepStmt.setString(14, accessTokenDO.getGrantType());
        insertTokenPrepStmt.setString(15, accessTokenDO.getAuthzUser().getAuthenticatedSubjectIdentifier());
        insertTokenPrepStmt.setString(16,
                getHashingPersistenceProcessor().getProcessedAccessTokenIdentifier(accessToken));
        if (accessTokenDO.getRefreshToken() != null) {
            insertTokenPrepStmt.setString(17,
                    getHashingPersistenceProcessor().getProcessedRefreshToken(accessTokenDO.getRefreshToken()));
        } else {
            insertTokenPrepStmt.setString(17, accessTokenDO.getRefreshToken());
        }
        insertTokenPrepStmt.setString(18, getPersistenceProcessor().getProcessedClientId(consumerKey));
        insertTokenPrepStmt.execute();

        String accessTokenId = accessTokenDO.getTokenId();
        addScopePrepStmt = connection.prepareStatement(sqlAddScopes);

        if (accessTokenDO.getScope() != null && accessTokenDO.getScope().length > 0) {
            for (String scope : accessTokenDO.getScope()) {
                addScopePrepStmt.setString(1, accessTokenId);
                addScopePrepStmt.setString(2, scope);
                addScopePrepStmt.setInt(3, tenantId);
                addScopePrepStmt.execute();
            }
        }
        if (retryAttemptCounter > 0) {
            log.info("Successfully recovered 'CON_APP_KEY' constraint violation with the attempt : "
                    + retryAttemptCounter);
        }
    } catch (SQLIntegrityConstraintViolationException e) {
        IdentityDatabaseUtil.rollBack(connection);
        if (retryAttemptCounter >= getTokenPersistRetryCount()) {
            log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - "
                    + getTokenPersistRetryCount());
            String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : "
                    + accessTokenDO.getAuthzUser() + " and scope : "
                    + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists";
            throw new IdentityOAuth2Exception(errorMsg, e);
        }

        recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection,
                userStoreDomain, retryAttemptCounter + 1);
    } catch (DataTruncation e) {
        IdentityDatabaseUtil.rollBack(connection);
        throw new IdentityOAuth2Exception("Invalid request", e);
    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(connection);
        // Handle constrain violation issue in JDBC drivers which does not throw
        // SQLIntegrityConstraintViolationException
        if (StringUtils.containsIgnoreCase(e.getMessage(), "CON_APP_KEY")) {
            if (retryAttemptCounter >= getTokenPersistRetryCount()) {
                log.error("'CON_APP_KEY' constrain violation retry count exceeds above the maximum count - "
                        + getTokenPersistRetryCount());
                String errorMsg = "Access Token for consumer key : " + consumerKey + ", user : "
                        + accessTokenDO.getAuthzUser() + " and scope : "
                        + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + "already exists";
                throw new IdentityOAuth2Exception(errorMsg, e);
            }

            recoverFromConAppKeyConstraintViolation(accessToken, consumerKey, accessTokenDO, connection,
                    userStoreDomain, retryAttemptCounter + 1);
        } else {
            throw new IdentityOAuth2Exception(
                    "Error when storing the access token for consumer key : " + consumerKey, e);
        }
    } finally {
        IdentityDatabaseUtil.closeStatement(addScopePrepStmt);
        IdentityDatabaseUtil.closeStatement(insertTokenPrepStmt);
    }

}

From source file:org.wso2.carbon.identity.scim.provider.impl.SCIMUserManager.java

@Override
public Group createGroup(Group group) throws CharonException, DuplicateResourceException {

    if (log.isDebugEnabled()) {
        log.debug("Creating group: " + group.getDisplayName());
    }/*from   w w  w .ja  va  2 s  .  c  o  m*/
    try {
        //modify display name if no domain is specified, in order to support multiple user store feature
        String originalName = group.getDisplayName();
        String roleNameWithDomain = null;
        String domainName = "";
        try {
            if (getUserStoreDomainFromSP() != null) {
                domainName = getUserStoreDomainFromSP();
                roleNameWithDomain = UserCoreUtil
                        .addDomainToName(UserCoreUtil.removeDomainFromName(originalName), domainName);
            } else if (originalName.indexOf(CarbonConstants.DOMAIN_SEPARATOR) > 0) {
                roleNameWithDomain = originalName;
                domainName = originalName.split(UserCoreConstants.DOMAIN_SEPARATOR)[0];
            } else {
                roleNameWithDomain = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME
                        + CarbonConstants.DOMAIN_SEPARATOR + originalName;
                domainName = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME;
            }
        } catch (IdentityApplicationManagementException e) {
            throw new CharonException("Error retrieving User Store name. ", e);
        }
        group.setDisplayName(roleNameWithDomain);
        //check if the group already exists
        if (carbonUM.isExistingRole(group.getDisplayName(), false)) {
            String error = "Group with name: " + group.getDisplayName() + " already exists in the system.";
            throw new DuplicateResourceException(error);
        }

        /*set thread local property to signal the downstream SCIMUserOperationListener
        about the provisioning route.*/
        SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true);
        /*if members are sent when creating the group, check whether users already exist in the
        user store*/
        List<String> userIds = group.getMembers();
        List<String> userDisplayNames = group.getMembersWithDisplayName();
        if (CollectionUtils.isNotEmpty(userIds)) {
            List<String> members = new ArrayList<>();
            for (String userId : userIds) {
                String[] userNames = carbonUM.getUserList(SCIMConstants.ID_URI, userId,
                        UserCoreConstants.DEFAULT_PROFILE);
                if (userNames == null || userNames.length == 0) {
                    String error = "User: " + userId + " doesn't exist in the user store. "
                            + "Hence, can not create the group: " + group.getDisplayName();
                    throw new IdentitySCIMException(error);
                } else if (userNames[0].indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0
                        && !StringUtils.containsIgnoreCase(userNames[0], domainName)) {
                    String error = "User: " + userId + " doesn't exist in the same user store. "
                            + "Hence, can not create the group: " + group.getDisplayName();
                    throw new IdentitySCIMException(error);
                } else {
                    members.add(userNames[0]);
                    if (CollectionUtils.isNotEmpty(userDisplayNames)) {
                        boolean userContains = false;
                        for (String user : userDisplayNames) {
                            user = user.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0
                                    ? user.split(UserCoreConstants.DOMAIN_SEPARATOR)[1]
                                    : user;
                            if (user.equalsIgnoreCase(
                                    userNames[0].indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0
                                            ? userNames[0].split(UserCoreConstants.DOMAIN_SEPARATOR)[1]
                                            : userNames[0])) {
                                userContains = true;
                                break;
                            }
                        }
                        if (!userContains) {
                            throw new IdentitySCIMException("Given SCIM user Id and name not matching..");
                        }
                    }
                }
            }

            //add other scim attributes in the identity DB since user store doesn't support some attributes.
            SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId());
            scimGroupHandler.createSCIMAttributes(group);
            carbonUM.addRole(group.getDisplayName(), members.toArray(new String[members.size()]), null, false);
            log.info("Group: " + group.getDisplayName() + " is created through SCIM.");
        } else {
            //add other scim attributes in the identity DB since user store doesn't support some attributes.
            SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId());
            scimGroupHandler.createSCIMAttributes(group);
            carbonUM.addRole(group.getDisplayName(), null, null, false);
            log.info("Group: " + group.getDisplayName() + " is created through SCIM.");
        }
    } catch (UserStoreException e) {
        try {
            SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId());
            scimGroupHandler.deleteGroupAttributes(group.getDisplayName());
        } catch (UserStoreException | IdentitySCIMException ex) {
            log.error("Error occurred while doing rollback operation of the SCIM table entry for role: "
                    + group.getDisplayName(), ex);
            throw new CharonException(
                    "Error occurred while doing rollback operation of the SCIM table entry for role: "
                            + group.getDisplayName(),
                    e);
        }
        throw new CharonException("Error occurred while adding role : " + group.getDisplayName(), e);
    } catch (IdentitySCIMException e) {
        //This exception can occurr because of scimGroupHandler.createSCIMAttributes(group) or
        //userContains=false. Therefore contextual message could not be provided.
        throw new CharonException("Error in creating group", e);
    }
    //TODO:after the group is added, read it from user store and return
    return group;
}

From source file:org.wso2.carbon.identity.scim.v2.common.impl.SCIMUserManager.java

@Override
public Group createGroup(Group group, Map<String, Boolean> requiredAttributes)
        throws CharonException, ConflictException, BadRequestException {
    if (log.isDebugEnabled()) {
        log.debug("Creating group: " + group.getDisplayName());
    }//from   ww w .  j a  va2s.co  m
    try {
        //modify display name if no domain is specified, in order to support multiple user store feature
        String originalName = group.getDisplayName();
        String roleNameWithDomain = null;
        String domainName = "";
        try {
            if (getUserStoreDomainFromSP() != null) {
                domainName = getUserStoreDomainFromSP();
                roleNameWithDomain = UserCoreUtil
                        .addDomainToName(UserCoreUtil.removeDomainFromName(originalName), domainName);
            } else if (originalName.indexOf(CarbonConstants.DOMAIN_SEPARATOR) > 0) {
                domainName = IdentityUtil.extractDomainFromName(originalName);
                roleNameWithDomain = UserCoreUtil
                        .addDomainToName(UserCoreUtil.removeDomainFromName(originalName), domainName);
            } else {
                domainName = UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME;
                roleNameWithDomain = SCIMCommonUtils.getGroupNameWithDomain(originalName);
            }
        } catch (IdentityApplicationManagementException e) {
            throw new CharonException("Error retrieving User Store name. ", e);
        }

        if (!isInternalOrApplicationGroup(domainName) && StringUtils.isNotBlank(domainName)
                && !isSCIMEnabled(domainName)) {
            throw new CharonException("Cannot add user through scim to user store " + ". SCIM is not "
                    + "enabled for user store " + domainName);
        }
        group.setDisplayName(roleNameWithDomain);
        //check if the group already exists
        if (carbonUM.isExistingRole(group.getDisplayName(), false)) {
            String error = "Group with name: " + group.getDisplayName() + " already exists in the system.";
            throw new ConflictException(error);
        }

        /*set thread local property to signal the downstream SCIMUserOperationListener
        about the provisioning route.*/
        SCIMCommonUtils.setThreadLocalIsManagedThroughSCIMEP(true);
        /*if members are sent when creating the group, check whether users already exist in the
        user store*/
        List<Object> userIds = group.getMembers();
        List<String> userDisplayNames = group.getMembersWithDisplayName();
        if (CollectionUtils.isNotEmpty(userIds)) {
            List<String> members = new ArrayList<>();
            for (Object userId : userIds) {
                String[] userNames = carbonUM.getUserList(SCIMConstants.CommonSchemaConstants.ID_URI,
                        (String) userId, UserCoreConstants.DEFAULT_PROFILE);
                if (userNames == null || userNames.length == 0) {
                    String error = "User: " + userId + " doesn't exist in the user store. "
                            + "Hence, can not create the group: " + group.getDisplayName();
                    throw new IdentitySCIMException(error);
                } else if (userNames[0].indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0
                        && !StringUtils.containsIgnoreCase(userNames[0], domainName)) {
                    String error = "User: " + userId + " doesn't exist in the same user store. "
                            + "Hence, can not create the group: " + group.getDisplayName();
                    throw new IdentitySCIMException(error);
                } else {
                    members.add(userNames[0]);
                    if (CollectionUtils.isNotEmpty(userDisplayNames)) {
                        boolean userContains = false;
                        for (String user : userDisplayNames) {
                            user = user.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0
                                    ? user.split(UserCoreConstants.DOMAIN_SEPARATOR)[1]
                                    : user;
                            if (user.equalsIgnoreCase(
                                    userNames[0].indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > 0
                                            ? userNames[0].split(UserCoreConstants.DOMAIN_SEPARATOR)[1]
                                            : userNames[0])) {
                                userContains = true;
                                break;
                            }
                        }
                        if (!userContains) {
                            throw new IdentitySCIMException("Given SCIM user Id and name does not match..");
                        }
                    }
                }
            }
            //add other scim attributes in the identity DB since user store doesn't support some attributes.
            SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId());
            scimGroupHandler.createSCIMAttributes(group);
            carbonUM.addRole(group.getDisplayName(), members.toArray(new String[members.size()]), null, false);
            log.info("Group: " + group.getDisplayName() + " is created through SCIM.");
        } else {
            //add other scim attributes in the identity DB since user store doesn't support some attributes.
            SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId());
            scimGroupHandler.createSCIMAttributes(group);
            carbonUM.addRole(group.getDisplayName(), null, null, false);
            log.info("Group: " + group.getDisplayName() + " is created through SCIM.");
        }
    } catch (UserStoreException e) {
        try {
            SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(carbonUM.getTenantId());
            scimGroupHandler.deleteGroupAttributes(group.getDisplayName());
        } catch (UserStoreException | IdentitySCIMException ex) {
            log.error("Error occurred while doing rollback operation of the SCIM table entry for role: "
                    + group.getDisplayName(), ex);
            throw new CharonException(
                    "Error occurred while doing rollback operation of the SCIM table entry for role: "
                            + group.getDisplayName(),
                    e);
        }
        throw new CharonException("Error occurred while adding role : " + group.getDisplayName(), e);
    } catch (IdentitySCIMException | BadRequestException e) {
        String error = "One or more group members do not exist in the same user store. "
                + "Hence, can not create the group: " + group.getDisplayName();
        throw new BadRequestException(error, ResponseCodeConstants.INVALID_VALUE);
    }
    return group;
}