Example usage for java.util Set retainAll

List of usage examples for java.util Set retainAll

Introduction

In this page you can find the example usage for java.util Set retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this set that are contained in the specified collection (optional operation).

Usage

From source file:org.wso2.carbon.identity.oauth2.validators.JDBCScopeValidator.java

@Override
public boolean validateScope(AccessTokenDO accessTokenDO, String resource) throws IdentityOAuth2Exception {

    //Get the list of scopes associated with the access token
    String[] scopes = accessTokenDO.getScope();

    //If no scopes are associated with the token
    if (scopes == null || scopes.length == 0) {
        return true;
    }//from  w  ww .  ja v a2s .c o  m

    String resourceScope = null;
    TokenMgtDAO tokenMgtDAO = new TokenMgtDAO();

    boolean cacheHit = false;
    // Check the cache, if caching is enabled.
    if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
        OAuthCache oauthCache = OAuthCache.getInstance();
        OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
        CacheEntry result = oauthCache.getValueFromCache(cacheKey);

        //Cache hit
        if (result instanceof ResourceScopeCacheEntry) {
            resourceScope = ((ResourceScopeCacheEntry) result).getScope();
            cacheHit = true;
        }
    }

    if (!cacheHit) {
        resourceScope = tokenMgtDAO.findScopeOfResource(resource);

        if (OAuthServerConfiguration.getInstance().isCacheEnabled()) {
            OAuthCache oauthCache = OAuthCache.getInstance();
            OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
            ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
            //Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
            //which scopes haven't been defined).
            oauthCache.addToCache(cacheKey, cacheEntry);
        }
    }

    //Return TRUE if - There does not exist a scope definition for the resource
    if (resourceScope == null) {
        if (log.isDebugEnabled()) {
            log.debug("Resource '" + resource + "' is not protected with a scope");
        }
        return true;
    }

    List<String> scopeList = new ArrayList<>(Arrays.asList(scopes));

    //If the access token does not bear the scope required for accessing the Resource.
    if (!scopeList.contains(resourceScope)) {
        if (log.isDebugEnabled()) {
            log.debug("Access token '" + accessTokenDO.getAccessToken() + "' does not bear the scope '"
                    + resourceScope + "'");
        }
        return false;
    }

    try {
        //Get the roles associated with the scope, if any
        Set<String> rolesOfScope = tokenMgtDAO.getRolesOfScopeByScopeKey(resourceScope);

        //If the scope doesn't have any roles associated with it.
        if (rolesOfScope == null || rolesOfScope.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("Did not find any roles associated to the scope " + resourceScope);
            }
            return true;
        }

        if (log.isDebugEnabled()) {
            StringBuilder logMessage = new StringBuilder("Found roles of scope '" + resourceScope + "' ");
            for (String role : rolesOfScope) {
                logMessage.append(role);
                logMessage.append(", ");
            }
            log.debug(logMessage.toString());
        }

        User authzUser = accessTokenDO.getAuthzUser();
        RealmService realmService = OAuthComponentServiceHolder.getRealmService();

        int tenantId = realmService.getTenantManager().getTenantId(authzUser.getTenantDomain());

        if (tenantId == 0 || tenantId == -1) {
            tenantId = IdentityTenantUtil.getTenantIdOfUser(authzUser.getUserName());
        }

        UserStoreManager userStoreManager;
        String[] userRoles;
        boolean tenantFlowStarted = false;

        try {
            //If this is a tenant user
            if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext.getThreadLocalCarbonContext()
                        .setTenantDomain(realmService.getTenantManager().getDomain(tenantId), true);
                tenantFlowStarted = true;
            }

            userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
            userRoles = userStoreManager
                    .getRoleListOfUser(MultitenantUtils.getTenantAwareUsername(authzUser.getUserName()));
        } finally {
            if (tenantFlowStarted) {
                PrivilegedCarbonContext.endTenantFlow();
            }
        }

        if (userRoles != null && userRoles.length > 0) {
            if (log.isDebugEnabled()) {
                StringBuilder logMessage = new StringBuilder("Found roles of user ");
                logMessage.append(authzUser.getUserName());
                logMessage.append(" ");
                for (String role : userRoles) {
                    logMessage.append(role);
                    logMessage.append(", ");
                }
                log.debug(logMessage.toString());
            }
            //Check if the user still has a valid role for this scope.
            rolesOfScope.retainAll(Arrays.asList(userRoles));
            return !rolesOfScope.isEmpty();
        } else {
            if (log.isDebugEnabled()) {
                log.debug("No roles associated for the user " + authzUser.getUserName());
            }
            return false;
        }

    } catch (UserStoreException e) {
        //Log and return since we do not want to stop issuing the token in case of scope validation failures.
        log.error("Error when getting the tenant's UserStoreManager or when getting roles of user ", e);
        return false;
    }
}

From source file:com.aurel.track.admin.customize.lists.systemOption.IssueTypeBL.java

/**
 * Load all possible item types which can be created by the user
 * @param personID/*from   w w w  .  jav a2 s.  com*/
 * @param locale
 * @return
 */
