Search in sources :

Example 86 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIProviderImpl method getAllPaginatedAPIs.

@Override
public Map<String, Object> getAllPaginatedAPIs(String tenantDomain, int start, int end) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    List<API> apiSortedList = new ArrayList<API>();
    int totalLength = 0;
    boolean isTenantFlowStarted = false;
    try {
        String paginationLimit = getAPIManagerConfiguration().getFirstProperty(APIConstants.API_PUBLISHER_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_PUBLISHER_APIS_PER_PAGE + "' is too low, defaulting to 11");
            }
            maxPaginationLimit = start + pagination + 1;
        } else // Else if the config is not specifed we go with default functionality and load all
        {
            maxPaginationLimit = Integer.MAX_VALUE;
        }
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
                PrivilegedCarbonContext.startTenantFlow();
                PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
                isTenantFlowStarted = true;
            }
            int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            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);
        }
        PaginationContext.init(start, end, "ASC", APIConstants.PROVIDER_OVERVIEW_NAME, maxPaginationLimit);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            List<GovernanceArtifact> genericArtifacts = null;
            if (isAccessControlRestrictionEnabled && !APIUtil.hasPermission(userNameWithoutChange, APIConstants.Permissions.APIM_ADMIN)) {
                genericArtifacts = GovernanceUtils.findGovernanceArtifacts(getUserRoleListQuery(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
            } else {
                genericArtifacts = GovernanceUtils.findGovernanceArtifacts(new HashMap<String, List<String>>(), userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
            }
            totalLength = PaginationContext.getInstance().getLength();
            if (genericArtifacts == null || genericArtifacts.isEmpty()) {
                result.put("apis", apiSortedList);
                result.put("totalLength", totalLength);
                return result;
            }
            // Check to see if we can speculate that there are more APIs to be loaded
            if (maxPaginationLimit == totalLength) {
                // performance hit
                // Remove the additional 1 we added earlier when setting max pagination limit
                --totalLength;
            }
            int tempLength = 0;
            for (GovernanceArtifact artifact : genericArtifacts) {
                API api = APIUtil.getAPI(artifact);
                if (api != null) {
                    apiSortedList.add(api);
                }
                tempLength++;
                if (tempLength >= totalLength) {
                    break;
                }
            }
            Collections.sort(apiSortedList, new APINameComparator());
        } else {
            String errorMessage = "Failed to retrieve artifact manager when getting paginated APIs of tenant " + tenantDomain;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
    } catch (RegistryException e) {
        handleException("Failed to get all APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all APIs", e);
    } finally {
        PaginationContext.destroy();
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    result.put("apis", apiSortedList);
    result.put("totalLength", totalLength);
    return result;
}
Also used : GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) JSONObject(org.json.simple.JSONObject) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)

Example 87 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIProviderImpl method removeDocumentation.

/**
 * Removes a given documentation
 *
 * @param apiId   APIIdentifier
 * @param docType the type of the documentation
 * @param docName name of the document
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to remove documentation
 */
