Search in sources :

Example 16 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class AbstractAPIManager method searchPaginatedAPIsByContent.

/**
 * Search api resources by their content
 *
 * @param registry
 * @param searchQuery
 * @param start
 * @param end
 * @return
 * @throws APIManagementException
 */
public Map<String, Object> searchPaginatedAPIsByContent(Registry registry, int tenantId, String searchQuery, int start, int end, boolean limitAttributes) throws APIManagementException {
    SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
    SortedSet<APIProduct> apiProductSet = new TreeSet<APIProduct>(new APIProductNameComparator());
    Map<Documentation, API> docMap = new HashMap<Documentation, API>();
    Map<Documentation, APIProduct> productDocMap = new HashMap<Documentation, APIProduct>();
    Map<String, Object> result = new HashMap<String, Object>();
    int totalLength = 0;
    boolean isMore = false;
    // SortedSet<Object> compoundResult = new TreeSet<Object>(new ContentSearchResultNameComparator());
    ArrayList<Object> compoundResult = new ArrayList<Object>();
    try {
        GenericArtifactManager apiArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifactManager docArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        String paginationLimit = 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);
            // 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 // Else if the config is not specified we go with default functionality and load all
        {
            maxPaginationLimit = Integer.MAX_VALUE;
        }
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        if (tenantId == -1) {
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        }
        UserRegistry systemUserRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME, tenantId);
        ContentBasedSearchService contentBasedSearchService = new ContentBasedSearchService();
        String newSearchQuery = getSearchQuery(searchQuery);
        String[] searchQueries = newSearchQuery.split("&");
        String apiState = "";
        String publisherRoles = "";
        Map<String, String> attributes = new HashMap<String, String>();
        for (String searchCriterea : searchQueries) {
            String[] keyVal = searchCriterea.split("=");
            if (APIConstants.STORE_VIEW_ROLES.equals(keyVal[0])) {
                attributes.put("propertyName", keyVal[0]);
                attributes.put("rightPropertyValue", keyVal[1]);
                attributes.put("rightOp", "eq");
            } else if (APIConstants.PUBLISHER_ROLES.equals(keyVal[0])) {
                publisherRoles = keyVal[1];
            } else {
                if (APIConstants.LCSTATE_SEARCH_KEY.equals(keyVal[0])) {
                    apiState = keyVal[1];
                    continue;
                }
                attributes.put(keyVal[0], keyVal[1]);
            }
        }
        // check whether the new document indexer is engaged
        RegistryConfigLoader registryConfig = RegistryConfigLoader.getInstance();
        Map<String, Indexer> indexerMap = registryConfig.getIndexerMap();
        Indexer documentIndexer = indexerMap.get(APIConstants.DOCUMENT_MEDIA_TYPE_KEY);
        String complexAttribute;
        if (documentIndexer != null && documentIndexer instanceof DocumentIndexer) {
            // field check on document_indexed was added to prevent unindexed(by new DocumentIndexer) from coming up as search results
            // on indexed documents this property is always set to true
            complexAttribute = ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE) + " OR mediaType_s:(" + ClientUtils.escapeQueryChars(APIConstants.DOCUMENT_RXT_MEDIA_TYPE) + " AND document_indexed_s:true)";
            // this was designed this way so that content search can be fully functional if registry is re-indexed after engaging DocumentIndexer
            if (!StringUtils.isEmpty(publisherRoles)) {
                complexAttribute = "(" + ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE) + " AND publisher_roles_ss:" + publisherRoles + ") OR mediaType_s:(" + ClientUtils.escapeQueryChars(APIConstants.DOCUMENT_RXT_MEDIA_TYPE) + " AND publisher_roles_s:" + publisherRoles + ")";
            }
        } else {
            // document indexer required for document content search is not engaged, therefore carry out the search only for api artifact contents
            complexAttribute = ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE);
            if (!StringUtils.isEmpty(publisherRoles)) {
                complexAttribute = "(" + ClientUtils.escapeQueryChars(APIConstants.API_RXT_MEDIA_TYPE) + " AND publisher_roles_ss:" + publisherRoles + ")";
            }
        }
        attributes.put(APIConstants.DOCUMENTATION_SEARCH_MEDIA_TYPE_FIELD, complexAttribute);
        attributes.put(APIConstants.API_OVERVIEW_STATUS, apiState);
        SearchResultsBean resultsBean = contentBasedSearchService.searchByAttribute(attributes, systemUserRegistry);
        String errorMsg = resultsBean.getErrorMessage();
        if (errorMsg != null) {
            handleException(errorMsg);
        }
        ResourceData[] resourceData = resultsBean.getResourceDataList();
        if (resourceData == null || resourceData.length == 0) {
            result.put("apis", compoundResult);
            result.put("length", 0);
            result.put("isMore", isMore);
        }
        totalLength = PaginationContext.getInstance().getLength();
        // Check to see if we can speculate that there are more APIs to be loaded
        if (maxPaginationLimit == totalLength) {
            // More APIs exist, cannot determine total API count without incurring perf hit
            isMore = true;
            // Remove the additional 1 added earlier when setting max pagination limit
            --totalLength;
        }
        for (ResourceData data : resourceData) {
            String resourcePath = data.getResourcePath();
            if (resourcePath.contains(APIConstants.APIMGT_REGISTRY_LOCATION)) {
                int index = resourcePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
                resourcePath = resourcePath.substring(index);
                Resource resource = registry.get(resourcePath);
                if (APIConstants.DOCUMENT_RXT_MEDIA_TYPE.equals(resource.getMediaType()) || APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE.equals(resource.getMediaType())) {
                    if (resourcePath.contains(APIConstants.INLINE_DOCUMENT_CONTENT_DIR)) {
                        int indexOfContents = resourcePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
                        resourcePath = resourcePath.substring(0, indexOfContents) + data.getName();
                    }
                    Resource docResource = registry.get(resourcePath);
                    String docArtifactId = docResource.getUUID();
                    GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
                    Documentation doc = APIUtil.getDocumentation(docArtifact);
                    API associatedAPI = null;
                    APIProduct associatedAPIProduct = null;
                    int indexOfDocumentation = resourcePath.indexOf(APIConstants.DOCUMENTATION_KEY);
                    String apiPath = resourcePath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
                    Resource apiResource = registry.get(apiPath);
                    String apiArtifactId = apiResource.getUUID();
                    if (apiArtifactId != null) {
                        GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                        if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.AuditLogConstants.API_PRODUCT)) {
                            associatedAPIProduct = APIUtil.getAPIProduct(apiArtifact, registry);
                        } else {
                            associatedAPI = APIUtil.getAPI(apiArtifact, registry);
                        }
                    } else {
                        throw new GovernanceException("artifact id is null of " + apiPath);
                    }
                    if (associatedAPI != null && doc != null) {
                        docMap.put(doc, associatedAPI);
                    }
                    if (associatedAPIProduct != null && doc != null) {
                        productDocMap.put(doc, associatedAPIProduct);
                    }
                } else {
                    String apiArtifactId = resource.getUUID();
                    API api;
                    APIProduct apiProduct;
                    if (apiArtifactId != null) {
                        GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                        if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.API_PRODUCT)) {
                            apiProduct = APIUtil.getAPIProduct(apiArtifact, registry);
                            apiProductSet.add(apiProduct);
                        } else {
                            api = APIUtil.getAPI(apiArtifact, registry);
                            apiSet.add(api);
                        }
                    } else {
                        throw new GovernanceException("artifact id is null for " + resourcePath);
                    }
                }
            }
        }
        compoundResult.addAll(apiSet);
        compoundResult.addAll(apiProductSet);
        compoundResult.addAll(docMap.entrySet());
        compoundResult.addAll(productDocMap.entrySet());
        compoundResult.sort(new ContentSearchResultNameComparator());
    } catch (RegistryException e) {
        handleException("Failed to search APIs by content", e);
    } catch (IndexerException e) {
        handleException("Failed to search APIs by content", e);
    }
    result.put("apis", compoundResult);
    result.put("length", totalLength);
    result.put("isMore", isMore);
    return result;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) DocumentIndexer(org.wso2.carbon.apimgt.impl.indexing.indexer.DocumentIndexer) Indexer(org.wso2.carbon.registry.indexing.indexer.Indexer) TreeSet(java.util.TreeSet) SearchResultsBean(org.wso2.carbon.registry.indexing.service.SearchResultsBean) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) DocumentIndexer(org.wso2.carbon.apimgt.impl.indexing.indexer.DocumentIndexer) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) ResourceData(org.wso2.carbon.registry.common.ResourceData) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ContentBasedSearchService(org.wso2.carbon.registry.indexing.service.ContentBasedSearchService) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) RegistryConfigLoader(org.wso2.carbon.registry.indexing.RegistryConfigLoader) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) JSONObject(org.json.simple.JSONObject) ContentSearchResultNameComparator(org.wso2.carbon.apimgt.impl.utils.ContentSearchResultNameComparator) APIAPIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIAPIProductNameComparator) APIProductNameComparator(org.wso2.carbon.apimgt.impl.utils.APIProductNameComparator)

