Example usage for java.util SortedSet addAll

List of usage examples for java.util SortedSet addAll

Introduction

In this page you can find the example usage for java.util SortedSet addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:com.zimbra.cs.account.ProvUtil.java

private void doDescribe(String[] args) throws ServiceException {
    DescribeArgs descArgs = null;//from  w  w  w  .  j  a  v  a 2s .  c o  m
    try {
        descArgs = parseDescribeArgs(args);
    } catch (ServiceException e) {
        descAttrsUsage(e);
        return;
    } catch (NumberFormatException e) {
        descAttrsUsage(e);
        return;
    }

    SortedSet<String> attrs = null;
    String specificAttr = null;

    AttributeManager am = AttributeManager.getInstance();

    if (descArgs.mAttr != null) {
        // specific attr
        specificAttr = descArgs.mAttr;
    } else if (descArgs.mAttrClass != null) {
        // attrs in a class
        attrs = new TreeSet<String>(am.getAllAttrsInClass(descArgs.mAttrClass));
        if (descArgs.mNonInheritedOnly) {
            Set<String> inheritFrom = null;
            Set<String> netAttrs = null;
            switch (descArgs.mAttrClass) {
            case account:
                netAttrs = new HashSet<String>(attrs);
                inheritFrom = new HashSet<String>(am.getAllAttrsInClass(AttributeClass.cos));
                netAttrs = SetUtil.subtract(netAttrs, inheritFrom);
                inheritFrom = new HashSet<String>(am.getAllAttrsInClass(AttributeClass.domain)); // for
                                                                                                 // accountCosDomainInherited
                netAttrs = SetUtil.subtract(netAttrs, inheritFrom);
                break;
            case domain:
            case server:
                netAttrs = new HashSet<String>(attrs);
                inheritFrom = new HashSet<String>(am.getAllAttrsInClass(AttributeClass.globalConfig));
                netAttrs = SetUtil.subtract(netAttrs, inheritFrom);
                break;
            }

            if (netAttrs != null) {
                attrs = new TreeSet<String>(netAttrs);
            }
        }

        if (descArgs.mOnThisObjectTypeOnly) {
            TreeSet<String> netAttrs = new TreeSet<String>();
            for (String attr : attrs) {
                AttributeInfo ai = am.getAttributeInfo(attr);
                if (ai == null) {
                    continue;
                }
                Set<AttributeClass> requiredIn = ai.getRequiredIn();
                Set<AttributeClass> optionalIn = ai.getOptionalIn();
                if ((requiredIn == null || requiredIn.size() == 1)
                        && (optionalIn == null || optionalIn.size() == 1)) {
                    netAttrs.add(attr);
                }
            }
            attrs = netAttrs;
        }

    } else {
        //
        // all attrs
        //

        // am.getAllAttrs() only contains attrs with AttributeInfo
        // not extension attrs
        // attrs = new TreeSet<String>(am.getAllAttrs());

        // attr sets for each AttributeClass contain attrs in the extensions, use them
        attrs = new TreeSet<String>();
        for (AttributeClass ac : AttributeClass.values()) {
            attrs.addAll(am.getAllAttrsInClass(ac));
        }
    }

    if (specificAttr != null) {
        AttributeInfo ai = am.getAttributeInfo(specificAttr);
        if (ai == null) {
            console.println("no attribute info for " + specificAttr);
        } else {
            console.println(ai.getName());
            // description
            String desc = ai.getDescription();
            console.println(FileGenUtil.wrapComments((desc == null ? "" : desc), 70, "    "));
            console.println();

            for (DescribeArgs.Field f : DescribeArgs.Field.values()) {
                console.format("    %15s : %s\n", f.name(), DescribeArgs.Field.print(f, ai));
            }
        }
        console.println();

    } else {
        for (String attr : attrs) {
            AttributeInfo ai = am.getAttributeInfo(attr);
            if (ai == null) {
                console.println(attr + " (no attribute info)");
                continue;
            }
            String attrName = ai.getName(); // camel case name
            console.println(attrName);
            if (descArgs.mVerbose) {
                String desc = ai.getDescription();
                console.println(FileGenUtil.wrapComments((desc == null ? "" : desc), 70, "    ") + "\n");
            }
        }
    }
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
 * Get the recently added APIs set//from  w w w .  j  a  va  2s .  c  om
 *
 * @param limit no limit. Return everything else, limit the return list to specified value.
 * @return Set<API>
 * @throws APIManagementException
 */
@Override
public Set<API> getRecentlyAddedAPIs(int limit, String tenantDomain) throws APIManagementException {
    SortedSet<API> recentlyAddedAPIs = new TreeSet<API>(new APINameComparator());
    SortedSet<API> recentlyAddedAPIsWithMultipleVersions = new TreeSet<API>(new APIVersionComparator());
    Registry userRegistry;
    APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration();
    boolean isRecentlyAddedAPICacheEnabled = Boolean
            .parseBoolean(config.getFirstProperty(APIConstants.API_STORE_RECENTLY_ADDED_API_CACHE_ENABLE));

    PrivilegedCarbonContext.startTenantFlow();
    boolean isTenantFlowStarted;
    if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        isTenantFlowStarted = true;
    } else {
        PrivilegedCarbonContext.getThreadLocalCarbonContext()
                .setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
        isTenantFlowStarted = true;
    }

    try {
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null)
                || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {//Tenant based store anonymous mode
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
            isTenantFlowStarted = true;
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
        } else {
            userRegistry = registry;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
            isTenantFlowStarted = true;
        }
        if (isRecentlyAddedAPICacheEnabled) {
            boolean isStatusChanged = false;
            Set<API> recentlyAddedAPI = (Set<API>) Caching
                    .getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
                    .getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME)
                    .get(username + COLON_CHAR + tenantDomain);
            if (recentlyAddedAPI != null) {
                for (API api : recentlyAddedAPI) {
                    try {
                        if (!APIConstants.PUBLISHED
                                .equalsIgnoreCase(userRegistry.get(APIUtil.getAPIPath(api.getId()))
                                        .getProperty(APIConstants.API_OVERVIEW_STATUS))) {
                            isStatusChanged = true;
                            break;
                        }
                    } catch (Exception ex) {
                        log.error("Error while checking API status for APP " + api.getId().getApiName() + '-'
                                + api.getId().getVersion(), ex);
                    }
                }
                if (!isStatusChanged) {
                    return recentlyAddedAPI;
                }
            }
        }

        PaginationContext.init(0, limit, APIConstants.REGISTRY_ARTIFACT_SEARCH_DESC_ORDER,
                APIConstants.REGISTRY_ARTIFACT_SORT_BY_CREATED_TIME, Integer.MAX_VALUE);
        Map<String, List<String>> listMap = new HashMap<String, List<String>>();
        listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
            {
                add(APIConstants.PUBLISHED);
            }
        });

        //Find UUID
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            SortedSet<API> allAPIs = new TreeSet<API>(new APINameComparator());
            for (GenericArtifact artifact : genericArtifacts) {

                API api = null;
                try {
                    api = APIUtil.getAPI(artifact);
                } catch (APIManagementException e) {
                    //just log and continue since we want to go through the other APIs as well.
                    log.error("Error loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
                }
                if (api != null) {
                    allAPIs.add(api);
                }
            }

            if (!APIUtil.isAllowDisplayMultipleVersions()) {
                Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
                Comparator<API> versionComparator = new APIVersionComparator();
                String key;
                for (API api : allAPIs) {
                    key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                    API existingAPI = latestPublishedAPIs.get(key);
                    if (existingAPI != null) {
                        // If we have already seen an API with the same
                        // name, make sure this one has a higher version
                        // number
                        if (versionComparator.compare(api, existingAPI) > 0) {
                            latestPublishedAPIs.put(key, api);
                        }
                    } else {
                        // We haven't seen this API before
                        latestPublishedAPIs.put(key, api);
                    }
                }

                recentlyAddedAPIs.addAll(latestPublishedAPIs.values());
                if (isRecentlyAddedAPICacheEnabled) {
                    Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
                            .getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME)
                            .put(username + COLON_CHAR + tenantDomain, allAPIs);
                }
                return recentlyAddedAPIs;
            } else {
                recentlyAddedAPIsWithMultipleVersions.addAll(allAPIs);
                if (isRecentlyAddedAPICacheEnabled) {
                    Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)
                            .getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME)
                            .put(username + COLON_CHAR + tenantDomain, allAPIs);
                }
                return recentlyAddedAPIsWithMultipleVersions;
            }
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return recentlyAddedAPIs;
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
 * The method to get APIs by given status to Store view
 *
 * @return Set<API>  Set of APIs/*from   ww w .ja va 2 s .c  om*/
 * @throws APIManagementException
 */