public static List<TListTypeBean> loadAllByPerson(Integer personID, Locale locale) {
    //get all create item role assignments for person
    List<TAccessControlListBean> accessControlListBeans = AccessBeans.loadByPersonAndRight(personID,
            new int[] { AccessFlagIndexes.CREATETASK, AccessFlagIndexes.PROJECTADMIN }, true);
    Map<Integer, Set<Integer>> projectsToRolesMap = new HashMap<Integer, Set<Integer>>();
    Set<Integer> allPersonRolesSet = new HashSet<Integer>();
    if (accessControlListBeans != null) {
        for (TAccessControlListBean accessControlListBean : accessControlListBeans) {
            Integer projectID = accessControlListBean.getProjectID();
            Integer roleID = accessControlListBean.getRoleID();
            allPersonRolesSet.add(roleID);
            Set<Integer> rolesInProject = projectsToRolesMap.get(projectID);
            if (rolesInProject == null) {
                rolesInProject = new HashSet<Integer>();
                projectsToRolesMap.put(projectID, rolesInProject);
            }
            rolesInProject.add(roleID);
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(accessControlListBeans.size() + " assignments found for person " + personID + ": "
                    + allPersonRolesSet.size() + " roles " + " in " + projectsToRolesMap.size() + " projects ");
        }
    } else {
        return new LinkedList<TListTypeBean>();
    }
    //gets the itemType assignments for the assigned roles 
    Map<Integer, Set<Integer>> roleToItemTypesMap = new HashMap<Integer, Set<Integer>>();
    List<TRoleListTypeBean> itemTypesInRoles = RoleBL
            .loadByRoles(GeneralUtils.createIntegerListFromCollection(allPersonRolesSet));
    if (itemTypesInRoles != null) {
        for (TRoleListTypeBean roleListTypeBean : itemTypesInRoles) {
            Integer roleID = roleListTypeBean.getRole();
            Integer itemTypeID = roleListTypeBean.getListType();
            Set<Integer> itemTypesInRoleSet = roleToItemTypesMap.get(roleID);
            if (itemTypesInRoleSet == null) {
                itemTypesInRoleSet = new HashSet<Integer>();
                roleToItemTypesMap.put(roleID, itemTypesInRoleSet);
            }
            itemTypesInRoleSet.add(itemTypeID);
        }
    }
    Set<Integer> projectSet = projectsToRolesMap.keySet();
    if (projectSet.isEmpty()) {
        LOGGER.info("No project assignment for person " + personID);
        return new LinkedList<TListTypeBean>();
    }
    //gets the project to projectType map
    List<TProjectBean> projectList = ProjectBL
            .loadByProjectIDs(GeneralUtils.createIntegerListFromCollection(projectSet));
    Map<Integer, Integer> projectToProjectTypeMap = new HashMap<Integer, Integer>();
    Set<Integer> projectTypesSet = new HashSet<Integer>();
    for (TProjectBean projectBean : projectList) {
        Integer projectTypeID = projectBean.getProjectType();
        projectToProjectTypeMap.put(projectBean.getObjectID(), projectTypeID);
        projectTypesSet.add(projectTypeID);
    }
    //gets the item type assignments for project types
    List<TPlistTypeBean> plistTypes = loadByProjectTypes(projectTypesSet.toArray());
    Map<Integer, Set<Integer>> projectTypeToItemTypesMap = new HashMap<Integer, Set<Integer>>();
    if (plistTypes != null) {
        for (TPlistTypeBean plistTypeBean : plistTypes) {
            Integer projectTypeID = plistTypeBean.getProjectType();
            Integer itemTypeID = plistTypeBean.getCategory();
            Set<Integer> itemTypesSet = projectTypeToItemTypesMap.get(projectTypeID);
            if (itemTypesSet == null) {
                itemTypesSet = new HashSet<Integer>();
                projectTypeToItemTypesMap.put(projectTypeID, itemTypesSet);
            }
            itemTypesSet.add(itemTypeID);
        }
    }
    Set<Integer> allowedItemTypeIDs = new HashSet<Integer>();
    List<TListTypeBean> allSelectableitemTypeBeans = IssueTypeBL.loadAllSelectable(locale);
    Set<Integer> allSelectableItemTypeIDs = GeneralUtils
            .createIntegerSetFromBeanList(allSelectableitemTypeBeans);
    for (Map.Entry<Integer, Set<Integer>> rolesInProjectEntry : projectsToRolesMap.entrySet()) {
        Integer projectID = rolesInProjectEntry.getKey();
        Set<Integer> roleIDs = rolesInProjectEntry.getValue();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(roleIDs.size() + " roles found in project " + projectID);
        }
        Integer projectTypeID = projectToProjectTypeMap.get(projectID);
        Set<Integer> projectTypeLimitedItemTypes = projectTypeToItemTypesMap.get(projectTypeID);
        Set<Integer> rolesLimitedItemTypes = new HashSet<Integer>();
        //get the item types limited in all roles
        for (Integer roleID : roleIDs) {
            Set<Integer> roleLimitedItemTypes = roleToItemTypesMap.get(roleID);
            if (roleLimitedItemTypes != null) {
                rolesLimitedItemTypes.addAll(roleLimitedItemTypes);
            } else {
                //at least one role has no item type limitations
                rolesLimitedItemTypes.clear();
                break;
            }
        }
        if ((projectTypeLimitedItemTypes == null || projectTypeLimitedItemTypes.isEmpty())
                && rolesLimitedItemTypes.isEmpty()) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("No roles or project type specific limitation found for project " + projectID);
            }
            return allSelectableitemTypeBeans;
        } else {
            if (projectTypeLimitedItemTypes == null || projectTypeLimitedItemTypes.isEmpty()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Add role specific item type limitations for project " + projectID);
                }
                allowedItemTypeIDs.addAll(rolesLimitedItemTypes);
            } else {
                if (rolesLimitedItemTypes.isEmpty()) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug(
                                "Add project type specific item type limitations for project " + projectID);
                    }
                    allowedItemTypeIDs.addAll(projectTypeLimitedItemTypes);
                } else {
                    Collection<Integer> intersection = CollectionUtils.intersection(projectTypeLimitedItemTypes,
                            rolesLimitedItemTypes);
                    if (intersection != null) {
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.debug(
                                    "Add project type specific and role specific item type limitations for project "
                                            + projectID);
                        }
                        allowedItemTypeIDs.addAll(intersection);
                    }
                }
            }
        }
    }
    allowedItemTypeIDs.retainAll(allSelectableItemTypeIDs);
    if (allowedItemTypeIDs.isEmpty()) {
        return new LinkedList<TListTypeBean>();
    } else {
        return LocalizeUtil.localizeDropDownList(
                loadByIssueTypeIDs(GeneralUtils.createIntegerListFromCollection(allowedItemTypeIDs)), locale);
    }
}

From source file:org.opencms.ade.galleries.CmsGalleryService.java

/**
 * @see org.opencms.ade.galleries.shared.rpc.I_CmsGalleryService#loadVfsEntryBean(java.lang.String, java.lang.String)
 *///from w ww.  j  av  a2s  . c om