Example 17 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateAPIProductInformation.

protected void populateAPIProductInformation(String uuid, String organization, APIProduct apiProduct) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    apiProduct.setOrganization(organization);
    ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
    apiProduct.setRating(Float.toString(APIUtil.getAverageRating(apiProduct.getProductId())));
    List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProduct.getId());
    Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
    for (APIProductResource resource : resources) {
        List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
        ListIterator it = resourceScopes.listIterator();
        while (it.hasNext()) {
            Scope resourceScope = (Scope) it.next();
            String scopeKey = resourceScope.getKey();
            if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
                resourceScope = APIUtil.getScopeByName(scopeKey, organization);
                uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
            } else {
                resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
            }
            it.set(resourceScope);
        }
    }
    for (APIProductResource resource : resources) {
        String resourceAPIUUID = resource.getApiIdentifier().getUUID();
        resource.setApiId(resourceAPIUUID);
        try {
            PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, resourceAPIUUID);
            API api = APIMapper.INSTANCE.toApi(publisherAPI);
            if (api.isAdvertiseOnly()) {
                resource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
            } else {
                resource.setEndpointConfig(api.getEndpointConfig());
            }
            resource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        } catch (APIPersistenceException e) {
            throw new APIManagementException("Error while retrieving the api for api product " + e);
        }
    }
    apiProduct.setProductResources(resources);
    // UUID
    if (apiProduct.getUuid() == null) {
        apiProduct.setUuid(uuid);
    }
    // environment
    String environmentString = null;
    if (apiProduct.getEnvironments() != null) {
        environmentString = String.join(",", apiProduct.getEnvironments());
    }
    apiProduct.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIProductIdentifier productIdentifier = apiProduct.getId();
    WorkflowDTO workflow;
    String currentApiProductUuid = uuid;
    if (apiProduct.isRevision() && apiProduct.getRevisionedApiProductId() != null) {
        currentApiProductUuid = apiProduct.getRevisionedApiProductId();
    }
    workflow = APIUtil.getAPIWorkflowStatus(currentApiProductUuid, WF_TYPE_AM_API_PRODUCT_STATE);
    if (workflow != null) {
        WorkflowStatus status = workflow.getStatus();
        apiProduct.setWorkflowStatus(status.toString());
    }
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = apiProduct.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (apiProduct.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, apiProduct.getId().getName());
    apiProduct.setAvailableTiers(availableTier);
    // Scopes
    /*
        Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(api.getId(), requestedTenantDomain);
        apiProduct.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        */
    // templates
    String resourceConfigsString = null;
    if (apiProduct.getDefinition() != null) {
        resourceConfigsString = apiProduct.getDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
        apiProduct.setDefinition(resourceConfigsString);
    }
    // CORS . if null is returned, set default config from the configuration
    if (apiProduct.getCorsConfiguration() == null) {
        apiProduct.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = apiProduct.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            // todo-category: optimize this loop with breaks
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        apiProduct.setApiCategories(categoryList);
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Tier(org.wso2.carbon.apimgt.api.model.Tier) ListIterator(java.util.ListIterator) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 18 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method deleteAPIProduct.

@Override
public void deleteAPIProduct(Organization org, String apiId) throws APIPersistenceException {
    boolean tenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        tenantFlowStarted = holder.isTenantFlowStarted();
        Registry registry = holder.getRegistry();
        GovernanceUtils.loadGovernanceArtifacts((UserRegistry) registry);
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when deleting API Product" + apiId;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        GenericArtifact apiProductArtifact = artifactManager.getGenericArtifact(apiId);
        APIProductIdentifier identifier = new APIProductIdentifier(apiProductArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER), apiProductArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME), apiProductArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
        // this is the product resource collection path
        String productResourcePath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + RegistryPersistenceUtil.replaceEmailDomain(identifier.getProviderName()) + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion();
        // this is the product rxt instance path
        String apiProductArtifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + RegistryPersistenceUtil.replaceEmailDomain(identifier.getProviderName()) + RegistryConstants.PATH_SEPARATOR + identifier.getName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
        Resource apiProductResource = registry.get(productResourcePath);
        String productResourceUUID = apiProductResource.getUUID();
        if (productResourceUUID == null) {
            throw new APIManagementException("artifact id is null for : " + productResourcePath);
        }
        Resource apiArtifactResource = registry.get(apiProductArtifactPath);
        String apiArtifactResourceUUID = apiArtifactResource.getUUID();
        if (apiArtifactResourceUUID == null) {
            throw new APIManagementException("artifact id is null for : " + apiProductArtifactPath);
        }
        // Delete the dependencies associated with the api product artifact
        GovernanceArtifact[] dependenciesArray = apiProductArtifact.getDependencies();
        if (dependenciesArray.length > 0) {
            for (GovernanceArtifact artifact : dependenciesArray) {
                registry.delete(artifact.getPath());
            }
        }
        // delete registry resources
        artifactManager.removeGenericArtifact(apiProductArtifact);
        artifactManager.removeGenericArtifact(productResourceUUID);
        /* remove empty directories */
        String apiProductCollectionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName();
        if (registry.resourceExists(apiProductCollectionPath)) {
            // at the moment product versioning is not supported so we are directly deleting this collection as
            // this is known to be empty
            registry.delete(apiProductCollectionPath);
        }
        String productProviderPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getName();
        if (registry.resourceExists(productProviderPath)) {
            Resource providerCollection = registry.get(productProviderPath);
            CollectionImpl collection = (CollectionImpl) providerCollection;
            // if there is no api product for given provider delete the provider directory
            if (collection.getChildCount() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("No more API Products from the provider " + identifier.getProviderName() + " found. " + "Removing provider collection from registry");
                }
                registry.delete(productProviderPath);
            }
        }
    } catch (RegistryException e) {
        String msg = "Failed to get API";
        throw new APIPersistenceException(msg, e);
    } catch (APIManagementException e) {
        String msg = "Failed to get API";
        throw new APIPersistenceException(msg, e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) CollectionImpl(org.wso2.carbon.registry.core.CollectionImpl)

Example 19 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method loadloadTenantAPIRXT.

public static void loadloadTenantAPIRXT(String tenant, int tenantID) throws APIManagementException {
    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    UserRegistry registry = null;
    try {
        registry = registryService.getGovernanceSystemRegistry(tenantID);
    } catch (RegistryException e) {
        throw new APIManagementException("Error when create registry instance ", e);
    }
    String rxtDir = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "resources" + File.separator + "rxts";
    File file = new File(rxtDir);
    FilenameFilter filenameFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            // if the file extension is .rxt return true, else false
            return name.endsWith(".rxt");
        }
    };
    String[] rxtFilePaths = file.list(filenameFilter);
    if (rxtFilePaths == null) {
        throw new APIManagementException("rxt files not found in directory " + rxtDir);
    }
    for (String rxtPath : rxtFilePaths) {
        String resourcePath = GovernanceConstants.RXT_CONFIGS_PATH + RegistryConstants.PATH_SEPARATOR + rxtPath;
        // This is  "registry" is a governance registry instance, therefore calculate the relative path to governance.
        String govRelativePath = RegistryUtils.getRelativePathToOriginal(resourcePath, RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH));
        try {
            // calculate resource path
            RegistryAuthorizationManager authorizationManager = new RegistryAuthorizationManager(ServiceReferenceHolder.getUserRealm());
            resourcePath = authorizationManager.computePathOnMount(resourcePath);
            org.wso2.carbon.user.api.AuthorizationManager authManager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
            if (registry.resourceExists(govRelativePath)) {
                // set anonymous user permission to RXTs
                authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
                continue;
            }
            String rxt = FileUtil.readFileToString(rxtDir + File.separator + rxtPath);
            Resource resource = registry.newResource();
            resource.setContent(rxt.getBytes(Charset.defaultCharset()));
            resource.setMediaType(APIConstants.RXT_MEDIA_TYPE);
            registry.put(govRelativePath, resource);
            authManager.authorizeRole(APIConstants.ANONYMOUS_ROLE, resourcePath, ActionConstants.GET);
        } catch (UserStoreException e) {
            throw new APIManagementException("Error while adding role permissions to API", e);
        } catch (IOException e) {
            String msg = "Failed to read rxt files";
            throw new APIManagementException(msg, e);
        } catch (RegistryException e) {
            String msg = "Failed to add rxt to registry ";
            throw new APIManagementException(msg, e);
        }
    }
}
Also used : AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) FilenameFilter(java.io.FilenameFilter) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryAuthorizationManager(org.wso2.carbon.registry.core.jdbc.realm.RegistryAuthorizationManager) UserStoreException(org.wso2.carbon.user.api.UserStoreException) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) File(java.io.File)

