Search in sources :

Example 1 with PublisherAPIInfo

use of org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method searchPaginatedPublisherAPIs.

private PublisherAPISearchResult searchPaginatedPublisherAPIs(Registry userRegistry, int tenantIDLocal, String searchQuery, int start, int offset) throws APIManagementException {
    int totalLength = 0;
    PublisherAPISearchResult searchResults = new PublisherAPISearchResult();
    try {
        final int maxPaginationLimit = getMaxPaginationLimit();
        PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        List<GovernanceArtifact> governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(searchQuery, userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
        totalLength = PaginationContext.getInstance().getLength();
        boolean isFound = true;
        if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
            if (searchQuery.contains(APIConstants.API_OVERVIEW_PROVIDER)) {
                searchQuery = searchQuery.replaceAll(APIConstants.API_OVERVIEW_PROVIDER, APIConstants.API_OVERVIEW_OWNER);
                governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(searchQuery, userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
                if (governanceArtifacts == null || governanceArtifacts.size() == 0) {
                    isFound = false;
                }
            } else {
                isFound = false;
            }
        }
        if (!isFound) {
            return searchResults;
        }
        // Check to see if we can speculate that there are more APIs to be loaded
        if (maxPaginationLimit == totalLength) {
            // Remove the additional 1 added earlier when setting max pagination limit
            --totalLength;
        }
        List<PublisherAPIInfo> publisherAPIInfoList = new ArrayList<PublisherAPIInfo>();
        int tempLength = 0;
        for (GovernanceArtifact artifact : governanceArtifacts) {
            PublisherAPIInfo apiInfo = new PublisherAPIInfo();
            String artifactPath = GovernanceUtils.getArtifactPath(userRegistry, artifact.getId());
            Resource apiResource = userRegistry.get(artifactPath);
            apiInfo.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
            apiInfo.setId(artifact.getId());
            apiInfo.setApiName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
            apiInfo.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
            apiInfo.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
            apiInfo.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
            apiInfo.setStatus(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS));
            apiInfo.setThumbnail(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
            apiInfo.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
            apiInfo.setAudience(artifact.getAttribute(APIConstants.API_OVERVIEW_AUDIENCE));
            apiInfo.setCreatedTime(String.valueOf(apiResource.getCreatedTime().getTime()));
            apiInfo.setUpdatedTime(apiResource.getLastModified());
            apiInfo.setGatewayVendor(String.valueOf(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR)));
            apiInfo.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
            publisherAPIInfoList.add(apiInfo);
            // 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;
            }
        }
        // Sort the publisherAPIInfoList according to the API name.
        Collections.sort(publisherAPIInfoList, new PublisherAPISearchResultComparator());
        searchResults.setPublisherAPIInfoList(publisherAPIInfoList);
        searchResults.setReturnedAPIsCount(publisherAPIInfoList.size());
        searchResults.setTotalAPIsCount(totalLength);
    } catch (RegistryException e) {
        String msg = "Failed to search APIs with type";
        throw new APIManagementException(msg, e);
    } finally {
        PaginationContext.destroy();
    }
    return searchResults;
}
Also used : GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.core.Resource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult) PublisherAPISearchResultComparator(org.wso2.carbon.apimgt.persistence.utils.PublisherAPISearchResultComparator)

Example 2 with PublisherAPIInfo

use of org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method searchPaginatedPublisherAPIsByDoc.