@Override
@Deprecated
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end,
        final String apiStatus, boolean returnAPITags) throws APIManagementException {
    Boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
    Map<String, List<String>> listMap = new HashMap<String, List<String>>();
    //Check the api-manager.xml config file entry <DisplayAllAPIs> value is false
    if (APIConstants.PROTOTYPED.equals(apiStatus)) {
        listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
            {
                add(apiStatus);
            }
        });
    } else {
        if (!displayAPIsWithMultipleStatus) {
            //Create the search attribute map
            listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
                {
                    add(apiStatus);
                }
            });
        } else {
            return getAllPaginatedAPIs(tenantDomain, start, end);
        }
    }

    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
    int totalLength = 0;
    boolean isMore = false;
    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null)
                || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {//Tenant store anonymous mode
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        }
        this.isTenantModeStoreView = isTenantMode;
        this.requestedTenant = tenantDomain;

        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        List<API> multiVersionedAPIs = new ArrayList<API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
        String paginationLimit = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
                .getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);

        // If the Config exists use it to set the pagination limit
        final int maxPaginationLimit;
        if (paginationLimit != null) {
            // The additional 1 added to the maxPaginationLimit is to help us determine if more
            // APIs may exist so that we know that we are unable to determine the actual total
            // API count. We will subtract this 1 later on so that it does not interfere with
            // the logic of the rest of the application
            int pagination = Integer.parseInt(paginationLimit);

            // Because the store jaggery pagination logic is 10 results per a page we need to set pagination
            // limit to at least 11 or the pagination done at this level will conflict with the store pagination
            // leading to some of the APIs not being displayed
            if (pagination < 11) {
                pagination = 11;
                log.warn(
                        "Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
            }

            maxPaginationLimit = start + pagination + 1;
        }
        // Else if the config is not specified we go with default functionality and load all
        else {
            maxPaginationLimit = Integer.MAX_VALUE;
        }

        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {

            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                result.put("isMore", isMore);
                return result;
            }

            // Check to see if we can speculate that there are more APIs to be loaded
            if (maxPaginationLimit == totalLength) {
                isMore = true; // More APIs exist so we cannot determine the total API count without incurring a
                // performance hit
                --totalLength; // Remove the additional 1 we added earlier when setting max pagination limit
            }
            int tempLength = 0;
            for (GenericArtifact artifact : genericArtifacts) {

                API api = null;
                try {
                    api = APIUtil.getAPI(artifact);
                } catch (APIManagementException e) {
                    //log and continue since we want to load the rest of the APIs.
                    log.error(
                            "Error while loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME),
                            e);
                }
                if (api != null) {
                    if (returnAPITags) {
                        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
                        Set<String> tags = new HashSet<String>();
                        org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath);
                        for (org.wso2.carbon.registry.core.Tag tag1 : tag) {
                            tags.add(tag1.getTagName());
                        }
                        api.addTags(tags);
                    }

                    String key;
                    //Check the configuration to allow showing multiple versions of an API true/false
                    if (!displayMultipleVersions) { //If allow only showing the latest version of an API
                        key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                        API existingAPI = latestPublishedAPIs.get(key);
                        if (existingAPI != null) {
                            // If we have already seen an API with the same name, make sure
                            // this one has a higher version number
                            if (versionComparator.compare(api, existingAPI) > 0) {
                                latestPublishedAPIs.put(key, api);
                            }
                        } else {
                            // We haven't seen this API before
                            latestPublishedAPIs.put(key, api);
                        }
                    } else { //If allow showing multiple versions of an API
                        multiVersionedAPIs.add(api);
                    }
                }
                tempLength++;
                if (tempLength >= totalLength) {
                    break;
                }
            }
            if (!displayMultipleVersions) {
                apiSortedSet.addAll(latestPublishedAPIs.values());
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                result.put("isMore", isMore);
                return result;
            } else {
                apiVersionsSortedSet.addAll(multiVersionedAPIs);
                result.put("apis", apiVersionsSortedSet);
                result.put("totalLength", totalLength);
                result.put("isMore", isMore);
                return result;
            }
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("apis", apiSortedSet);
    result.put("totalLength", totalLength);
    result.put("isMore", isMore);
    return result;
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
* Pagination API search based on solr indexing
*
* @param registry//www.  j av  a2s .co  m
* @param searchTerm
* @param searchType
* @return
* @throws APIManagementException
*/

