Search in sources :

Example 36 with GenericArtifactManager

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

the class APIProviderImpl method updateApiArtifact.

private String updateApiArtifact(API api, boolean updateMetadata, boolean updatePermissions) throws APIManagementException {
    // Validate Transports
    validateAndSetTransports(api);
    validateAndSetAPISecurity(api);
    boolean transactionCommitted = false;
    String apiUUID = null;
    try {
        registry.beginTransaction();
        String apiArtifactId = registry.get(APIUtil.getAPIPath(api.getId())).getUUID();
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact artifact = artifactManager.getGenericArtifact(apiArtifactId);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when updating API artifact ID " + api.getId();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        String oldStatus = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        Resource apiResource = registry.get(artifact.getPath());
        String oldAccessControlRoles = api.getAccessControlRoles();
        if (apiResource != null) {
            oldAccessControlRoles = registry.get(artifact.getPath()).getProperty(APIConstants.PUBLISHER_ROLES);
        }
        GenericArtifact updateApiArtifact = APIUtil.createAPIArtifactContent(artifact, api);
        String artifactPath = GovernanceUtils.getArtifactPath(registry, updateApiArtifact.getId());
        org.wso2.carbon.registry.core.Tag[] oldTags = registry.getTags(artifactPath);
        if (oldTags != null) {
            for (org.wso2.carbon.registry.core.Tag tag : oldTags) {
                registry.removeTag(artifactPath, tag.getTagName());
            }
        }
        Set<String> tagSet = api.getTags();
        if (tagSet != null) {
            for (String tag : tagSet) {
                registry.applyTag(artifactPath, tag);
            }
        }
        if (updateMetadata && api.getEndpointConfig() != null && !api.getEndpointConfig().isEmpty()) {
            // If WSDL URL get change only we update registry WSDL resource. If its registry resource patch we
            // will skip registry update. Only if this API created with WSDL end point type we need to update
            // wsdls for each update.
            // check for wsdl endpoint
            org.json.JSONObject response1 = new org.json.JSONObject(api.getEndpointConfig());
            boolean isWSAPI = APIConstants.APITransportType.WS.toString().equals(api.getType());
            String wsdlURL;
            if (!APIUtil.isStreamingApi(api) && "wsdl".equalsIgnoreCase(response1.get("endpoint_type").toString()) && response1.has("production_endpoints")) {
                wsdlURL = response1.getJSONObject("production_endpoints").get("url").toString();
                if (APIUtil.isValidWSDLURL(wsdlURL, true)) {
                    String path = APIUtil.createWSDL(registry, api);
                    if (path != null) {
                        // reset the wsdl path to permlink
                        updateApiArtifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
                    }
                }
            }
        }
        artifactManager.updateGenericArtifact(updateApiArtifact);
        // write API Status to a separate property. This is done to support querying APIs using custom query (SQL)
        // to gain performance
        String apiStatus = api.getStatus().toUpperCase();
        saveAPIStatus(artifactPath, apiStatus);
        String[] visibleRoles = new String[0];
        String publisherAccessControlRoles = api.getAccessControlRoles();
        updateRegistryResources(artifactPath, publisherAccessControlRoles, api.getAccessControl(), api.getAdditionalProperties());
        // propagate api status change and access control roles change to document artifact
        String newStatus = updateApiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
        if (!StringUtils.equals(oldStatus, newStatus) || !StringUtils.equals(oldAccessControlRoles, publisherAccessControlRoles)) {
            APIUtil.notifyAPIStateChangeToAssociatedDocuments(artifact, registry);
        }
        if (updatePermissions) {
            APIUtil.clearResourcePermissions(artifactPath, api.getId(), ((UserRegistry) registry).getTenantId());
            String visibleRolesList = api.getVisibleRoles();
            if (visibleRolesList != null) {
                visibleRoles = visibleRolesList.split(",");
            }
            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, artifactPath, registry);
        }
        // attaching api categories to the API
        List<APICategory> attachedApiCategories = api.getApiCategories();
        artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
        if (attachedApiCategories != null) {
            for (APICategory category : attachedApiCategories) {
                artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
            }
        }
        registry.commitTransaction();
        transactionCommitted = true;
        apiUUID = updateApiArtifact.getId();
        if (updatePermissions) {
            APIManagerConfiguration config = getAPIManagerConfiguration();
            boolean isSetDocLevelPermissions = Boolean.parseBoolean(config.getFirstProperty(APIConstants.API_PUBLISHER_ENABLE_API_DOC_VISIBILITY_LEVELS));
            String docRootPath = APIUtil.getAPIDocPath(api.getId());
            if (isSetDocLevelPermissions) {
                // Retain the docs
                List<Documentation> docs = getAllDocumentation(api.getId());
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                        if (Documentation.DocumentSourceType.INLINE.equals(doc.getSourceType()) || Documentation.DocumentSourceType.MARKDOWN.equals(doc.getSourceType())) {
                            String contentPath = APIUtil.getAPIDocContentPath(api.getId(), doc.getName());
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, contentPath, registry);
                        } else if (Documentation.DocumentSourceType.FILE.equals(doc.getSourceType()) && doc.getFilePath() != null) {
                            String filePath = APIUtil.getDocumentationFilePath(api.getId(), doc.getFilePath().split("files" + RegistryConstants.PATH_SEPARATOR)[1]);
                            APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, filePath, registry);
                        }
                    }
                }
            } else {
                APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, docRootPath, registry);
            }
        } else {
            // In order to support content search feature - we need to update resource permissions of document resources
            // if their visibility is set to API level.
            List<Documentation> docs = getAllDocumentation(api.getId());
            if (docs != null) {
                for (Documentation doc : docs) {
                    if ((APIConstants.DOC_API_BASED_VISIBILITY).equalsIgnoreCase(doc.getVisibility().name())) {
                        String documentationPath = APIUtil.getAPIDocPath(api.getId()) + doc.getName();
                        APIUtil.setResourcePermissions(api.getId().getProviderName(), api.getVisibility(), visibleRoles, documentationPath, registry);
                    }
                }
            }
        }
    } catch (Exception e) {
        try {
            registry.rollbackTransaction();
        } catch (RegistryException re) {
            // Throwing an error from this level will mask the original exception
            log.error("Error while rolling back the transaction for API: " + api.getId().getApiName(), re);
        }
        handleException("Error while performing registry transaction operation", e);
    } finally {
        try {
            if (!transactionCommitted) {
                registry.rollbackTransaction();
            }
        } catch (RegistryException ex) {
            handleException("Error occurred while rolling back the transaction.", ex);
        }
    }
    return apiUUID;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) 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) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) XMLStreamException(javax.xml.stream.XMLStreamException) GraphQLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.GraphQLPersistenceException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) IOException(java.io.IOException) MediationPolicyPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.MediationPolicyPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) WSDLPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.WSDLPersistenceException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.PersistenceException) UnsupportedPolicyTypeException(org.wso2.carbon.apimgt.api.UnsupportedPolicyTypeException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) NotificationException(org.wso2.carbon.apimgt.impl.notification.exception.NotificationException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) MonetizationException(org.wso2.carbon.apimgt.api.MonetizationException) ThumbnailPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.ThumbnailPersistenceException) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) OMException(org.apache.axiom.om.OMException) JSONObject(org.json.simple.JSONObject) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 37 with GenericArtifactManager

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