private PublisherAPISearchResult searchPaginatedPublisherAPIsByDoc(Registry registry, int tenantID, String searchQuery, String username, int start, int offset) throws APIPersistenceException {
    PublisherAPISearchResult searchResults = new PublisherAPISearchResult();
    try {
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
            log.error(errorMessage);
            throw new APIPersistenceException(errorMessage);
        }
        GenericArtifactManager docArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        if (docArtifactManager == null) {
            String errorMessage = "Doc artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
            log.error(errorMessage);
            throw new APIPersistenceException(errorMessage);
        }
        SolrClient client = SolrClient.getInstance();
        Map<String, String> fields = new HashMap<String, String>();
        fields.put(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, "*" + APIConstants.API_ROOT_LOCATION + "*");
        fields.put(APIConstants.DOCUMENTATION_SEARCH_MEDIA_TYPE_FIELD, "*");
        if (tenantID == -1) {
            tenantID = MultitenantConstants.SUPER_TENANT_ID;
        }
        // PaginationContext.init(0, 10000, "ASC", APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, Integer.MAX_VALUE);
        SolrDocumentList documentList = client.query(searchQuery, tenantID, fields);
        org.wso2.carbon.user.api.AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
        username = MultitenantUtils.getTenantAwareUsername(username);
        List<PublisherAPIInfo> publisherAPIInfoList = new ArrayList<PublisherAPIInfo>();
        for (SolrDocument document : documentList) {
            PublisherAPIInfo apiInfo = new PublisherAPIInfo();
            String filePath = (String) document.getFieldValue("path_s");
            String fileName = (String) document.getFieldValue("resourceName_s");
            int index = filePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
            filePath = filePath.substring(index);
            boolean isAuthorized;
            int indexOfContents = filePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
            String documentationPath = filePath.substring(0, indexOfContents) + fileName;
            String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + documentationPath);
            if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
                isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
            } else {
                isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
            }
            if (isAuthorized) {
                int indexOfDocumentation = filePath.indexOf(APIConstants.DOCUMENTATION_KEY);
                String apiPath = documentationPath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
                path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), RegistryPersistenceUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
                if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
                    isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
                } else {
                    isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
                }
                if (isAuthorized) {
                    Resource resource = registry.get(apiPath);
                    String apiArtifactId = resource.getUUID();
                    if (apiArtifactId != null) {
                        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
                        String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
                        if (APIConstants.PUBLISHED.equals(status) || APIConstants.PROTOTYPED.equals(status)) {
                            apiInfo.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
                            apiInfo.setId(artifact.getId());
                            apiInfo.setApiName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
                            apiInfo.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
                            apiInfo.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
                            apiInfo.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
                            apiInfo.setStatus(status);
                            apiInfo.setThumbnail(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
                            apiInfo.setCreatedTime(String.valueOf(resource.getCreatedTime().getTime()));
                            apiInfo.setUpdatedTime(resource.getLastModified());
                            apiInfo.setGatewayVendor(String.valueOf(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR)));
                            // apiInfo.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
                            apiInfo.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
                            apiInfo.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
                            publisherAPIInfoList.add(apiInfo);
                        }
                    } else {
                        throw new GovernanceException("artifact id is null of " + apiPath);
                    }
                }
            }
        }
        // Sort the publisherAPIInfoList according to the API name.
        Collections.sort(publisherAPIInfoList, new PublisherAPISearchResultComparator());
        searchResults.setPublisherAPIInfoList(publisherAPIInfoList);
        searchResults.setTotalAPIsCount(publisherAPIInfoList.size());
        searchResults.setReturnedAPIsCount(publisherAPIInfoList.size());
    } catch (RegistryException | UserStoreException | APIPersistenceException | IndexerException e) {
        String msg = "Failed to search APIs with type";
        throw new APIPersistenceException(msg, e);
    } finally {
        PaginationContext.destroy();
    }
    return searchResults;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SolrDocument(org.apache.solr.common.SolrDocument) SolrClient(org.wso2.carbon.registry.indexing.solr.SolrClient) UserStoreException(org.wso2.carbon.user.api.UserStoreException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) 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) Resource(org.wso2.carbon.registry.core.Resource) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) SolrDocumentList(org.apache.solr.common.SolrDocumentList) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) PublisherAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult) PublisherAPISearchResultComparator(org.wso2.carbon.apimgt.persistence.utils.PublisherAPISearchResultComparator)

Example 3 with PublisherAPIInfo

use of org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo in project carbon-apimgt by wso2.

the class APIMapperTestCase method testPublisherAPIInfoToAPI.