public Map<String, Object> searchPaginatedAPIs(Registry registry, String searchTerm, String searchType,
        int start, int end, boolean limitAttributes) throws APIManagementException {
    SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
    List<API> apiList = new ArrayList<API>();

    searchTerm = searchTerm.trim();
    Map<String, Object> result = new HashMap<String, Object>();
    int totalLength = 0;
    boolean isMore = false;
    String criteria = APIConstants.API_OVERVIEW_NAME;
    try {
        String paginationLimit = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
                .getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);

        // If the Config exists use it to set the pagination limit
        final int maxPaginationLimit;
        if (paginationLimit != null) {
            // The additional 1 added to the maxPaginationLimit is to help us determine if more
            // APIs may exist so that we know that we are unable to determine the actual total
            // API count. We will subtract this 1 later on so that it does not interfere with
            // the logic of the rest of the application
            int pagination = Integer.parseInt(paginationLimit);

            // Because the store jaggery pagination logic is 10 results per a page we need to set pagination
            // limit to at least 11 or the pagination done at this level will conflict with the store pagination
            // leading to some of the APIs not being displayed
            if (pagination < 11) {
                pagination = 11;
                log.warn(
                        "Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
            }
            maxPaginationLimit = start + pagination + 1;
        }
        // Else if the config is not specified we go with default functionality and load all
        else {
            maxPaginationLimit = Integer.MAX_VALUE;
        }
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        if (artifactManager != null) {

            if (APIConstants.API_PROVIDER.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_PROVIDER;
                searchTerm = searchTerm.replaceAll("@", "-AT-");
            } else if (APIConstants.API_VERSION_LABEL.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_VERSION;
            } else if (APIConstants.API_CONTEXT.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_CONTEXT;
            } else if (APIConstants.API_DESCRIPTION.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_DESCRIPTION;
            } else if (APIConstants.API_TAG.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_TAG;
            }

            //Create the search attribute map for PUBLISHED APIs
            final String searchValue = searchTerm;
            Map<String, List<String>> listMap = new HashMap<String, List<String>>();
            listMap.put(criteria, new ArrayList<String>() {
                {
                    add(searchValue);
                }
            });

            boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();

            //This is due to take only the published APIs from the search if there is no need to return APIs with
            //multiple status. This is because pagination is breaking when we do a another filtering with the API Status
            if (!displayAPIsWithMultipleStatus) {
                listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
                    {
                        add(APIConstants.PUBLISHED);
                    }
                });
            }

            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();

            boolean isFound = true;
            if (genericArtifacts == null || genericArtifacts.length == 0) {

                if (APIConstants.API_OVERVIEW_PROVIDER.equals(criteria)) {
                    genericArtifacts = searchAPIsByOwner(artifactManager, searchValue);
                    if (genericArtifacts == null || genericArtifacts.length == 0) {
                        isFound = false;
                    }
                } else {
                    isFound = false;
                }
            }

            if (!isFound) {
                result.put("apis", apiSet);
                result.put("length", 0);
                result.put("isMore", isMore);
                return result;
            }

            // Check to see if we can speculate that there are more APIs to be loaded
            if (maxPaginationLimit == totalLength) {
                isMore = true; // More APIs exist, cannot determine total API count without incurring perf hit
                --totalLength; // Remove the additional 1 added earlier when setting max pagination limit
            }

            int tempLength = 0;
            for (GenericArtifact artifact : genericArtifacts) {
                String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);

                if (APIUtil.isAllowDisplayAPIsWithMultipleStatus()) {
                    if (APIConstants.PROTOTYPED.equals(status) || APIConstants.PUBLISHED.equals(status)
                            || APIConstants.DEPRECATED.equals(status)) {
                        API resultAPI;
                        if (limitAttributes) {
                            resultAPI = APIUtil.getAPI(artifact);
                        } else {
                            resultAPI = APIUtil.getAPI(artifact, registry);
                        }
                        if (resultAPI != null) {
                            apiList.add(resultAPI);
                        }
                    }
                } else {
                    if (APIConstants.PROTOTYPED.equals(status) || APIConstants.PUBLISHED.equals(status)) {
                        API resultAPI;
                        if (limitAttributes) {
                            resultAPI = APIUtil.getAPI(artifact);
                        } else {
                            resultAPI = APIUtil.getAPI(artifact, registry);
                        }
                        if (resultAPI != null) {
                            apiList.add(resultAPI);
                        }
                    }
                }
                // Ensure the APIs returned matches the length, there could be an additional API
                // returned due incrementing the pagination limit when getting from registry
                tempLength++;
                if (tempLength >= totalLength) {
                    break;
                }
            }

            apiSet.addAll(apiList);
        }
    } catch (RegistryException e) {
        handleException("Failed to search APIs with type", e);
    }
    result.put("apis", apiSet);
    result.put("length", totalLength);
    result.put("isMore", isMore);
    return result;
}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
 * The method to get APIs in any of the given LC status array
 *
 * @return Map<String, Object>  API result set with pagination information
 * @throws APIManagementException/*w  w  w  .ja va2 s. co m*/
 */
