Search in sources :

Example 21 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method searchAPIProductsForPublisher.

@Override
public PublisherAPIProductSearchResult searchAPIProductsForPublisher(Organization org, String searchQuery, int start, int offset, UserContext ctx) throws APIPersistenceException {
    String requestedTenantDomain = org.getName();
    boolean isTenantFlowStarted = false;
    PublisherAPIProductSearchResult result = new PublisherAPIProductSearchResult();
    try {
        RegistryHolder holder = getRegistry(ctx.getUserame(), requestedTenantDomain);
        Registry userRegistry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        log.debug("Requested query for publisher product search: " + searchQuery);
        String modifiedQuery = RegistrySearchUtil.getPublisherProductSearchQuery(searchQuery, ctx);
        log.debug("Modified query for publisher product search: " + modifiedQuery);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(ctx.getUserame());
        final int maxPaginationLimit = getMaxPaginationLimit();
        PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        List<GovernanceArtifact> governanceArtifacts = GovernanceUtils.findGovernanceArtifacts(modifiedQuery, userRegistry, APIConstants.API_RXT_MEDIA_TYPE, true);
        int totalLength = PaginationContext.getInstance().getLength();
        // 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;
        }
        int tempLength = 0;
        List<PublisherAPIProductInfo> publisherAPIProductInfoList = new ArrayList<PublisherAPIProductInfo>();
        for (GovernanceArtifact artifact : governanceArtifacts) {
            PublisherAPIProductInfo info = new PublisherAPIProductInfo();
            info.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
            info.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
            info.setId(artifact.getId());
            info.setApiProductName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
            info.setState(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS));
            info.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
            info.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
            info.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
            publisherAPIProductInfoList.add(info);
            // 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;
            }
        }
        result.setPublisherAPIProductInfoList(publisherAPIProductInfoList);
        result.setReturnedAPIsCount(publisherAPIProductInfoList.size());
        result.setTotalAPIsCount(totalLength);
    } catch (GovernanceException e) {
        throw new APIPersistenceException("Error while searching APIs ", e);
    } finally {
        PaginationContext.destroy();
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return result;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) ArrayList(java.util.ArrayList) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) PublisherAPIProductSearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProductSearchResult) PublisherAPIProductInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProductInfo)

Example 22 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method changeAPILifeCycle.

@Override
public void changeAPILifeCycle(Organization org, String apiId, String status) throws APIPersistenceException {
    GenericArtifactManager artifactManager = null;
    boolean isTenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        if (GovernanceUtils.findGovernanceArtifactConfiguration(APIConstants.API_KEY, registry) != null) {
            artifactManager = new GenericArtifactManager(registry, APIConstants.API_KEY);
            GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
            String action = LCManagerFactory.getInstance().getLCManager().getTransitionAction(apiArtifact.getLifecycleState().toUpperCase(), status.toUpperCase());
            apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
        } else {
            log.warn("Couldn't find GovernanceArtifactConfiguration of RXT: " + APIConstants.API_KEY + ". Tenant id set in registry : " + ((UserRegistry) registry).getTenantId() + ", Tenant domain set in PrivilegedCarbonContext: " + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
        }
    } catch (GovernanceException e) {
        throw new APIPersistenceException("Error while changing the lifecycle. ", e);
    } catch (RegistryException e) {
        throw new APIPersistenceException("Error while accessing the registry. ", e);
    } catch (PersistenceException e) {
        throw new APIPersistenceException("Error while accessing the lifecycle. ", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.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) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 23 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry 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 24 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method saveOASDefinition.

@Override
public void saveOASDefinition(Organization org, String apiId, String apiDefinition) throws OASPersistenceException {
    boolean isTenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when deleting API " + apiId;
            log.error(errorMessage);
            throw new OASPersistenceException(errorMessage);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
        String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        String visibleRoles = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES);
        String visibility = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY);
        String resourcePath = RegistryPersistenceUtil.getOpenAPIDefinitionFilePath(apiName, apiVersion, apiProviderName);
        resourcePath = resourcePath + APIConstants.API_OAS_DEFINITION_RESOURCE_NAME;
        Resource resource;
        if (!registry.resourceExists(resourcePath)) {
            resource = registry.newResource();
        } else {
            resource = registry.get(resourcePath);
        }
        resource.setContent(apiDefinition);
        resource.setMediaType("application/json");
        registry.put(resourcePath, resource);
        String[] visibleRolesArr = null;
        if (visibleRoles != null) {
            visibleRolesArr = visibleRoles.split(",");
        }
        // Need to set anonymous if the visibility is public
        RegistryPersistenceUtil.clearResourcePermissions(resourcePath, new APIIdentifier(apiProviderName, apiName, apiVersion), ((UserRegistry) registry).getTenantId());
        RegistryPersistenceUtil.setResourcePermissions(apiProviderName, visibility, visibleRolesArr, resourcePath);
    } catch (RegistryException | APIPersistenceException | APIManagementException e) {
        throw new OASPersistenceException("Error while adding OSA Definition for " + apiId, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.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) 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) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 25 with UserRegistry