@Test
public void testPublisherAPIInfoToAPI() throws GovernanceException, APIManagementException {
    PublisherAPIInfo infoapi = new PublisherAPIInfo();
    infoapi.setApiName("TestAPI");
    infoapi.setVersion("1.0");
    infoapi.setType("API");
    infoapi.setStatus("PUBLISHED");
    infoapi.setProviderName("admin");
    infoapi.setDescription("Test API description");
    API mappedAPI = APIMapper.INSTANCE.toApi(infoapi);
    Assert.assertEquals("Mapped api name does not match", mappedAPI.getId().getName(), infoapi.getApiName());
    Assert.assertEquals("Mapped api version does not match", mappedAPI.getId().getVersion(), infoapi.getVersion());
    Assert.assertEquals("Mapped api state does not match", mappedAPI.getStatus(), infoapi.getStatus());
    Assert.assertEquals("Mapped api description does not match", mappedAPI.getDescription(), infoapi.getDescription());
}
Also used : PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) API(org.wso2.carbon.apimgt.api.model.API) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 4 with PublisherAPIInfo

use of org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo in project carbon-apimgt by wso2.

the class AbstractAPIManager method getAllAPIs.

public List<API> getAllAPIs() throws APIManagementException {
    List<API> apiSortedList = new ArrayList<API>();
    Organization org = new Organization(tenantDomain);
    String[] roles = APIUtil.getFilteredUserRoles(username);
    Map<String, Object> properties = APIUtil.getUserProperties(username);
    UserContext userCtx = new UserContext(username, org, properties, roles);
    try {
        PublisherAPISearchResult searchAPIs = apiPersistenceInstance.searchAPIsForPublisher(org, "", 0, Integer.MAX_VALUE, userCtx, null, null);
        if (searchAPIs != null) {
            List<PublisherAPIInfo> list = searchAPIs.getPublisherAPIInfoList();
            for (PublisherAPIInfo publisherAPIInfo : list) {
                API mappedAPI = APIMapper.INSTANCE.toApi(publisherAPIInfo);
                apiSortedList.add(mappedAPI);
            }
        }
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while searching the api ", e);
    }
    Collections.sort(apiSortedList, new APINameComparator());
    return apiSortedList;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult) 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)

Example 5 with PublisherAPIInfo

use of org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo in project carbon-apimgt by wso2.

the class AbstractAPIManagerTestCase method testGetAllApis.

@Test
public void testGetAllApis() throws GovernanceException, APIManagementException, APIPersistenceException {
    PowerMockito.mockStatic(APIUtil.class);
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(apiPersistenceInstance);
    PublisherAPISearchResult value = new PublisherAPISearchResult();
    List<PublisherAPIInfo> publisherAPIInfoList = new ArrayList<PublisherAPIInfo>();
    PublisherAPIInfo pubInfo = new PublisherAPI();
    pubInfo.setApiName("TestAPI");
    pubInfo.setContext("/test");
    pubInfo.setId("xxxxxx");
    pubInfo.setProviderName("test");
    pubInfo.setType("API");
    pubInfo.setVersion("1");
    publisherAPIInfoList.add(pubInfo);
    value.setPublisherAPIInfoList(publisherAPIInfoList);
    PowerMockito.when(apiPersistenceInstance.searchAPIsForPublisher(any(Organization.class), any(String.class), any(Integer.class), any(Integer.class), any(UserContext.class), any(String.class), any(String.class))).thenReturn(value);
    List<API> apis = abstractAPIManager.getAllAPIs();
    Assert.assertNotNull(apis);
    Assert.assertEquals(apis.size(), 1);
}
Also used : Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) UserContext(org.wso2.carbon.apimgt.persistence.dto.UserContext) ArrayList(java.util.ArrayList) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) PublisherAPISearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Aggregations

ArrayList (java.util.ArrayList)6 PublisherAPIInfo (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo)6 PublisherAPISearchResult (org.wso2.carbon.apimgt.persistence.dto.PublisherAPISearchResult)5 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 API (org.wso2.carbon.apimgt.api.model.API)4 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)4 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)4 UserContext (org.wso2.carbon.apimgt.persistence.dto.UserContext)4 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)4 HashMap (java.util.HashMap)3 JSONObject (org.json.simple.JSONObject)3 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 Test (org.junit.Test)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 PublisherAPISearchResultComparator (org.wso2.carbon.apimgt.persistence.utils.PublisherAPISearchResultComparator)2 Resource (org.wso2.carbon.registry.core.Resource)2 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)2 LinkedHashSet (java.util.LinkedHashSet)1 TreeSet (java.util.TreeSet)1