@Override
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end,
        final String[] apiStatus, boolean returnAPITags) throws APIManagementException {

    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
    int totalLength = 0;
    boolean isMore = false;
    String criteria = "lcState=";

    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null)
                || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {//Tenant store anonymous mode
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        }
        this.isTenantModeStoreView = isTenantMode;
        this.requestedTenant = tenantDomain;

        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        List<API> multiVersionedAPIs = new ArrayList<API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
        String paginationLimit = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
                .getAPIManagerConfiguration().getFirstProperty(APIConstants.API_STORE_APIS_PER_PAGE);

        // If the Config exists use it to set the pagination limit
        final int maxPaginationLimit;
        if (paginationLimit != null) {
            // The additional 1 added to the maxPaginationLimit is to help us determine if more
            // APIs may exist so that we know that we are unable to determine the actual total
            // API count. We will subtract this 1 later on so that it does not interfere with
            // the logic of the rest of the application
            int pagination = Integer.parseInt(paginationLimit);

            // Because the store jaggery pagination logic is 10 results per a page we need to set pagination
            // limit to at least 11 or the pagination done at this level will conflict with the store pagination
            // leading to some of the APIs not being displayed
            if (pagination < 11) {
                pagination = 11;
                log.warn(
                        "Value of '" + APIConstants.API_STORE_APIS_PER_PAGE + "' is too low, defaulting to 11");
            }

            maxPaginationLimit = start + pagination + 1;
        }
        // Else if the config is not specified we go with default functionality and load all
        else {
            maxPaginationLimit = Integer.MAX_VALUE;
        }

        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);

        criteria = criteria + APIUtil.getORBasedSearchCriteria(apiStatus);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            if (apiStatus != null && apiStatus.length > 0) {
                List<GovernanceArtifact> genericArtifacts = GovernanceUtils.findGovernanceArtifacts(criteria,
                        userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
                totalLength = PaginationContext.getInstance().getLength();
                if (genericArtifacts == null || genericArtifacts.size() == 0) {
                    result.put("apis", apiSortedSet);
                    result.put("totalLength", totalLength);
                    result.put("isMore", isMore);
                    return result;
                }

                // Check to see if we can speculate that there are more APIs to be loaded
                if (maxPaginationLimit == totalLength) {
                    isMore = true; // More APIs exist so we cannot determine the total API count without incurring a
                    // performance hit
                    --totalLength; // Remove the additional 1 we added earlier when setting max pagination limit
                }
                int tempLength = 0;
                for (GovernanceArtifact artifact : genericArtifacts) {

                    API api = null;
                    try {
                        api = APIUtil.getAPI(artifact);
                    } catch (APIManagementException e) {
                        //log and continue since we want to load the rest of the APIs.
                        log.error("Error while loading API "
                                + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
                    }
                    if (api != null) {
                        if (returnAPITags) {
                            String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
                            Set<String> tags = new HashSet<String>();
                            org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath);
                            for (org.wso2.carbon.registry.core.Tag tag1 : tag) {
                                tags.add(tag1.getTagName());
                            }
                            api.addTags(tags);
                        }

                        String key;
                        //Check the configuration to allow showing multiple versions of an API true/false
                        if (!displayMultipleVersions) { //If allow only showing the latest version of an API
                            key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                            API existingAPI = latestPublishedAPIs.get(key);
                            if (existingAPI != null) {
                                // If we have already seen an API with the same name, make sure
                                // this one has a higher version number
                                if (versionComparator.compare(api, existingAPI) > 0) {
                                    latestPublishedAPIs.put(key, api);
                                }
                            } else {
                                // We haven't seen this API before
                                latestPublishedAPIs.put(key, api);
                            }
                        } else { //If allow showing multiple versions of an API
                            multiVersionedAPIs.add(api);
                        }
                    }
                    tempLength++;
                    if (tempLength >= totalLength) {
                        break;
                    }
                }
                if (!displayMultipleVersions) {
                    apiSortedSet.addAll(latestPublishedAPIs.values());
                    result.put("apis", apiSortedSet);
                    result.put("totalLength", totalLength);
                    result.put("isMore", isMore);
                    return result;
                } else {
                    apiVersionsSortedSet.addAll(multiVersionedAPIs);
                    result.put("apis", apiVersionsSortedSet);
                    result.put("totalLength", totalLength);
                    result.put("isMore", isMore);
                    return result;
                }
            }
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("apis", apiSortedSet);
    result.put("totalLength", totalLength);
    result.put("isMore", isMore);
    return result;

}