the class APIConsumerImpl method searchPaginatedAPIs.

/**
 * Pagination API search based on solr indexing
 *
 * @param registry
 * @param searchTerm
 * @param searchType
 * @return
 * @throws APIManagementException
 */
public Map<String, Object> searchPaginatedAPIs(Registry registry, String searchTerm, String searchType, int start, int end, boolean limitAttributes) throws APIManagementException {
    SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator());
    List<API> apiList = new ArrayList<API>();
    searchTerm = searchTerm.trim();
    Map<String, Object> result = new HashMap<String, Object>();
    int totalLength = 0;
    boolean isMore = false;
    String criteria = APIConstants.API_OVERVIEW_NAME;
    try {
        String paginationLimit = 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;
        }
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        PaginationContext.init(start, end, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        if (artifactManager != null) {
            if (APIConstants.API_PROVIDER.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_PROVIDER;
                searchTerm = searchTerm.replaceAll("@", "-AT-");
            } else if (APIConstants.API_VERSION_LABEL.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_VERSION;
            } else if (APIConstants.API_CONTEXT.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_CONTEXT;
            } else if (APIConstants.API_DESCRIPTION.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_DESCRIPTION;
            } else if (APIConstants.API_TAG.equalsIgnoreCase(searchType)) {
                criteria = APIConstants.API_OVERVIEW_TAG;
            }
            // Create the search attribute map for PUBLISHED APIs
            final String searchValue = searchTerm;
            Map<String, List<String>> listMap = new HashMap<String, List<String>>();
            listMap.put(criteria, new ArrayList<String>() {

                {
                    add(searchValue);
                }
            });
            boolean displayAPIsWithMultipleStatus = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
            // multiple status. This is because pagination is breaking when we do a another filtering with the API Status
            if (!displayAPIsWithMultipleStatus) {
                listMap.put(APIConstants.API_OVERVIEW_STATUS, new ArrayList<String>() {

                    {
                        add(APIConstants.PUBLISHED);
                    }
                });
            }
            GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
            totalLength = PaginationContext.getInstance().getLength();
            boolean isFound = true;
            if (genericArtifacts == null || genericArtifacts.length == 0) {
                if (APIConstants.API_OVERVIEW_PROVIDER.equals(criteria)) {
                    genericArtifacts = searchAPIsByOwner(artifactManager, searchValue);
                    if (genericArtifacts == null || genericArtifacts.length == 0) {
                        isFound = false;
                    }
                } else {
                    isFound = false;
                }
            }
            if (!isFound) {
                result.put("apis", apiSet);
                result.put("length", 0);
                result.put("isMore", isMore);
                return result;
            }
            // Check to see if we can speculate that there are more APIs to be loaded
            if (maxPaginationLimit == totalLength) {
                // 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;
            }
            int tempLength = 0;
            for (GenericArtifact artifact : genericArtifacts) {
                String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS);
                if (APIUtil.isAllowDisplayAPIsWithMultipleStatus()) {
                    if (APIConstants.PROTOTYPED.equals(status) || APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) {
                        API resultAPI;
                        if (limitAttributes) {
                            resultAPI = APIUtil.getAPI(artifact);
                        } else {
                            resultAPI = APIUtil.getAPI(artifact, registry);
                        }
                        if (resultAPI != null) {
                            apiList.add(resultAPI);
                        }
                    }
                } else {
                    if (APIConstants.PROTOTYPED.equals(status) || APIConstants.PUBLISHED.equals(status)) {
                        API resultAPI;
                        if (limitAttributes) {
                            resultAPI = APIUtil.getAPI(artifact);
                        } else {
                            resultAPI = APIUtil.getAPI(artifact, registry);
                        }
                        if (resultAPI != null) {
                            apiList.add(resultAPI);
                        }
                    }
                }
                // Ensure the APIs returned matches the length, there could be an additional API
                // returned due incrementing the pagination limit when getting from registry
                tempLength++;
                if (tempLength >= totalLength) {
                    break;
                }
            }
            apiSet.addAll(apiList);
        }
    } catch (RegistryException e) {
        handleException("Failed to search APIs with type", e);
    }
    result.put("apis", apiSet);
    result.put("length", totalLength);
    result.put("isMore", isMore);
    return result;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) TreeSet(java.util.TreeSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) JSONObject(org.json.simple.JSONObject) CommentList(org.wso2.carbon.apimgt.api.model.CommentList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 38 with GenericArtifactManager

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

the class APIConsumerImpl method getAllPaginatedAPIsByStatus.

/**
 * The method to get APIs in any of the given LC status array
 *
 * @return Map<String, Object>  API result set with pagination information
 * @throws APIManagementException
 */
@Override
public Map<String, Object> getAllPaginatedAPIsByStatus(String tenantDomain, int start, int end, final String[] apiStatus, boolean returnAPITags) throws APIManagementException {
    Map<String, Object> result = new HashMap<String, Object>();
    SortedSet<API> apiSortedSet = new TreeSet<API>(new APINameComparator());
    SortedSet<API> apiVersionsSortedSet = new TreeSet<API>(new APIVersionComparator());
    int totalLength = 0;
    boolean isMore = false;
    String criteria = APIConstants.LCSTATE_SEARCH_TYPE_KEY;
    try {
        Registry userRegistry;
        boolean isTenantMode = (tenantDomain != null);
        if ((isTenantMode && this.tenantDomain == null) || (isTenantMode && isTenantDomainNotMatching(tenantDomain))) {
            // Tenant store anonymous mode
            int tenantId = getTenantId(tenantDomain);
            // explicitly load the tenant's registry
            APIUtil.loadTenantRegistry(tenantId);
            userRegistry = getGovernanceUserRegistry(tenantId);
            setUsernameToThreadLocalCarbonContext(CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME);
        } else {
            userRegistry = registry;
            setUsernameToThreadLocalCarbonContext(this.username);
        }
        this.isTenantModeStoreView = isTenantMode;
        this.requestedTenant = tenantDomain;
        Map<String, API> latestPublishedAPIs = new HashMap<String, API>();
        List<API> multiVersionedAPIs = new ArrayList<API>();
        Comparator<API> versionComparator = new APIVersionComparator();
        Boolean displayMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
        String paginationLimit = 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);
        criteria = criteria + APIUtil.getORBasedSearchCriteria(apiStatus);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(userRegistry, APIConstants.API_KEY);
        if (artifactManager != null) {
            if (apiStatus != null && apiStatus.length > 0) {
                List<GovernanceArtifact> genericArtifacts = GovernanceUtils.findGovernanceArtifacts(getSearchQuery(criteria), userRegistry, APIConstants.API_RXT_MEDIA_TYPE);
                totalLength = PaginationContext.getInstance().getLength();
                if (genericArtifacts == null || genericArtifacts.size() == 0) {
                    result.put("apis", apiSortedSet);
                    result.put("totalLength", totalLength);
                    result.put("isMore", isMore);
                    return result;
                }
                // Check to see if we can speculate that there are more APIs to be loaded
                if (maxPaginationLimit == totalLength) {
                    // More APIs exist so we cannot determine the total API count without incurring a
                    isMore = true;
                    // performance hit
                    // Remove the additional 1 we added earlier when setting max pagination limit
                    --totalLength;
                }
                int tempLength = 0;
                for (GovernanceArtifact artifact : genericArtifacts) {
                    API api = null;
                    try {
                        api = APIUtil.getAPI(artifact);
                    } catch (APIManagementException e) {
                        // log and continue since we want to load the rest of the APIs.
                        log.error("Error while loading API " + artifact.getAttribute(APIConstants.API_OVERVIEW_NAME), e);
                    }
                    if (api != null) {
                        if (returnAPITags) {
                            String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
                            Set<String> tags = new HashSet<String>();
                            org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath);
                            for (org.wso2.carbon.registry.core.Tag tag1 : tag) {
                                tags.add(tag1.getTagName());
                            }
                            api.addTags(tags);
                        }
                        String key;
                        // Check the configuration to allow showing multiple versions of an API true/false
                        if (!displayMultipleVersions) {
                            // If allow only showing the latest version of an API
                            key = api.getId().getProviderName() + COLON_CHAR + api.getId().getApiName();
                            API existingAPI = latestPublishedAPIs.get(key);
                            if (existingAPI != null) {
                                // this one has a higher version number
                                if (versionComparator.compare(api, existingAPI) > 0) {
                                    latestPublishedAPIs.put(key, api);
                                }
                            } else {
                                // We haven't seen this API before
                                latestPublishedAPIs.put(key, api);
                            }
                        } else {
                            // If allow showing multiple versions of an API
                            multiVersionedAPIs.add(api);
                        }
                    }
                    tempLength++;
                    if (tempLength >= totalLength) {
                        break;
                    }
                }
                if (!displayMultipleVersions) {
                    apiSortedSet.addAll(latestPublishedAPIs.values());
                    result.put("apis", apiSortedSet);
                    result.put("totalLength", totalLength);
                    result.put("isMore", isMore);
                    return result;
                } else {
                    apiVersionsSortedSet.addAll(multiVersionedAPIs);
                    result.put("apis", apiVersionsSortedSet);
                    result.put("totalLength", totalLength);
                    result.put("isMore", isMore);
                    return result;
                }
            }
        } else {
            String errorMessage = "Artifact manager is null for tenant domain " + tenantDomain + " when retrieving all paginated APIs by status.";
            log.error(errorMessage);
        }
    } catch (RegistryException e) {
        handleException("Failed to get all published APIs", e);
    } catch (UserStoreException e) {
        handleException("Failed to get all published APIs", e);
    } finally {
        PaginationContext.destroy();
    }
    result.put("apis", apiSortedSet);
    result.put("totalLength", totalLength);
    result.put("isMore", isMore);
    return result;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) APINameComparator(org.wso2.carbon.apimgt.impl.utils.APINameComparator) APIVersionComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionComparator) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TreeSet(java.util.TreeSet) UserStoreException(org.wso2.carbon.user.api.UserStoreException) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) GovernanceArtifact(org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) API(org.wso2.carbon.apimgt.api.model.API) Tag(org.wso2.carbon.apimgt.api.model.Tag)