use of org.wso2.carbon.registry.core.session.UserRegistry in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method getAllTags.

@Override
public Set<Tag> getAllTags(Organization org, UserContext ctx) throws APIPersistenceException {
    TreeSet<Tag> tempTagSet = new TreeSet<Tag>(new Comparator<Tag>() {

        @Override
        public int compare(Tag o1, Tag o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });
    Registry userRegistry = null;
    boolean tenantFlowStarted = false;
    String tagsQueryPath = null;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        tenantFlowStarted = holder.isTenantFlowStarted();
        userRegistry = holder.getRegistry();
        tagsQueryPath = RegistryConstants.QUERIES_COLLECTION_PATH + "/tag-summary";
        Map<String, String> params = new HashMap<String, String>();
        params.put(RegistryConstants.RESULT_TYPE_PROPERTY_NAME, RegistryConstants.TAG_SUMMARY_RESULT_TYPE);
        String userNameLocal;
        if (holder.isAnonymousMode()) {
            userNameLocal = APIConstants.WSO2_ANONYMOUS_USER;
        } else {
            userNameLocal = getTenantAwareUsername(ctx.getUserame());
        }
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userNameLocal);
        Map<String, Tag> tagsData = new HashMap<String, Tag>();
        Map<String, List<String>> criteriaPublished = new HashMap<String, List<String>>();
        criteriaPublished.put(APIConstants.LCSTATE_SEARCH_KEY, new ArrayList<String>() {

            {
                add(APIConstants.PUBLISHED);
            }
        });
        // rxt api media type
        List<TermData> termsPublished = GovernanceUtils.getTermDataList(criteriaPublished, APIConstants.API_OVERVIEW_TAG, APIConstants.API_RXT_MEDIA_TYPE, true);
        if (termsPublished != null) {
            for (TermData data : termsPublished) {
                tempTagSet.add(new Tag(data.getTerm(), (int) data.getFrequency()));
            }
        }
        Map<String, List<String>> criteriaPrototyped = new HashMap<String, List<String>>();
        criteriaPrototyped.put(APIConstants.LCSTATE_SEARCH_KEY, new ArrayList<String>() {

            {
                add(APIConstants.PROTOTYPED);
            }
        });
        // rxt api media type
        List<TermData> termsPrototyped = GovernanceUtils.getTermDataList(criteriaPrototyped, APIConstants.API_OVERVIEW_TAG, APIConstants.API_RXT_MEDIA_TYPE, true);
        if (termsPrototyped != null) {
            for (TermData data : termsPrototyped) {
                tempTagSet.add(new Tag(data.getTerm(), (int) data.getFrequency()));
            }
        }
        return tempTagSet;
    } catch (RegistryException e) {
        try {
            // give a warn.
            if (userRegistry != null && !userRegistry.resourceExists(tagsQueryPath)) {
                log.warn("Failed to retrieve tags query resource at " + tagsQueryPath);
                return Collections.EMPTY_SET;
            }
        } catch (RegistryException e1) {
            // Even if we should ignore this exception, we are logging this as a warn log.
            // The reason is that, this error happens when we try to add some additional logs in an error
            // scenario and it does not affect the execution path.
            log.warn("Unable to execute the resource exist method for tags query resource path : " + tagsQueryPath, e1);
        }
        throw new APIPersistenceException("Failed to get all the tags", e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) HashMap(java.util.HashMap) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) TreeSet(java.util.TreeSet) TermData(org.wso2.carbon.registry.common.TermData) SolrDocumentList(org.apache.solr.common.SolrDocumentList) ArrayList(java.util.ArrayList) List(java.util.List) Tag(org.wso2.carbon.apimgt.api.model.Tag)

Aggregations

UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)147 Resource (org.wso2.carbon.registry.core.Resource)96 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)86 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)84 Test (org.junit.Test)75 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)75 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)66 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)65 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)53 API (org.wso2.carbon.apimgt.api.model.API)47 UserStoreException (org.wso2.carbon.user.api.UserStoreException)44 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)43 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)41 Registry (org.wso2.carbon.registry.core.Registry)39 IOException (java.io.IOException)38 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)37 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)34 ArrayList (java.util.ArrayList)33 QName (javax.xml.namespace.QName)32 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)32