From source file:org.wso2.carbon.apimgt.impl.APIConsumerImpl.java

/**
 * The method to get All PUBLISHED and DEPRECATED APIs, to Store view
 *
 * @return Set<API>  Set of APIs/*  ww  w. j  a v a2s  .c  om*/
 * @throws APIManagementException
 */
@Deprecated
public Map<String, Object> getAllPaginatedAPIs(String tenantDomain, int start, int end)
        throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
    int totalLength = 0;
    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null)
                || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {//Tenant store anonymous mode
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                    .getTenantId(tenantDomain);
            userRegistry = ServiceReferenceHolder.getInstance().getRegistryService()
                    .getGovernanceUserRegistry(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME, tenantId);
            PrivilegedCarbonContext.getThreadLocalCarbonContext()
                    .setUsername(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        }
        this.isTenantModeStoreView = isTenantMode;
        this.requestedTenant = tenantDomain;

        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        List<API> multiVersionedAPIs = new ArrayList<API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();

        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);

        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);

        boolean noPublishedAPIs = false;
        if (artifactManager != null) {

            //Create the search attribute map for PUBLISHED APIs
            Map<String, List<String>> listMap = new HashMap<String, List<String>>();
            listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
                {
                    add(APIConstants.PUBLISHED);
                }
            });

            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                noPublishedAPIs = true;
            }
            int publishedAPICount;
            if (genericArtifacts != null) {
                for (GenericArtifact artifact : genericArtifacts) {
                    // adding the API provider can mark the latest API .
                    //                        String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
                    API api = APIUtil.getAPI(artifact);
                    if (api != null) {
                        String key;
                        //Check the configuration to allow showing multiple versions of an API true/false
                        if (!displayMultipleVersions) { //If allow only showing the latest version of an API
                            key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                            API existingAPI = latestPublishedAPIs.get(key);
                            if (existingAPI != null) {
                                // If we have already seen an API with the same name, make sure
                                // this one has a higher version number
                                if (versionComparator.compare(api, existingAPI) > 0) {
                                    latestPublishedAPIs.put(key, api);
                                }
                            } else {
                                // We haven't seen this API before
                                latestPublishedAPIs.put(key, api);
                            }
                        } else { //If allow showing multiple versions of an API
                            //                            key = api.getId().getProviderName() + ":" + api.getId().getApiName() + ":" + api.getId()
                            //                                    .getVersion();
                            multiVersionedAPIs.add(api);
                        }
                    }
                }
            }
            if (!displayMultipleVersions) {
                publishedAPICount = latestPublishedAPIs.size();
            } else {
                publishedAPICount = multiVersionedAPIs.size();
            }
            if ((start + end) > publishedAPICount) {
                if (publishedAPICount > 0) {
                    /*Starting to retrieve DEPRECATED APIs*/
                    start = 0;
                    /* publishedAPICount is always less than end*/
                    end = end - publishedAPICount;
                } else {
                    start = start - totalLength;
                }
                PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE);
                //Create the search attribute map for DEPRECATED APIs
                Map<String, List<String>> listMapForDeprecatedAPIs = new HashMap<String, List<String>>();
                listMapForDeprecatedAPIs.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {
                    {
                        add(APIConstants.DEPRECATED);
                    }
                });

                GenericArtifact[] genericArtifactsForDeprecatedAPIs = artifactManager
                        .findGenericArtifacts(listMapForDeprecatedAPIs);
                totalLength = totalLength + PaginationContext.getInstance().getLength();
                if ((genericArtifactsForDeprecatedAPIs == null || genericArtifactsForDeprecatedAPIs.length == 0)
                        && noPublishedAPIs) {
                    result.put("apis", apiSortedSet);
                    result.put("totalLength", totalLength);
                    return result;
                }

                if (genericArtifactsForDeprecatedAPIs != null) {
                    for (GenericArtifact artifact : genericArtifactsForDeprecatedAPIs) {
                        // adding the API provider can mark the latest API .

                        API api = APIUtil.getAPI(artifact);

                        if (api != null) {
                            String key;
                            //Check the configuration to allow showing multiple versions of an API true/false
                            if (!displayMultipleVersions) { //If allow only showing the latest version of an API
                                key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                                API existingAPI = latestPublishedAPIs.get(key);
                                if (existingAPI != null) {
                                    // If we have already seen an API with the same name, make sure
                                    // this one has a higher version number
                                    if (versionComparator.compare(api, existingAPI) > 0) {
                                        latestPublishedAPIs.put(key, api);
                                    }
                                } else {
                                    // We haven't seen this API before
                                    latestPublishedAPIs.put(key, api);
                                }
                            } else { //If allow showing multiple versions of an API
                                multiVersionedAPIs.add(api);
                            }
                        }
                    }
                }
            }

            if (!displayMultipleVersions) {
                for (API api : latestPublishedAPIs.values()) {
                    apiSortedSet.add(api);
                }
                result.put("apis", apiSortedSet);
                result.put("totalLength", totalLength);
                return result;
            } else {
                apiVersionsSortedSet.addAll(multiVersionedAPIs);
                result.put("apis", apiVersionsSortedSet);
                result.put("totalLength", totalLength);
                return result;
            }
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("apis", apiSortedSet);
    result.put("totalLength", totalLength);
    return result;
}