Example 39 with GenericArtifactManager

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

the class APIProviderImpl method addDocumentationContent.

/**
 * This method used to save the documentation content
 *
 * @param api,               API
 * @param documentationName, name of the inline documentation
 * @param text,              content of the inline documentation
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to add the document as a resource to registry
 */
public void addDocumentationContent(API api, String documentationName, String text) throws APIManagementException {
    APIIdentifier identifier = api.getId();
    String documentationPath = APIUtil.getAPIDocPath(identifier) + documentationName;
    String contentPath = APIUtil.getAPIDocPath(identifier) + APIConstants.INLINE_DOCUMENT_CONTENT_DIR + RegistryConstants.PATH_SEPARATOR + documentationName;
    boolean isTenantFlowStarted = false;
    try {
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            PrivilegedCarbonContext.startTenantFlow();
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        Resource docResource = registry.get(documentationPath);
        GenericArtifactManager artifactManager = new GenericArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        GenericArtifact docArtifact = artifactManager.getGenericArtifact(docResource.getUUID());
        Documentation doc = APIUtil.getDocumentation(docArtifact);
        Resource docContent;
        if (!registry.resourceExists(contentPath)) {
            docContent = registry.newResource();
        } else {
            docContent = registry.get(contentPath);
        }
        /* This is a temporary fix for doc content replace issue. We need to add
             * separate methods to add inline content resource in document update */
        if (!APIConstants.NO_CONTENT_UPDATE.equals(text)) {
            docContent.setContent(text);
        }
        docContent.setMediaType(APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE);
        registry.put(contentPath, docContent);
        String apiPath = APIUtil.getAPIPath(identifier);
        String[] authorizedRoles = getAuthorizedRoles(apiPath);
        String docVisibility = doc.getVisibility().name();
        String visibility = api.getVisibility();
        if (docVisibility != null) {
            if (APIConstants.DOC_SHARED_VISIBILITY.equalsIgnoreCase(docVisibility)) {
                authorizedRoles = null;
                visibility = APIConstants.DOC_SHARED_VISIBILITY;
            } else if (APIConstants.DOC_OWNER_VISIBILITY.equalsIgnoreCase(docVisibility)) {
                authorizedRoles = null;
                visibility = APIConstants.DOC_OWNER_VISIBILITY;
            }
        }
        APIUtil.setResourcePermissions(api.getId().getProviderName(), visibility, authorizedRoles, contentPath, registry);
    } catch (RegistryException e) {
        String msg = "Failed to add the documentation content of : " + documentationName + " of API :" + identifier.getApiName();
        handleException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to add the documentation content of : " + documentationName + " of API :" + identifier.getApiName();
        handleException(msg, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) 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) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserStoreException(org.wso2.carbon.user.api.UserStoreException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 40 with GenericArtifactManager

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

the class APIProviderImpl method getAllProviders.

/**
 * Returns a list of all #{@link org.wso2.carbon.apimgt.api.model.Provider} available on the system.
 *
 * @return Set<Provider>
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get Providers
 */
@Override
public Set<Provider> getAllProviders() throws APIManagementException {
    Set<Provider> providerSet = new HashSet<Provider>();
    GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.PROVIDER_KEY);
    try {
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when fetching providers.";
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        GenericArtifact[] genericArtifact = artifactManager.getAllGenericArtifacts();
        if (genericArtifact == null || genericArtifact.length == 0) {
            return providerSet;
        }
        for (GenericArtifact artifact : genericArtifact) {
            Provider provider = new Provider(artifact.getAttribute(APIConstants.PROVIDER_OVERVIEW_NAME));
            provider.setDescription(APIConstants.PROVIDER_OVERVIEW_DESCRIPTION);
            provider.setEmail(APIConstants.PROVIDER_OVERVIEW_EMAIL);
            providerSet.add(provider);
        }
    } catch (GovernanceException e) {
        handleException("Failed to get all providers", e);
    }
    return providerSet;
}
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) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) Provider(org.wso2.carbon.apimgt.api.model.Provider) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

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