Example 20 with Resources

use of org.wso2.carbon.identity.configuration.mgt.core.model.Resources in project carbon-apimgt by wso2.

the class OAS2Parser method generateAPIDefinition.

/**
 * This method generates API definition using the given api's URI templates and the swagger.
 * It will alter the provided swagger definition based on the URI templates. For example: if there is a new
 * URI template which is not included in the swagger, it will be added to the swagger as a basic resource. Any
 * additional resources inside the swagger will be removed from the swagger. Changes to scopes, throtting policies,
 * on the resource will be updated on the swagger
 *
 * @param swaggerData api
 * @param swaggerObj  swagger
 * @return API definition in string format
 * @throws APIManagementException if error occurred when generating API Definition
 */
private String generateAPIDefinition(SwaggerData swaggerData, Swagger swaggerObj) throws APIManagementException {
    // Generates below model using the API's URI template
    // path -> [verb1 -> template1, verb2 -> template2, ..]
    Map<String, Map<String, SwaggerData.Resource>> resourceMap = getResourceMap(swaggerData);
    Iterator<Map.Entry<String, Path>> itr = swaggerObj.getPaths().entrySet().iterator();
    while (itr.hasNext()) {
        Map.Entry<String, Path> pathEntry = itr.next();
        String pathName = pathEntry.getKey();
        Path path = pathEntry.getValue();
        Map<String, SwaggerData.Resource> resourcesForPath = resourceMap.get(pathName);
        if (resourcesForPath == null) {
            // remove paths that are not in URI Templates
            itr.remove();
        } else {
            // If path is available in the URI template, then check for operations(verbs)
            for (Map.Entry<HttpMethod, Operation> operationEntry : path.getOperationMap().entrySet()) {
                HttpMethod httpMethod = operationEntry.getKey();
                Operation operation = operationEntry.getValue();
                SwaggerData.Resource resource = resourcesForPath.get(httpMethod.toString().toUpperCase());
                if (resource == null) {
                    // if particular operation is not available in URI templates, then remove it from swagger
                    path.set(httpMethod.toString().toLowerCase(), null);
                } else {
                    // if operation is available in URI templates, update swagger operation
                    // with auth type, scope etc
                    updateOperationManagedInfo(resource, operation);
                }
            }
            // if there are any verbs (operations) not defined in swagger then add them
            for (Map.Entry<String, SwaggerData.Resource> resourcesForPathEntry : resourcesForPath.entrySet()) {
                String verb = resourcesForPathEntry.getKey();
                SwaggerData.Resource resource = resourcesForPathEntry.getValue();
                HttpMethod method = HttpMethod.valueOf(verb.toUpperCase());
                Operation operation = path.getOperationMap().get(method);
                if (operation == null) {
                    operation = createOperation(resource);
                    path.set(resource.getVerb().toLowerCase(), operation);
                }
            }
        }
    }
    // add to swagger if there are any new templates
    for (Map.Entry<String, Map<String, SwaggerData.Resource>> resourceMapEntry : resourceMap.entrySet()) {
        String path = resourceMapEntry.getKey();
        Map<String, SwaggerData.Resource> verbMap = resourceMapEntry.getValue();
        if (swaggerObj.getPath(path) == null) {
            for (Map.Entry<String, SwaggerData.Resource> verbMapEntry : verbMap.entrySet()) {
                SwaggerData.Resource resource = verbMapEntry.getValue();
                addOrUpdatePathToSwagger(swaggerObj, resource);
            }
        }
    }
    updateSwaggerSecurityDefinition(swaggerObj, swaggerData, "https://test.com");
    updateLegacyScopesFromSwagger(swaggerObj, swaggerData);
    if (StringUtils.isEmpty(swaggerObj.getInfo().getTitle())) {
        swaggerObj.getInfo().setTitle(swaggerData.getTitle());
    }
    if (StringUtils.isEmpty(swaggerObj.getInfo().getVersion())) {
        swaggerObj.getInfo().setVersion(swaggerData.getVersion());
    }
    preserveResourcePathOrderFromAPI(swaggerData, swaggerObj);
    return getSwaggerJsonString(swaggerObj);
}
Also used : RefPath(io.swagger.models.RefPath) Path(io.swagger.models.Path) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) Operation(io.swagger.models.Operation) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpMethod(io.swagger.models.HttpMethod)

Aggregations

ArrayList (java.util.ArrayList)49 Test (org.testng.annotations.Test)41 HashMap (java.util.HashMap)30 File (java.io.File)26 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)24 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)21 IOException (java.io.IOException)20 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)20 FileInputStream (java.io.FileInputStream)19 Map (java.util.Map)17 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)16 JSONObject (org.json.simple.JSONObject)15 Resource (org.wso2.carbon.registry.core.Resource)15 List (java.util.List)14 Scope (org.wso2.carbon.apimgt.core.models.Scope)14 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)13 API (org.wso2.carbon.apimgt.api.model.API)12 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)12 API (org.wso2.carbon.apimgt.core.models.API)12 Collection (org.wso2.carbon.registry.core.Collection)12