From source file:org.sakaiproject.content.impl.BaseContentService.java

/**
 * Make a deep copy of a collection. /*from w w  w .  j av a2s  .  co m*/
 * Creates a new collection with an id similar to new_folder_id and recursively copies all nested collections and resources within thisCollection to the new collection.
 * Only used in "copyIntoFolder" for now
 * 
 * @param thisCollection
 *        The collection to be copied
 * @param new_folder_id
 *        The desired id of the new collection.
 * @return The full id of the copied collection (which may be a slight variation on the desired id to ensure uniqueness).
 * @exception PermissionException
 *            if the user does not have permissions to perform the operations
 * @exception IdUnusedException
 *            if the collection id is not found. ???
 * @exception TypeException
 *            if the resource is not a collection.
 * @exception InUseException
 *            if the collection is locked by someone else.
 * @exception IdUsedException
 *            if a unique id cannot be found for the new collection after some arbitrary number of attempts to find a unique variation of the new_folder_id (@see MAXIMUM_ATTEMPTS_FOR_UNIQUENESS).
 * @exception ServerOverloadException
 *            if the server is configured to save content bodies in the server's filesystem and an error occurs trying to access the filesystem.
 */
protected String deepcopyCollection(ContentCollection thisCollection, String new_folder_id)
        throws PermissionException, IdUnusedException, TypeException, InUseException, IdLengthException,
        IdUniquenessException, OverQuotaException, IdUsedException, ServerOverloadException {
    String name = isolateName(new_folder_id);
    ResourceProperties properties = thisCollection.getProperties();
    ResourcePropertiesEdit newProps = duplicateResourceProperties(properties, thisCollection.getId());
    if (newProps.getProperty(ResourceProperties.PROP_DISPLAY_NAME) == null) {
        name = Validator.escapeResourceName(name);

        newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
    }

    if (M_log.isDebugEnabled())
        M_log.debug("deepCopyCollection adding colletion=" + new_folder_id + " name=" + name);

    String base_id = new_folder_id + "-";
    boolean still_trying = true;
    int attempt = 0;
    ContentCollection newCollection = null;
    try {
        try {
            newCollection = addCollection(new_folder_id, newProps);
            // use the creator and creation-date of the original instead of the copy
            BaseCollectionEdit collection = (BaseCollectionEdit) m_storage
                    .editCollection(newCollection.getId());
            if (isPubView(thisCollection.getId())) {
                collection.setPublicAccess();
            }
            collection.setAvailability(thisCollection.isHidden(), thisCollection.getReleaseDate(),
                    thisCollection.getReleaseDate());
            m_storage.commitCollection(collection);

            if (M_log.isDebugEnabled())
                M_log.debug("deepCopyCollection  top level created successful");
            still_trying = false;
        } catch (IdUsedException e) {
            try {
                checkCollection(new_folder_id);
            } catch (Exception ee) {
                throw new IdUniquenessException(new_folder_id);
            }
        }
        String containerId = this.isolateContainingId(new_folder_id);
        ContentCollection containingCollection = findCollection(containerId);
        SortedSet<String> siblings = new TreeSet<String>();
        siblings.addAll(containingCollection.getMembers());

        while (still_trying) {
            attempt++;
            if (attempt >= MAXIMUM_ATTEMPTS_FOR_UNIQUENESS) {
                throw new IdUniquenessException(new_folder_id);
            }
            new_folder_id = base_id + attempt;
            if (!siblings.contains(new_folder_id)) {
                newProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name + "-" + attempt);
                try {
                    newCollection = addCollection(new_folder_id, newProps);
                    BaseCollectionEdit collection = (BaseCollectionEdit) m_storage
                            .editCollection(newCollection.getId());
                    if (isPubView(thisCollection.getId())) {
                        collection.setPublicAccess();
                    }
                    collection.setAvailability(thisCollection.isHidden(), thisCollection.getReleaseDate(),
                            thisCollection.getReleaseDate());
                    m_storage.commitCollection(collection);
                    still_trying = false;
                } catch (IdUsedException inner_e) {
                    // try again
                }
            }
        }

        List<String> members = thisCollection.getMembers();

        if (M_log.isDebugEnabled())
            M_log.debug("deepCopyCollection size=" + members.size());

        Iterator<String> memberIt = members.iterator();
        while (memberIt.hasNext()) {
            String member_id = (String) memberIt.next();
            if (isAvailable(member_id)) {
                copyIntoFolder(member_id, new_folder_id);
            }
        }

    } catch (InconsistentException e) {
        throw new TypeException(new_folder_id);
    } catch (IdInvalidException e) {
        throw new TypeException(new_folder_id);
    }

    return new_folder_id;

}