public void removeDocumentation(APIIdentifier apiId, String docName, String docType, String orgId) throws APIManagementException {
    String docPath = APIUtil.getAPIDocPath(apiId) + docName;
    try {
        String apiArtifactId = registry.get(docPath).getUUID();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when deleting documentation of API " + apiId + " document type " + docType + " document name " + docName;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
        String docFilePath = artifact.getAttribute(APIConstants.DOC_FILE_PATH);
        if (docFilePath != null) {
            File tempFile = new File(docFilePath);
            String fileName = tempFile.getName();
            docFilePath = APIUtil.getDocumentationFilePath(apiId, fileName);
            if (registry.resourceExists(docFilePath)) {
                registry.delete(docFilePath);
            }
        }
    } catch (RegistryException e) {
        handleException("Failed to delete documentation", e);
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 88 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class APIProviderImpl method changeLifeCycleStatusToPublish.

private void changeLifeCycleStatusToPublish(APIProductIdentifier apiIdentifier) throws APIManagementException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(this.tenantDomain, true);
        String productArtifactId = registry.get(APIUtil.getAPIProductPath(apiIdentifier)).getUUID();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(productArtifactId);
        if (apiArtifact != null) {
            apiArtifact.invokeAction("Publish", APIConstants.API_LIFE_CYCLE);
            if (log.isDebugEnabled()) {
                String logMessage = "API Product Status changed successfully. API Product Name: " + apiIdentifier.getName();
                log.debug(logMessage);
            }
        }
    } catch (RegistryException e) {
        throw new APIManagementException("Error while Changing Lifecycle status of API Product " + apiIdentifier.getName(), e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 89 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class CustomAPIIndexerTest method testIndexingCustomProperties.

/**
 * This method checks the indexer's behaviour for APIs which does not have the relevant custom properties.
 *
 * @throws RegistryException Registry Exception.
 * @throws APIManagementException API Management Exception.
 */
@Test
public void testIndexingCustomProperties() throws RegistryException, APIManagementException {
    Resource resource = new ResourceImpl();
    PowerMockito.mockStatic(APIUtil.class);
    Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry) (Mockito.anyObject()), Mockito.anyString())).thenReturn(artifactManager);
    Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)).thenReturn("public");
    PowerMockito.when(APIUtil.getAPI(genericArtifact, userRegistry)).thenReturn(Mockito.mock(API.class));
    resource.setProperty(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + APIConstants.CUSTOM_API_INDEXER_PROPERTY, APIConstants.CUSTOM_API_INDEXER_PROPERTY);
    Assert.assertEquals(APIConstants.OVERVIEW_PREFIX + APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + APIConstants.CUSTOM_API_INDEXER_PROPERTY, indexer.getIndexedDocument(file2Index).getFields().keySet().toArray()[0].toString());
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource) API(org.wso2.carbon.apimgt.api.model.API) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 90 with GenericArtifactManager

use of org.wso2.carbon.governance.api.generic.GenericArtifactManager in project carbon-apimgt by wso2.

the class RegistryPersistenceImplTestCase method testAddAPIProduct.

@Test
public void testAddAPIProduct() throws RegistryException, APIPersistenceException, APIManagementException {
    GenericArtifact artifact = PersistenceHelper.getSampleAPIProductArtifact();
    PublisherAPIProduct publisherAPI = new PublisherAPIProduct();
    publisherAPI.setApiProductName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
    publisherAPI.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
    publisherAPI.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
    APIProduct api = APIProductMapper.INSTANCE.toApiProduct(publisherAPI);
    Registry registry = Mockito.mock(UserRegistry.class);
    Resource resource = new ResourceImpl();
    Mockito.when(registry.get(anyString())).thenReturn(resource);
    Tag[] tags = new Tag[0];
    Mockito.when(registry.getTags(anyString())).thenReturn(tags);
    PowerMockito.mockStatic(RegistryPersistenceUtil.class);
    GenericArtifactManager manager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY)).thenReturn(manager);
    PowerMockito.when(RegistryPersistenceUtil.createAPIProductArtifactContent(any(GenericArtifact.class), any(APIProduct.class))).thenReturn(artifact);
    GenericArtifact newArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(manager.newGovernanceArtifact(new QName(publisherAPI.getApiProductName()))).thenReturn(newArtifact);
    Mockito.when(manager.getGenericArtifact(any(String.class))).thenReturn(newArtifact);
    Mockito.doNothing().when(newArtifact).invokeAction("Publish", APIConstants.API_LIFE_CYCLE);
    Organization org = new Organization(SUPER_TENANT_DOMAIN);
    APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(registry, artifact);
    apiPersistenceInstance.addAPIProduct(org, publisherAPI);
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) Matchers.anyString(org.mockito.Matchers.anyString) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) Tag(org.wso2.carbon.registry.core.Tag) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)95 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)90 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)70 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)63 Registry (org.wso2.carbon.registry.core.Registry)57 Resource (org.wso2.carbon.registry.core.Resource)54 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)51 API (org.wso2.carbon.apimgt.api.model.API)37 Test (org.junit.Test)29 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)29 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)29 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)29 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)28 UserStoreException (org.wso2.carbon.user.api.UserStoreException)27 ArrayList (java.util.ArrayList)26 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)26 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)20 HashMap (java.util.HashMap)18 DocumentationPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException)17 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)16