public CmsVfsEntryBean loadVfsEntryBean(String path, String filter) throws CmsRpcException {

    try {
        if (CmsStringUtil.isEmpty(filter)) {

            CmsObject cms = OpenCms.initCmsObject(getCmsObject());
            cms.getRequestContext().setSiteRoot("");
            if (!cms.existsResource(path, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
                String startFolder = CmsStringUtil.joinPaths(path,
                        getWorkplaceSettings().getUserSettings().getStartFolder());
                if (cms.existsResource(startFolder, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
                    path = startFolder;
                }
            }
            CmsResource optionRes = cms.readResource(path);
            String title = cms.readPropertyObject(optionRes, CmsPropertyDefinition.PROPERTY_TITLE, false)
                    .getValue();
            if (CmsStringUtil.isEmpty(title)) {
                title = path;
            }
            CmsVfsEntryBean entryBean = internalCreateVfsEntryBean(getCmsObject(), optionRes, title, true,
                    isEditable(cms, optionRes), null, false);
            return entryBean;
        } else {
            filter = filter.toLowerCase();
            CmsObject cms = OpenCms.initCmsObject(getCmsObject());
            cms.getRequestContext().setSiteRoot("");
            if (!cms.existsResource(path, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
                String startFolder = CmsStringUtil.joinPaths(path,
                        getWorkplaceSettings().getUserSettings().getStartFolder());
                if (cms.existsResource(startFolder, CmsResourceFilter.ONLY_VISIBLE_NO_DELETED)) {
                    path = startFolder;
                }
            }
            CmsResource optionRes = cms.readResource(path);
            List<CmsResource> folders = cms.readResources(optionRes.getRootPath(),
                    CmsResourceFilter.ONLY_VISIBLE_NO_DELETED.addRequireFolder());
            folders.add(optionRes);
            Set<CmsResource> folderSet = Sets.newHashSet(folders);
            List<CmsResource> titleResources = cms.readResourcesWithProperty(path,
                    CmsPropertyDefinition.PROPERTY_TITLE);
            titleResources.retainAll(folderSet);
            Set<CmsResource> filterMatches = Sets.newHashSet();
            for (CmsResource folder : folderSet) {
                if (folder.getName().toLowerCase().contains(filter)) {
                    filterMatches.add(folder);
                    titleResources.remove(folder); // we don't need to check the title if the name already matched
                }
            }
            for (CmsResource titleRes : titleResources) {
                CmsProperty prop = cms.readPropertyObject(titleRes, CmsPropertyDefinition.PROPERTY_TITLE,
                        false);
                String title = prop.getValue();
                if ((title != null) && title.toLowerCase().contains(filter)) {
                    filterMatches.add(titleRes);
                }
            }
            Set<String> filterMatchAncestorPaths = Sets.newHashSet();
            if (filterMatches.size() > 0) {
                for (CmsResource filterMatch : filterMatches) {
                    String currentPath = filterMatch.getRootPath();
                    while (currentPath != null) {
                        filterMatchAncestorPaths.add(currentPath);
                        currentPath = CmsResource.getParentFolder(currentPath);
                    }
                }
                Set<String> allPaths = Sets.newHashSet();
                Set<String> parentPaths = Sets.newHashSet();
                for (CmsResource folder : folderSet) {
                    allPaths.add(folder.getRootPath());
                    String parent = CmsResource.getParentFolder(folder.getRootPath());
                    if (parent != null) {
                        parentPaths.add(parent);
                    }
                }
                parentPaths.retainAll(allPaths);

                Set<CmsResource> filterMatchAncestors = Sets.newHashSet();
                for (CmsResource folderRes : folderSet) {
                    if (filterMatchAncestorPaths.contains(folderRes.getRootPath())) {
                        filterMatchAncestors.add(folderRes);
                    }
                }
                Map<String, CmsResource> resourcesByPath = Maps.newHashMap();
                for (CmsResource treeRes : filterMatchAncestors) {
                    resourcesByPath.put(treeRes.getRootPath(), treeRes);
                }
                Multimap<CmsResource, CmsResource> childMap = ArrayListMultimap.create();
                for (CmsResource res : filterMatchAncestors) {
                    CmsResource parent = resourcesByPath.get(CmsResource.getParentFolder(res.getRootPath()));
                    if (parent != null) {
                        childMap.put(parent, res);
                    }
                }
                return buildVfsEntryBeanForQuickSearch(optionRes, childMap, filterMatches, parentPaths, true);
            } else {
                return null;
            }
        }
    } catch (Throwable e) {
        error(e);
        return null;
    }
}

From source file:org.wso2.carbon.appmgt.impl.APIProviderImpl.java

@Override
public Set<AppStore> getExternalAppStores(APIIdentifier identifier) throws AppManagementException {
    // get all stores from configuration
    Set<AppStore> storesFromConfig = AppManagerUtil.getExternalStores(tenantId);
    if (storesFromConfig != null && storesFromConfig.size() > 0) {
        AppManagerUtil.validateStoreName(storesFromConfig);
        //get already published stores from db
        Set<AppStore> publishedStores = appMDAO.getExternalAppStoresDetails(identifier);
        if (publishedStores != null && publishedStores.size() > 0) {
            //Retains only the stores that contained in configuration
            publishedStores.retainAll(storesFromConfig);

            for (AppStore publishedStore : publishedStores) {
                for (AppStore configuredStore : storesFromConfig) {
                    if (publishedStore.getName().equals(configuredStore.getName())) { //If the configured appstore
                        // already stored in db, change the published state to true
                        configuredStore.setPublished(true);
                    }//ww  w.  ja  v  a 2s  .  c  o m
                }
            }
        }
    }
    return storesFromConfig;
}

From source file:com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.java

/**
 * Utility method for checking the validity of both hash and range key
 * conditions. It also tries to infer the correct index name from the POJO
 * annotation, if such information is not directly specified by the user.
 *
 * @param clazz/*  ww w. j a v a  2s . c om*/
 *            The domain class of the queried items.
 * @param queryRequest
 *            The QueryRequest object to be sent to service.
 * @param hashKeyConditions
 *            All the hash key EQ conditions extracted from the POJO object.
 *            The mapper will choose one of them that could be applied together with
 *            the user-specified (if any) index name and range key conditions. Or it
 *            throws error if more than one conditions are applicable for the query.
 * @param rangeKeyConditions
 *            The range conditions specified by the user. We currently only
 *            allow at most one range key condition.
 */
private void processKeyConditions(Class<?> clazz, QueryRequest queryRequest,
        Map<String, Condition> hashKeyConditions, Map<String, Condition> rangeKeyConditions) {
    // There should be least one hash key condition.
    if (hashKeyConditions == null || hashKeyConditions.isEmpty()) {
        throw new IllegalArgumentException(
                "Illegal query expression: No hash key condition is found in the query");
    }
    // We don't allow multiple range key conditions.
    if (rangeKeyConditions != null && rangeKeyConditions.size() > 1) {
        throw new IllegalArgumentException("Illegal query expression: Conditions on multiple range keys ("
                + rangeKeyConditions.keySet().toString()
                + ") are found in the query. DynamoDB service only accepts up to ONE range key condition.");
    }
    final boolean hasRangeKeyCondition = (rangeKeyConditions != null) && (!rangeKeyConditions.isEmpty());
    final String userProvidedIndexName = queryRequest.getIndexName();
    final String primaryHashKeyName = reflector.getPrimaryHashKeyName(clazz);
    final TableIndexesInfo parsedIndexesInfo = schemaParser.parseTableIndexes(clazz, reflector);

    // First collect the names of all the global/local secondary indexes that could be applied to this query.
    // If the user explicitly specified an index name, we also need to
    //   1) check the index is applicable for both hash and range key conditions
    //   2) choose one hash key condition if there are more than one of them
    boolean hasPrimaryHashKeyCondition = false;
    final Map<String, Set<String>> annotatedGSIsOnHashKeys = new HashMap<String, Set<String>>();
    String hashKeyNameForThisQuery = null;

    boolean hasPrimaryRangeKeyCondition = false;
    final Set<String> annotatedLSIsOnRangeKey = new HashSet<String>();
    final Set<String> annotatedGSIsOnRangeKey = new HashSet<String>();

    // Range key condition
    String rangeKeyNameForThisQuery = null;
    if (hasRangeKeyCondition) {
        for (String rangeKeyName : rangeKeyConditions.keySet()) {
            rangeKeyNameForThisQuery = rangeKeyName;

            if (reflector.hasPrimaryRangeKey(clazz)
                    && rangeKeyName.equals(reflector.getPrimaryRangeKeyName(clazz))) {
                hasPrimaryRangeKeyCondition = true;
            }

            Collection<String> annotatedLSI = parsedIndexesInfo.getLsiNamesByIndexRangeKey(rangeKeyName);
            if (annotatedLSI != null) {
                annotatedLSIsOnRangeKey.addAll(annotatedLSI);
            }
            Collection<String> annotatedGSI = parsedIndexesInfo.getGsiNamesByIndexRangeKey(rangeKeyName);
            if (annotatedGSI != null) {
                annotatedGSIsOnRangeKey.addAll(annotatedGSI);
            }
        }

        if (!hasPrimaryRangeKeyCondition && annotatedLSIsOnRangeKey.isEmpty()
                && annotatedGSIsOnRangeKey.isEmpty()) {
            throw new DynamoDBMappingException(
                    "The query contains a condition on a range key (" + rangeKeyNameForThisQuery + ") "
                            + "that is not annotated with either @DynamoDBRangeKey or @DynamoDBIndexRangeKey.");
        }
    }

    final boolean userProvidedLSIWithRangeKeyCondition = (userProvidedIndexName != null)
            && (annotatedLSIsOnRangeKey.contains(userProvidedIndexName));
    final boolean hashOnlyLSIQuery = (userProvidedIndexName != null) && (!hasRangeKeyCondition)
            && parsedIndexesInfo.getAllLsiNames().contains(userProvidedIndexName);
    final boolean userProvidedLSI = userProvidedLSIWithRangeKeyCondition || hashOnlyLSIQuery;

    final boolean userProvidedGSIWithRangeKeyCondition = (userProvidedIndexName != null)
            && (annotatedGSIsOnRangeKey.contains(userProvidedIndexName));
    final boolean hashOnlyGSIQuery = (userProvidedIndexName != null) && (!hasRangeKeyCondition)
            && parsedIndexesInfo.getAllGsiNames().contains(userProvidedIndexName);
    final boolean userProvidedGSI = userProvidedGSIWithRangeKeyCondition || hashOnlyGSIQuery;

    if (userProvidedLSI && userProvidedGSI) {
        throw new DynamoDBMappingException("Invalid query: " + "Index \"" + userProvidedIndexName + "\" "
                + "is annotateded as both a LSI and a GSI for attribute.");
    }

    // Hash key conditions
    for (String hashKeyName : hashKeyConditions.keySet()) {
        if (hashKeyName.equals(primaryHashKeyName)) {
            hasPrimaryHashKeyCondition = true;
        }

        Collection<String> annotatedGSINames = parsedIndexesInfo.getGsiNamesByIndexHashKey(hashKeyName);
        annotatedGSIsOnHashKeys.put(hashKeyName,
                annotatedGSINames == null ? new HashSet<String>() : new HashSet<String>(annotatedGSINames));

        // Additional validation if the user provided an index name.
        if (userProvidedIndexName != null) {
            boolean foundHashKeyConditionValidWithUserProvidedIndex = false;
            if (userProvidedLSI && hashKeyName.equals(primaryHashKeyName)) {
                // found an applicable hash key condition (primary hash + LSI range)
                foundHashKeyConditionValidWithUserProvidedIndex = true;
            } else if (userProvidedGSI && annotatedGSINames != null
                    && annotatedGSINames.contains(userProvidedIndexName)) {
                // found an applicable hash key condition (GSI hash + range)
                foundHashKeyConditionValidWithUserProvidedIndex = true;
            }
            if (foundHashKeyConditionValidWithUserProvidedIndex) {
                if (hashKeyNameForThisQuery != null) {
                    throw new IllegalArgumentException(
                            "Ambiguous query expression: More than one hash key EQ conditions ("
                                    + hashKeyNameForThisQuery + ", " + hashKeyName
                                    + ") are applicable to the specified index (" + userProvidedIndexName
                                    + "). " + "Please provide only one of them in the query expression.");
                } else {
                    // found an applicable hash key condition
                    hashKeyNameForThisQuery = hashKeyName;
                }
            }
        }
    }

    // Collate all the key conditions
    Map<String, Condition> keyConditions = new HashMap<String, Condition>();

    // With user-provided index name
    if (userProvidedIndexName != null) {
        if (hasRangeKeyCondition && (!userProvidedLSI) && (!userProvidedGSI)) {
            throw new IllegalArgumentException(
                    "Illegal query expression: No range key condition is applicable to the specified index ("
                            + userProvidedIndexName + "). ");
        }
        if (hashKeyNameForThisQuery == null) {
            throw new IllegalArgumentException(
                    "Illegal query expression: No hash key condition is applicable to the specified index ("
                            + userProvidedIndexName + "). ");
        }

        keyConditions.put(hashKeyNameForThisQuery, hashKeyConditions.get(hashKeyNameForThisQuery));
        if (hasRangeKeyCondition) {
            keyConditions.putAll(rangeKeyConditions);
        }
    }
    // Infer the index name by finding the index shared by both hash and range key annotations.
    else {
        if (hasRangeKeyCondition) {
            String inferredIndexName = null;
            hashKeyNameForThisQuery = null;
            if (hasPrimaryHashKeyCondition && hasPrimaryRangeKeyCondition) {
                // Found valid query: primary hash + range key conditions
                hashKeyNameForThisQuery = primaryHashKeyName;
            } else {
                // Intersect the set of all the indexes applicable to the range key
                // with the set of indexes applicable to each hash key condition.
                for (String hashKeyName : annotatedGSIsOnHashKeys.keySet()) {
                    boolean foundValidQueryExpressionWithInferredIndex = false;
                    String indexNameInferredByThisHashKey = null;
                    if (hashKeyName.equals(primaryHashKeyName)) {
                        if (annotatedLSIsOnRangeKey.size() == 1) {
                            // Found valid query (Primary hash + LSI range conditions)
                            foundValidQueryExpressionWithInferredIndex = true;
                            indexNameInferredByThisHashKey = annotatedLSIsOnRangeKey.iterator().next();
                        }
                    }

                    Set<String> annotatedGSIsOnHashKey = annotatedGSIsOnHashKeys.get(hashKeyName);
                    // We don't need the data in annotatedGSIsOnHashKeys afterwards,
                    // so it's safe to do the intersection in-place.
                    annotatedGSIsOnHashKey.retainAll(annotatedGSIsOnRangeKey);
                    if (annotatedGSIsOnHashKey.size() == 1) {
                        // Found valid query (Hash + range conditions on a GSI)
                        if (foundValidQueryExpressionWithInferredIndex) {
                            hashKeyNameForThisQuery = hashKeyName;
                            inferredIndexName = indexNameInferredByThisHashKey;
                        }

                        foundValidQueryExpressionWithInferredIndex = true;
                        indexNameInferredByThisHashKey = annotatedGSIsOnHashKey.iterator().next();
                    }

                    if (foundValidQueryExpressionWithInferredIndex) {
                        if (hashKeyNameForThisQuery != null) {
                            throw new IllegalArgumentException(
                                    "Ambiguous query expression: Found multiple valid queries: " + "(Hash: \""
                                            + hashKeyNameForThisQuery + "\", Range: \""
                                            + rangeKeyNameForThisQuery + "\", Index: \"" + inferredIndexName
                                            + "\") and " + "(Hash: \"" + hashKeyName + "\", Range: \""
                                            + rangeKeyNameForThisQuery + "\", Index: \""
                                            + indexNameInferredByThisHashKey + "\").");
                        } else {
                            hashKeyNameForThisQuery = hashKeyName;
                            inferredIndexName = indexNameInferredByThisHashKey;
                        }
                    }
                }
            }

            if (hashKeyNameForThisQuery != null) {
                keyConditions.put(hashKeyNameForThisQuery, hashKeyConditions.get(hashKeyNameForThisQuery));
                keyConditions.putAll(rangeKeyConditions);
                queryRequest.setIndexName(inferredIndexName);
            } else {
                throw new IllegalArgumentException(
                        "Illegal query expression: Cannot infer the index name from the query expression.");
            }

        } else {
            // No range key condition is specified.
            if (hashKeyConditions.size() > 1) {
                if (hasPrimaryHashKeyCondition) {
                    keyConditions.put(primaryHashKeyName, hashKeyConditions.get(primaryHashKeyName));
                } else {
                    throw new IllegalArgumentException(
                            "Ambiguous query expression: More than one index hash key EQ conditions ("
                                    + hashKeyConditions.keySet() + ") are applicable to the query. "
                                    + "Please provide only one of them in the query expression, or specify the appropriate index name.");
                }

            } else {
                // Only one hash key condition
                String hashKeyName = annotatedGSIsOnHashKeys.keySet().iterator().next();
                if (!hasPrimaryHashKeyCondition) {
                    if (annotatedGSIsOnHashKeys.get(hashKeyName).size() == 1) {
                        // Set the index if the index hash key is only annotated with one GSI.
                        queryRequest.setIndexName(annotatedGSIsOnHashKeys.get(hashKeyName).iterator().next());
                    } else if (annotatedGSIsOnHashKeys.get(hashKeyName).size() > 1) {
                        throw new IllegalArgumentException("Ambiguous query expression: More than one GSIs ("
                                + annotatedGSIsOnHashKeys.get(hashKeyName) + ") are applicable to the query. "
                                + "Please specify one of them in your query expression.");
                    } else {
                        throw new IllegalArgumentException(
                                "Illegal query expression: No GSI is found in the @DynamoDBIndexHashKey annotation for attribute "
                                        + "\"" + hashKeyName + "\".");
                    }
                }
                keyConditions.putAll(hashKeyConditions);
            }

        }
    }

    queryRequest.setKeyConditions(keyConditions);
}

From source file:org.wso2.carbon.appmgt.impl.APIProviderImpl.java

/**
 * Get the stores where given app is already published.
 * @param identifier WebApp Identifier/*from  w  ww  .ja v  a 2  s  .  c o  m*/
 * @return
 * @throws AppManagementException
 */
private Set<AppStore> getPublishedExternalAppStores(APIIdentifier identifier) throws AppManagementException {
    Set<AppStore> configuredAppStores = new HashSet<AppStore>();
    configuredAppStores.addAll(AppManagerUtil.getExternalStores(tenantId));
    if (configuredAppStores.size() != 0) {
        Set<AppStore> storesSet = appMDAO.getExternalAppStoresDetails(identifier);
        //Retains only the stores that contained in configuration
        configuredAppStores.retainAll(storesSet);
        return configuredAppStores;

    } else {
        return null;
    }
}

From source file:org.jahia.ajax.gwt.content.server.JahiaContentManagementServiceImpl.java

@Override
public Set<String> compareAcl(GWTJahiaNodeACL nodeAcl, List<GWTJahiaNode> references)
        throws GWTJahiaServiceException {
    JCRSessionWrapper sessionWrapper = retrieveCurrentSession();

    final Set<String> result = new HashSet<String>();

    for (GWTJahiaNode reference : references) {
        GWTJahiaNodeACL referenceAcl = contentManager.getACL(reference.getPath(), false, sessionWrapper,
                getUILocale());/*  www . ja v a  2 s.c  om*/

        final Set<String> allReadUsers = new HashSet<String>(); // All users having read rights
        for (GWTJahiaNodeACE ace : nodeAcl.getAce()) {
            if ((ace.getRoles().containsKey("jcr:read_live")
                    && !Boolean.FALSE.equals(ace.getRoles().get("jcr:read_live")))
                    || (ace.getInheritedRoles().containsKey("jcr:read_live")
                            && !Boolean.FALSE.equals(ace.getInheritedRoles().get("jcr:read_live")))) {
                allReadUsers.add(ace.getPrincipalType() + ":" + ace.getPrincipal());
            }
        }

        final Set<String> allDeniedUsers = new HashSet<String>(); // All users having read rights
        for (GWTJahiaNodeACE ace : referenceAcl.getAce()) {
            if ((ace.getRoles().containsKey("jcr:read_live")
                    && !Boolean.TRUE.equals(ace.getRoles().get("jcr:read_live")))
                    || (ace.getInheritedRoles().containsKey("jcr:read_live")
                            && !Boolean.TRUE.equals(ace.getInheritedRoles().get("jcr:read_live")))) {
                allDeniedUsers.add(ace.getPrincipalType() + ":" + ace.getPrincipal());
            }
        }
        allDeniedUsers.retainAll(allReadUsers);
        result.addAll(allDeniedUsers);
    }
    return result;
}

From source file:com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper.java

/**
 * Utility method for checking the validity of both hash and range key
 * conditions. It also tries to infer the correct index name from the POJO
 * annotation, if such information is not directly specified by the user.
 *
 * @param clazz The domain class of the queried items.
 * @param queryRequest The QueryRequest object to be sent to service.
 * @param hashKeyConditions All the hash key EQ conditions extracted from
 *            the POJO object. The mapper will choose one of them that could
 *            be applied together with the user-specified (if any) index
 *            name and range key conditions. Or it throws error if more than
 *            one conditions are applicable for the query.
 * @param rangeKeyConditions The range conditions specified by the user. We
 *            currently only allow at most one range key condition.
 *//*w  w w .  j a  v  a 2  s.  c om*/
@SuppressWarnings("checkstyle:methodlength")
private void processKeyConditions(Class<?> clazz, QueryRequest queryRequest,
        Map<String, Condition> hashKeyConditions, Map<String, Condition> rangeKeyConditions) {
    // There should be least one hash key condition.
    if (hashKeyConditions == null || hashKeyConditions.isEmpty()) {
        throw new IllegalArgumentException(
                "Illegal query expression: No hash key condition is found in the query");
    }
    // We don't allow multiple range key conditions.
    if (rangeKeyConditions != null && rangeKeyConditions.size() > 1) {
        throw new IllegalArgumentException("Illegal query expression: Conditions on multiple range keys ("
                + rangeKeyConditions.keySet().toString()
                + ") are found in the query. DynamoDB service only accepts up to ONE range key condition.");
    }
    final boolean hasRangeKeyCondition = (rangeKeyConditions != null) && (!rangeKeyConditions.isEmpty());
    final String userProvidedIndexName = queryRequest.getIndexName();
    final String primaryHashKeyName = reflector.getPrimaryHashKeyName(clazz);
    final TableIndexesInfo parsedIndexesInfo = schemaParser.parseTableIndexes(clazz, reflector);

    // First collect the names of all the global/local secondary indexes
    // that could be applied to this query.
    // If the user explicitly specified an index name, we also need to
    // 1) check the index is applicable for both hash and range key
    // conditions
    // 2) choose one hash key condition if there are more than one of them
    boolean hasPrimaryHashKeyCondition = false;
    final Map<String, Set<String>> annotatedGSIsOnHashKeys = new HashMap<String, Set<String>>();
    String hashKeyNameForThisQuery = null;

    boolean hasPrimaryRangeKeyCondition = false;
    final Set<String> annotatedLSIsOnRangeKey = new HashSet<String>();
    final Set<String> annotatedGSIsOnRangeKey = new HashSet<String>();

    // Range key condition
    String rangeKeyNameForThisQuery = null;
    if (hasRangeKeyCondition) {
        for (final String rangeKeyName : rangeKeyConditions.keySet()) {
            rangeKeyNameForThisQuery = rangeKeyName;

            if (reflector.hasPrimaryRangeKey(clazz)
                    && rangeKeyName.equals(reflector.getPrimaryRangeKeyName(clazz))) {
                hasPrimaryRangeKeyCondition = true;
            }

            final Collection<String> annotatedLSI = parsedIndexesInfo.getLsiNamesByIndexRangeKey(rangeKeyName);
            if (annotatedLSI != null) {
                annotatedLSIsOnRangeKey.addAll(annotatedLSI);
            }
            final Collection<String> annotatedGSI = parsedIndexesInfo.getGsiNamesByIndexRangeKey(rangeKeyName);
            if (annotatedGSI != null) {
                annotatedGSIsOnRangeKey.addAll(annotatedGSI);
            }
        }

        if (!hasPrimaryRangeKeyCondition && annotatedLSIsOnRangeKey.isEmpty()
                && annotatedGSIsOnRangeKey.isEmpty()) {
            throw new DynamoDBMappingException(
                    "The query contains a condition on a range key (" + rangeKeyNameForThisQuery + ") "
                            + "that is not annotated with either @DynamoDBRangeKey or @DynamoDBIndexRangeKey.");
        }
    }

    final boolean userProvidedLSIWithRangeKeyCondition = (userProvidedIndexName != null)
            && (annotatedLSIsOnRangeKey.contains(userProvidedIndexName));
    final boolean hashOnlyLSIQuery = (userProvidedIndexName != null) && (!hasRangeKeyCondition)
            && parsedIndexesInfo.getAllLsiNames().contains(userProvidedIndexName);
    final boolean userProvidedLSI = userProvidedLSIWithRangeKeyCondition || hashOnlyLSIQuery;

    final boolean userProvidedGSIWithRangeKeyCondition = (userProvidedIndexName != null)
            && (annotatedGSIsOnRangeKey.contains(userProvidedIndexName));
    final boolean hashOnlyGSIQuery = (userProvidedIndexName != null) && (!hasRangeKeyCondition)
            && parsedIndexesInfo.getAllGsiNames().contains(userProvidedIndexName);
    final boolean userProvidedGSI = userProvidedGSIWithRangeKeyCondition || hashOnlyGSIQuery;

    if (userProvidedLSI && userProvidedGSI) {
        throw new DynamoDBMappingException("Invalid query: " + "Index \"" + userProvidedIndexName + "\" "
                + "is annotateded as both a LSI and a GSI for attribute.");
    }

    // Hash key conditions
    for (final String hashKeyName : hashKeyConditions.keySet()) {
        if (hashKeyName.equals(primaryHashKeyName)) {
            hasPrimaryHashKeyCondition = true;
        }

        final Collection<String> annotatedGSINames = parsedIndexesInfo.getGsiNamesByIndexHashKey(hashKeyName);
        annotatedGSIsOnHashKeys.put(hashKeyName,
                annotatedGSINames == null ? new HashSet<String>() : new HashSet<String>(annotatedGSINames));

        // Additional validation if the user provided an index name.
        if (userProvidedIndexName != null) {
            boolean foundHashKeyConditionValidWithUserProvidedIndex = false;
            if (userProvidedLSI && hashKeyName.equals(primaryHashKeyName)) {
                // found an applicable hash key condition (primary hash +
                // LSI range)
                foundHashKeyConditionValidWithUserProvidedIndex = true;
            } else if (userProvidedGSI && annotatedGSINames != null
                    && annotatedGSINames.contains(userProvidedIndexName)) {
                // found an applicable hash key condition (GSI hash + range)
                foundHashKeyConditionValidWithUserProvidedIndex = true;
            }
            if (foundHashKeyConditionValidWithUserProvidedIndex) {
                if (hashKeyNameForThisQuery != null) {
                    throw new IllegalArgumentException(
                            "Ambiguous query expression: More than one hash key EQ conditions ("
                                    + hashKeyNameForThisQuery + ", " + hashKeyName
                                    + ") are applicable to the specified index (" + userProvidedIndexName
                                    + "). " + "Please provide only one of them in the query expression.");
                } else {
                    // found an applicable hash key condition
                    hashKeyNameForThisQuery = hashKeyName;
                }
            }
        }
    }

    // Collate all the key conditions
    final Map<String, Condition> keyConditions = new HashMap<String, Condition>();

    // With user-provided index name
    if (userProvidedIndexName != null) {
        if (hasRangeKeyCondition && (!userProvidedLSI) && (!userProvidedGSI)) {
            throw new IllegalArgumentException(
                    "Illegal query expression: No range key condition is applicable to the specified index ("
                            + userProvidedIndexName + "). ");
        }
        if (hashKeyNameForThisQuery == null) {
            throw new IllegalArgumentException(
                    "Illegal query expression: No hash key condition is applicable to the specified index ("
                            + userProvidedIndexName + "). ");
        }

        keyConditions.put(hashKeyNameForThisQuery, hashKeyConditions.get(hashKeyNameForThisQuery));
        if (hasRangeKeyCondition) {
            keyConditions.putAll(rangeKeyConditions);
        }
    }
    // Infer the index name by finding the index shared by both hash and
    // range key annotations.
    else {
        if (hasRangeKeyCondition) {
            String inferredIndexName = null;
            hashKeyNameForThisQuery = null;
            if (hasPrimaryHashKeyCondition && hasPrimaryRangeKeyCondition) {
                // Found valid query: primary hash + range key conditions
                hashKeyNameForThisQuery = primaryHashKeyName;
            } else {
                // Intersect the set of all the indexes applicable to the
                // range key
                // with the set of indexes applicable to each hash key
                // condition.
                for (final String hashKeyName : annotatedGSIsOnHashKeys.keySet()) {
                    boolean foundValidQueryExpressionWithInferredIndex = false;
                    String indexNameInferredByThisHashKey = null;
                    if (hashKeyName.equals(primaryHashKeyName)) {
                        if (annotatedLSIsOnRangeKey.size() == 1) {
                            // Found valid query (Primary hash + LSI range
                            // conditions)
                            foundValidQueryExpressionWithInferredIndex = true;
                            indexNameInferredByThisHashKey = annotatedLSIsOnRangeKey.iterator().next();
                        }
                    }

                    final Set<String> annotatedGSIsOnHashKey = annotatedGSIsOnHashKeys.get(hashKeyName);
                    // We don't need the data in annotatedGSIsOnHashKeys
                    // afterwards,
                    // so it's safe to do the intersection in-place.
                    annotatedGSIsOnHashKey.retainAll(annotatedGSIsOnRangeKey);
                    if (annotatedGSIsOnHashKey.size() == 1) {
                        // Found valid query (Hash + range conditions on a
                        // GSI)
                        if (foundValidQueryExpressionWithInferredIndex) {
                            hashKeyNameForThisQuery = hashKeyName;
                            inferredIndexName = indexNameInferredByThisHashKey;
                        }

                        foundValidQueryExpressionWithInferredIndex = true;
                        indexNameInferredByThisHashKey = annotatedGSIsOnHashKey.iterator().next();
                    }

                    if (foundValidQueryExpressionWithInferredIndex) {
                        if (hashKeyNameForThisQuery != null) {
                            throw new IllegalArgumentException(
                                    "Ambiguous query expression: Found multiple valid queries: " + "(Hash: \""
                                            + hashKeyNameForThisQuery + "\", Range: \""
                                            + rangeKeyNameForThisQuery + "\", Index: \"" + inferredIndexName
                                            + "\") and " + "(Hash: \"" + hashKeyName + "\", Range: \""
                                            + rangeKeyNameForThisQuery + "\", Index: \""
                                            + indexNameInferredByThisHashKey + "\").");
                        } else {
                            hashKeyNameForThisQuery = hashKeyName;
                            inferredIndexName = indexNameInferredByThisHashKey;
                        }
                    }
                }
            }

            if (hashKeyNameForThisQuery != null) {
                keyConditions.put(hashKeyNameForThisQuery, hashKeyConditions.get(hashKeyNameForThisQuery));
                keyConditions.putAll(rangeKeyConditions);
                queryRequest.setIndexName(inferredIndexName);
            } else {
                throw new IllegalArgumentException(
                        "Illegal query expression: Cannot infer the index name from the query expression.");
            }

        } else {
            // No range key condition is specified.
            if (hashKeyConditions.size() > 1) {
                if (hasPrimaryHashKeyCondition) {
                    keyConditions.put(primaryHashKeyName, hashKeyConditions.get(primaryHashKeyName));
                } else {
                    throw new IllegalArgumentException(
                            "Ambiguous query expression: More than one index hash key EQ conditions ("
                                    + hashKeyConditions.keySet() + ") are applicable to the query. "
                                    + "Please provide only one of them in the query expression, or specify the appropriate index name.");
                }

            } else {
                // Only one hash key condition
                final String hashKeyName = annotatedGSIsOnHashKeys.keySet().iterator().next();
                if (!hasPrimaryHashKeyCondition) {
                    if (annotatedGSIsOnHashKeys.get(hashKeyName).size() == 1) {
                        // Set the index if the index hash key is only
                        // annotated with one GSI.
                        queryRequest.setIndexName(annotatedGSIsOnHashKeys.get(hashKeyName).iterator().next());
                    } else if (annotatedGSIsOnHashKeys.get(hashKeyName).size() > 1) {
                        throw new IllegalArgumentException("Ambiguous query expression: More than one GSIs ("
                                + annotatedGSIsOnHashKeys.get(hashKeyName) + ") are applicable to the query. "
                                + "Please specify one of them in your query expression.");
                    } else {
                        throw new IllegalArgumentException(
                                "Illegal query expression: No GSI is found in the @DynamoDBIndexHashKey annotation for attribute "
                                        + "\"" + hashKeyName + "\".");
                    }
                }
                keyConditions.putAll(hashKeyConditions);
            }

        }
    }

    queryRequest.setKeyConditions(keyConditions);
}

From source file:org.codecover.eclipse.views.CoverageGraphView.java

private edu.uci.ics.jung.graph.Graph<CoverageGraphNode, CoverageGraphLink> createGraph(String Criterion,
        String SUTLevel, String TestLevel, Boolean ShowOnlyCovered, Boolean CompleteName) {
    edu.uci.ics.jung.graph.Graph<CoverageGraphNode, CoverageGraphLink> graph = new SparseMultigraph<CoverageGraphNode, CoverageGraphLink>();
    try {/*  w  w w  . j  a  v  a  2 s .com*/
        Set<CoverableItem> coverableItemSet = CreateCoverableItemSet(Criterion);
        Vector<CoverageGraphNode> SUTItems = new Vector<CoverageGraphNode>();
        Vector<String> SUTItemsId = new Vector<String>();
        Vector<CoverageGraphNode> TestItems = new Vector<CoverageGraphNode>();
        Vector<String> TestItemsId = new Vector<String>();
        int NumOfSUTNodes = 0;
        int NumOfTestNodes = 0;
        if (selectedTestCases.size() != 0) {
            CoverageGraphNode SUTNode;
            CoverageGraphNode TestNode;
            List<CoverableItem> SUTItemList = new ArrayList<CoverableItem>(coverableItemSet);
            List<CoverableItem> CoveredItemList;

            //Adding all of the SUT Nodes to the graph:
            //-----------------------------------------
            for (int j = 0; j < SUTItemList.size(); j++) {
                boolean ex = false;
                HierarchyLevel methodLevel = null;
                try {
                    methodLevel = getSUTItemMethod(SUTItemList.get(j));
                } catch (IllegalArgumentException e1) {
                    // the item is a condition, it is not possible to get the parent statement in the tree (it's parent is null)
                    ex = true;
                } catch (Exception e2) {
                    ex = true;
                }

                if (methodLevel != null && !ex) {
                    String PackageName = getSUTItemPackage(getSUTItemClass(methodLevel));
                    String ClassName = getSUTItemClass(methodLevel).getName();
                    String MethodName = methodLevel.getName();

                    String ItemName = getSUTItemId(SUTItemList.get(j).getId());
                    String nodeName = getNodeLable(SUTLevel, PackageName, ClassName, MethodName, ItemName);
                    if (!SUTItemsId.contains(nodeName)) {
                        SUTNode = new CoverageGraphNode("SUT", SUTLevel, PackageName, ClassName,
                                getSUTItemClass(methodLevel).getLocation().getLocations().get(0), MethodName,
                                methodLevel.getLocation().getLocations().get(0), ItemName, loc, StContent,
                                methodLevel, CompleteName);
                        SUTItemsId.add(SUTNode.getLable());
                        SUTItems.add(SUTNode);
                        NumOfSUTNodes++;
                        if (!ShowOnlyCovered)
                            graph.addVertex(SUTNode);
                    }
                }
            }

            Set<CoverableItem> coveredItemSet;
            int testsize = 0;
            if (!selectedTestCases.equals(null))
                testsize = selectedTestCases.size();
            for (int i = 0; i < testsize; i++) {

                //Adding Test Nodes to the graph:
                //-------------------------------
                TestCase tc = (TestCase) selectedTestCases.get(i);
                TestNode = new CoverageGraphNode("Test", TestLevel, getTestNodeName(tc.getName(), "Package"),
                        getTestNodeName(tc.getName(), "Class"), getTestNodeName(tc.getName(), "Method"),
                        CompleteName);
                String testNodeName = TestNode.getLable();
                if (!TestItemsId.contains(testNodeName)) {
                    TestItemsId.add(TestNode.getLable());
                    TestItems.add(TestNode);
                    graph.addVertex(TestNode);
                    TestNode.Testcases.add(tc);
                    NumOfTestNodes++;
                } else {
                    for (int k = 0; k < NumOfTestNodes; k++)
                        if (TestItems.get(k).getLable().compareTo(testNodeName) == 0)
                            TestNode = TestItems.get(k);
                    TestNode.Testcases.add(tc);
                }

                Map<CoverableItem, Long> CoveredItemMap = tc.getCoverageData();
                coveredItemSet = new HashSet<CoverableItem>();
                for (int j = 0; j < SUTItemList.size(); j++) {
                    coveredItemSet.add(SUTItemList.get(j));
                }
                coveredItemSet.retainAll(CoveredItemMap.keySet());
                CoveredItemList = new ArrayList<CoverableItem>(coveredItemSet);

                String nodeName = "";
                for (int j = 0; j < CoveredItemList.size(); j++) {
                    boolean ex = false;
                    HierarchyLevel methodLevel = null;
                    HierarchyLevel currentlevel = null;
                    try {
                        methodLevel = getSUTItemMethod(CoveredItemList.get(j));
                    } catch (Exception ec) {
                        ex = true;
                    }

                    if (methodLevel != null && !ex) {
                        String PackageName = getSUTItemPackage(getSUTItemClass(methodLevel));
                        String ClassName = getSUTItemClass(methodLevel).getName();
                        String MethodName = methodLevel.getName();
                        String ItemName = getSUTItemId(CoveredItemList.get(j).getId());
                        nodeName = getNodeLable(SUTLevel, PackageName, ClassName, MethodName, ItemName);
                        //Adding Edges to the graph:
                        //--------------------------
                        Integer id = graph.getEdgeCount() + 1;
                        CoverageGraphLink CoverageLink = graph.findEdge(TestItems.lastElement(),
                                SUTItems.elementAt(SUTItemsId.indexOf(nodeName)));
                        if (CoverageLink == null) {
                            CoverageLink = new CoverageGraphLink(id);
                            CoverageLink.SUTLevel = SUTLevel;
                        } else
                            graph.removeEdge(CoverageLink);
                        CoverageLink.times++;

                        CoverageGraphNode CurrentNode = new CoverageGraphNode();
                        for (int k = 0; k < NumOfSUTNodes; k++)
                            if (SUTItems.get(k).getLable().compareTo(nodeName) == 0)
                                CurrentNode = SUTItems.get(k);
                        if (CurrentNode != null) {
                            if (ShowOnlyCovered)
                                graph.addVertex(CurrentNode);

                            //For calculating Ratio:
                            if (SUTLevel.compareTo("Method") == 0)
                                currentlevel = methodLevel;
                            else if (SUTLevel.compareTo("Class") == 0)
                                currentlevel = topLevel.getParent(methodLevel);
                            else if (SUTLevel.compareTo("Package") == 0) {
                                currentlevel = topLevel.getParent(methodLevel);
                                currentlevel = topLevel.getParent(currentlevel);
                            }
                            if (currentlevel != null) {
                                CoverageResult coverageResult = null;
                                if (Criterion.compareTo("Statement") == 0) {
                                    StatementCoverage coverageMetric = StatementCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                } else if (Criterion.compareTo("Branch") == 0) {
                                    BranchCoverage coverageMetric = BranchCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                } else if (Criterion.compareTo("Loop") == 0) {
                                    LoopCoverage coverageMetric = LoopCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                } else if (Criterion.compareTo("Term") == 0) {
                                    TermCoverage coverageMetric = TermCoverage.getInstance();
                                    coverageResult = coverageMetric.getCoverage(TestNode.Testcases,
                                            currentlevel);
                                }
                                if (coverageResult != null) {
                                    float coverage = 0f;
                                    if (coverageResult.getTotalItems() > 0) {
                                        coverage = ((float) coverageResult.getCoveredItems()
                                                / coverageResult.getTotalItems());
                                    }
                                    CoverageLink.ratio = coverage;
                                }
                            } else
                                CoverageLink.ratio = 2;
                            graph.addEdge(CoverageLink, TestItems.lastElement(), CurrentNode,
                                    EdgeType.DIRECTED);
                        }
                    }
                }
                coveredItemSet.clear();
            }
        }
    } catch (Exception ex) {
        return null;
    }
    return graph;
}

From source file:org.sakaiproject.content.tool.ListItem.java

/**
 * Sets the access roles on the entity when saving the ListItem.
 * @param entityEdit the Edit object of the underlying ListItem that is being saved.
 * @throws PermissionException if the current user doesn't have permission to add or remove roles.
 * @throws InconsistentException if the current entity inherits an access mode such as group access.
 */// www .j  a va 2s.co  m
protected void setAccessRoles(GroupAwareEdit entityEdit) throws PermissionException, InconsistentException {

    Set<String> rolesToSave = new LinkedHashSet<String>(roleIds);
    rolesToSave.retainAll(availableRoleIds());

    Set<String> currentRoles = entityEdit.getRoleAccessIds();

    Set<String> rolesToAdd = new LinkedHashSet<String>(rolesToSave);
    rolesToAdd.removeAll(currentRoles);
    rolesToAdd.removeAll(inheritedRoleIds);
    for (String role : rolesToAdd) {
        entityEdit.addRoleAccess(role);
    }

    Set<String> rolesToRemove = new LinkedHashSet<String>(currentRoles);
    rolesToRemove.removeAll(rolesToSave);
    rolesToRemove.removeAll(inheritedRoleIds);
    for (String role : rolesToRemove) {
        entityEdit.removeRoleAccess(role);
    }
}