From source file:org.sakaiproject.content.impl.BaseContentService.java

/**
 * Create the site's dropbox collection and one for each qualified user that the current user can make.
 * //w  ww.  j a  va2 s .c om
 * @param siteId
 *        the Site id.
 */
public void createDropboxCollection(String siteId) {
    // make sure we are in a worksite, not a workspace
    if (m_siteService.isUserSite(siteId) || m_siteService.isSpecialSite(siteId)) {
        return;
    }

    // do our ONE security check to see if the current user can create the
    // dropbox and all inner folders
    if (!isDropboxMaintainer(siteId)) {
        createIndividualDropbox(siteId);
        return;
    }

    // form the site's dropbox collection
    String dropbox = COLLECTION_DROPBOX + siteId + "/";

    try {
        // try to create if it doesn't exist
        if (findCollection(dropbox) == null) {
            ContentCollectionEdit edit = addValidPermittedCollection(dropbox);
            ResourcePropertiesEdit props = edit.getPropertiesEdit();
            try {
                Site site = m_siteService.getSite(siteId);
            } catch (IdUnusedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // these need to be moved to language bundle
            props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, siteId + DROPBOX_ID);
            props.addProperty(ResourceProperties.PROP_DESCRIPTION, rb.getString("use2"));
            // props.addProperty(ResourceProperties.PROP_DESCRIPTION, PROP_SITE_DROPBOX_DESCRIPTION);

            commitCollection(edit);
        }
    } catch (TypeException e) {
        M_log.warn("createDropboxCollection: TypeException: " + dropbox);
        return;
    } catch (IdUsedException e) {
        M_log.warn("createDropboxCollection: IdUsedException: " + dropbox);
        return;
    } catch (InconsistentException e) {
        M_log.warn("createDropboxCollection(): InconsistentException: " + dropbox);
        M_log.warn("createDropboxCollection(): InconsistentException: " + e.getMessage());
        return;
    }
    //      catch (PermissionException e) 
    //      {
    //         M_log.warn("createDropboxCollection(): PermissionException: " + dropbox);
    //         return;
    //      }

    SortedSet<String> members = new TreeSet<String>();
    try {
        ContentCollection topDropbox = findCollection(dropbox);
        members.addAll((List<String>) topDropbox.getMembers());
    } catch (TypeException e) {
        M_log.warn("createDropboxCollection(): File exists where dropbox collection is expected: " + dropbox);
    }

    // The AUTH_DROPBOX_OWN is granted within the site, so we can ask for all the users who have this ability
    // using just the dropbox collection
    List users = m_securityService.unlockUsers(AUTH_DROPBOX_OWN, getReference(dropbox));
    for (Iterator it = users.iterator(); it.hasNext();) {
        User user = (User) it.next();

        // the folder id for this user's dropbox in this group
        String userFolder = dropbox + user.getId() + "/";

        // see if it exists - add if it doesn't
        try {

            if (!members.remove(userFolder)) {
                if (findCollection(userFolder) == null) // This check it probably redundant
                {
                    ContentCollectionEdit edit = addValidPermittedCollection(userFolder);
                    ResourcePropertiesEdit props = edit.getPropertiesEdit();
                    props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, getDisplayName(user));
                    props.addProperty(ResourceProperties.PROP_DESCRIPTION, rb.getString("use1"));
                    commitCollection(edit);
                }
            }
        } catch (TypeException e) {
            M_log.warn("createDropboxCollectionn(): TypeException: " + userFolder);
        } catch (IdUsedException e) {
            M_log.warn("createDropboxCollectionn(): idUsedException: " + userFolder);
        } catch (InconsistentException e) {
            M_log.warn("createDropboxCollection(): InconsistentException: " + userFolder);
        }
    }
    // Attempt to remove all empty dropboxes that are no longer members of the site.
    for (String member : members) {
        try {
            ContentCollection folder = getCollection(member);
            if (folder.getMemberCount() == 0) {
                removeCollection(member);
                M_log.info("createDropboxCollection(): Removed the empty dropbox collection for member: "
                        + member);
            } else {
                M_log.warn("createDropboxCollection(): Could not remove the dropbox collection for member ("
                        + member + ") because the root contains " + folder.getMemberCount() + " members");
            }
        } catch (IdUnusedException e) {
            M_log.warn("createDropboxCollection(): Could not find collection to delete: " + member);
        } catch (PermissionException e) {
            M_log.warn("createDropboxCollection(): Unable to delete collection due to lack of permission: "
                    + member);
        } catch (InUseException e) {
            M_log.warn("createDropboxCollection(): Unable to delete collection as collection is in use: "
                    + member);
        } catch (ServerOverloadException e) {
            M_log.warn("createDropboxCollection(): Unable to delete collection as server is overloaded: "
                    + member);
        } catch (TypeException e) {
            M_log.warn("createDropboxCollection(): Unable to delete as it doesn't appear to be a collection: "
                    + member);
        }
    }
}

From source file:org.sakaiproject.content.impl.BaseContentService.java

public ContentResourceEdit addResource(String collectionId, String basename, String extension,
        int maximum_tries) throws PermissionException, IdUniquenessException, IdLengthException,
        IdInvalidException, IdUnusedException, OverQuotaException, ServerOverloadException {
    // check the id's validity (this may throw IdInvalidException)
    // use only the "name" portion, separated at the end
    try {/* w  ww . j  a v  a2s . c om*/
        checkCollection(collectionId);
    } catch (TypeException e) {
        throw new IdUnusedException(collectionId);
    }

    if (basename == null) {
        throw new IdInvalidException("");
    }

    if (extension == null) {
        extension = "";
    } else {
        extension = extension.trim();
        if (extension.equals("") || extension.startsWith(".")) {
            // do nothing
        } else {
            extension = "." + extension;
        }
    }

    basename = Validator.escapeResourceName(basename.trim());
    extension = Validator.escapeResourceName(extension);

    String name = basename + extension;
    String id = collectionId + name;
    if (id.length() > ContentHostingService.MAXIMUM_RESOURCE_ID_LENGTH) {
        throw new IdLengthException(id);
    }

    BaseResourceEdit edit = null;

    int attempts = 0;
    boolean done = false;
    while (!done && attempts < maximum_tries) {
        try {
            edit = (BaseResourceEdit) addResource(id);
            done = true;

            // add live properties
            addLiveResourceProperties(edit);

            ResourceProperties props = edit.getPropertiesEdit();
            props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);

            // track event
            edit.setEvent(EVENT_RESOURCE_ADD);
        } catch (InconsistentException inner_e) {
            throw new IdInvalidException(id);
        } catch (IdUsedException e) {
            SortedSet<String> siblings = new TreeSet<String>();
            try {
                ContentCollection collection = findCollection(collectionId);
                siblings.addAll(collection.getMembers());
            } catch (TypeException inner_e) {
                throw new IdUnusedException(collectionId);
            }

            // see end of loop for condition that enforces attempts <= limit)
            do {
                attempts++;
                name = basename + "-" + attempts + extension;
                id = collectionId + name;

                if (attempts >= maximum_tries) {
                    throw new IdUniquenessException(id);
                }

                if (id.length() > MAXIMUM_RESOURCE_ID_LENGTH) {
                    throw new IdLengthException(id);
                }
            } while (siblings.contains(id));
        }

    }

    threadLocalManager.set("members@" + collectionId, null);
    //threadLocalManager.set("getCollections@" + collectionId, null);
    threadLocalManager.set("getResources@" + collectionId, null);

    //      if (edit == null)
    //      {
    //         throw new IdUniquenessException(id);
    //      }

    return edit;

}