Search in sources :

Example 21 with APIResource

use of org.wso2.carbon.apimgt.api.doc.model.APIResource in project carbon-apimgt by wso2.

the class APIPublisherImpl method getAPIbyUUID.

@Override
public API getAPIbyUUID(String uuid) throws APIManagementException {
    API api = null;
    try {
        api = super.getAPIbyUUID(uuid);
        if (api != null) {
            api.setUserSpecificApiPermissions(getAPIPermissionsOfLoggedInUser(getUsername(), api));
            String permissionString = api.getApiPermission();
            if (!StringUtils.isEmpty(permissionString)) {
                api.setApiPermission(replaceGroupIdWithName(permissionString));
            }
            if (!getScopesForApi(uuid).isEmpty()) {
                String swagger = getApiSwaggerDefinition(uuid);
                List<String> globalScopes = new APIDefinitionFromSwagger20().getGlobalAssignedScopes(swagger);
                List<APIResource> apiResourceList = new APIDefinitionFromSwagger20().parseSwaggerAPIResources(new StringBuilder(swagger));
                api.setScopes(globalScopes);
                for (APIResource apiResource : apiResourceList) {
                    if (apiResource.getUriTemplate().getScopes().isEmpty()) {
                        UriTemplate retrievedUriTemplateFromApi = api.getUriTemplates().get(apiResource.getUriTemplate().getTemplateId());
                        if (retrievedUriTemplateFromApi != null) {
                            UriTemplate.UriTemplateBuilder uriTemplate = new UriTemplate.UriTemplateBuilder(retrievedUriTemplateFromApi);
                            uriTemplate.scopes(apiResource.getScope());
                            api.getUriTemplates().replace(apiResource.getUriTemplate().getTemplateId(), uriTemplate.build());
                        }
                    }
                }
            }
        }
    } catch (ParseException e) {
        String errorMsg = "Error occurred while parsing the permission json string for API " + api.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.JSON_PARSE_ERROR);
    }
    return api;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIResource(org.wso2.carbon.apimgt.core.models.APIResource) API(org.wso2.carbon.apimgt.core.models.API) ParseException(org.json.simple.parser.ParseException) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate)

Example 22 with APIResource

use of org.wso2.carbon.apimgt.api.doc.model.APIResource in project carbon-apimgt by wso2.

the class PublisherCommonUtils method updateSwagger.

/**
 * update swagger definition of the given api.
 *
 * @param apiId    API Id
 * @param response response of a swagger definition validation call
 * @param organization  Organization Identifier
 * @return updated swagger definition
 * @throws APIManagementException when error occurred updating swagger
 * @throws FaultGatewaysException when error occurred publishing API to the gateway
 */
public static String updateSwagger(String apiId, APIDefinitionValidationResponse response, boolean isServiceAPI, String organization) throws APIManagementException, FaultGatewaysException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    // this will fail if user does not have access to the API or the API does not exist
    API existingAPI = apiProvider.getAPIbyUUID(apiId, organization);
    APIDefinition oasParser = response.getParser();
    String apiDefinition = response.getJsonContent();
    if (isServiceAPI) {
        apiDefinition = oasParser.copyVendorExtensions(existingAPI.getSwaggerDefinition(), apiDefinition);
    } else {
        apiDefinition = OASParserUtil.preProcess(apiDefinition);
    }
    if (APIConstants.API_TYPE_SOAPTOREST.equals(existingAPI.getType())) {
        List<SOAPToRestSequence> sequenceList = SequenceGenerator.generateSequencesFromSwagger(apiDefinition);
        existingAPI.setSoapToRestSequences(sequenceList);
    }
    Set<URITemplate> uriTemplates = null;
    uriTemplates = oasParser.getURITemplates(apiDefinition);
    if (uriTemplates == null || uriTemplates.isEmpty()) {
        throw new APIManagementException(ExceptionCodes.NO_RESOURCES_FOUND);
    }
    Set<org.wso2.carbon.apimgt.api.model.Scope> scopes = oasParser.getScopes(apiDefinition);
    // validating scope roles
    for (org.wso2.carbon.apimgt.api.model.Scope scope : scopes) {
        String roles = scope.getRoles();
        if (roles != null) {
            for (String aRole : roles.split(",")) {
                boolean isValidRole = APIUtil.isRoleNameExist(RestApiCommonUtil.getLoggedInUsername(), aRole);
                if (!isValidRole) {
                    throw new APIManagementException("Role '" + aRole + "' Does not exist.");
                }
            }
        }
    }
    List<APIResource> removedProductResources = apiProvider.getRemovedProductResources(uriTemplates, existingAPI);
    if (!removedProductResources.isEmpty()) {
        throw new APIManagementException("Cannot remove following resource paths " + removedProductResources.toString() + " because they are used by one or more API Products", ExceptionCodes.from(ExceptionCodes.API_PRODUCT_USED_RESOURCES, existingAPI.getId().getApiName(), existingAPI.getId().getVersion()));
    }
    // set existing operation policies to URI templates
    apiProvider.setOperationPoliciesToURITemplates(apiId, uriTemplates);
    existingAPI.setUriTemplates(uriTemplates);
    existingAPI.setScopes(scopes);
    PublisherCommonUtils.validateScopes(existingAPI);
    // Update API is called to update URITemplates and scopes of the API
    SwaggerData swaggerData = new SwaggerData(existingAPI);
    String updatedApiDefinition = oasParser.populateCustomManagementInfo(apiDefinition, swaggerData);
    apiProvider.saveSwaggerDefinition(existingAPI, updatedApiDefinition, organization);
    existingAPI.setSwaggerDefinition(updatedApiDefinition);
    API unModifiedAPI = apiProvider.getAPIbyUUID(apiId, organization);
    existingAPI.setStatus(unModifiedAPI.getStatus());
    apiProvider.updateAPI(existingAPI, unModifiedAPI);
    // retrieves the updated swagger definition
    // TODO see why we need to get it
    String apiSwagger = apiProvider.getOpenAPIDefinition(apiId, organization);
    // instead of passing same
    return oasParser.getOASDefinitionForPublisher(existingAPI, apiSwagger);
}
Also used : APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) SwaggerData(org.wso2.carbon.apimgt.api.model.SwaggerData) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) SOAPToRestSequence(org.wso2.carbon.apimgt.api.model.SOAPToRestSequence) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Scope(org.wso2.carbon.apimgt.rest.api.common.annotations.Scope) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API)

Example 23 with APIResource

use of org.wso2.carbon.apimgt.api.doc.model.APIResource in project carbon-apimgt by wso2.

the class DocumentIndexer method fetchRequiredDetailsFromAssociatedAPI.

/**
 * Fetch api status and access control details to document artifacts
 *
 * @param registry
 * @param documentResource
 * @param fields
 * @throws RegistryException
 * @throws APIManagementException
 */
private void fetchRequiredDetailsFromAssociatedAPI(Registry registry, Resource documentResource, Map<String, List<String>> fields) throws RegistryException, APIManagementException {
    String pathToDocFile = documentResource.getPath();
    String apiPath = pathToDocFile.substring(0, pathToDocFile.indexOf(APIConstants.DOC_DIR)) + APIConstants.API_KEY;
    if (registry.resourceExists(apiPath)) {
        Resource apiResource = registry.get(apiPath);
        GenericArtifactManager apiArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiResource.getUUID());
        String apiStatus = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_STATUS).toLowerCase();
        String publisherRoles = apiResource.getProperty(APIConstants.PUBLISHER_ROLES);
        fields.put(APIConstants.API_OVERVIEW_STATUS, Arrays.asList(apiStatus));
        fields.put(APIConstants.PUBLISHER_ROLES, Arrays.asList(publisherRoles));
    } else {
        log.warn("API does not exist at " + apiPath);
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource)

Example 24 with APIResource

use of org.wso2.carbon.apimgt.api.doc.model.APIResource in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method searchContentForPublisher.

@Override
public PublisherContentSearchResult searchContentForPublisher(Organization org, String searchQuery, int start, int offset, UserContext ctx) throws APIPersistenceException {
    log.debug("Requested query for publisher content search: " + searchQuery);
    Map<String, String> attributes = RegistrySearchUtil.getPublisherSearchAttributes(searchQuery, ctx);
    if (log.isDebugEnabled()) {
        log.debug("Search attributes : " + attributes);
    }
    boolean isTenantFlowStarted = false;
    PublisherContentSearchResult result = null;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        String requestedTenantDomain = org.getName();
        String tenantAwareUsername = getTenantAwareUsername(RegistryPersistenceUtil.getTenantAdminUserName(requestedTenantDomain));
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(tenantAwareUsername);
        GenericArtifactManager apiArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifactManager docArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        int maxPaginationLimit = getMaxPaginationLimit();
        PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        int tenantId = holder.getTenantId();
        if (tenantId == -1) {
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        }
        UserRegistry systemUserRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME, tenantId);
        ContentBasedSearchService contentBasedSearchService = new ContentBasedSearchService();
        SearchResultsBean resultsBean = contentBasedSearchService.searchByAttribute(attributes, systemUserRegistry);
        String errorMsg = resultsBean.getErrorMessage();
        if (errorMsg != null) {
            throw new APIPersistenceException("Error while searching " + errorMsg);
        }
        ResourceData[] resourceData = resultsBean.getResourceDataList();
        int totalLength = PaginationContext.getInstance().getLength();
        if (resourceData != null) {
            result = new PublisherContentSearchResult();
            List<SearchContent> contentData = new ArrayList<SearchContent>();
            if (log.isDebugEnabled()) {
                log.debug("Number of records Found: " + resourceData.length);
            }
            for (ResourceData data : resourceData) {
                String resourcePath = data.getResourcePath();
                if (resourcePath.contains(APIConstants.APIMGT_REGISTRY_LOCATION)) {
                    int index = resourcePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
                    resourcePath = resourcePath.substring(index);
                    Resource resource = registry.get(resourcePath);
                    if (APIConstants.DOCUMENT_RXT_MEDIA_TYPE.equals(resource.getMediaType()) || APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE.equals(resource.getMediaType())) {
                        if (resourcePath.contains(APIConstants.INLINE_DOCUMENT_CONTENT_DIR)) {
                            int indexOfContents = resourcePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
                            resourcePath = resourcePath.substring(0, indexOfContents) + data.getName();
                        }
                        DocumentSearchContent docSearch = new DocumentSearchContent();
                        Resource docResource = registry.get(resourcePath);
                        String docArtifactId = docResource.getUUID();
                        GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
                        Documentation doc = RegistryPersistenceDocUtil.getDocumentation(docArtifact);
                        // API associatedAPI = null;
                        // APIProduct associatedAPIProduct = null;
                        int indexOfDocumentation = resourcePath.indexOf(APIConstants.DOCUMENTATION_KEY);
                        String apiPath = resourcePath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
                        Resource apiResource = registry.get(apiPath);
                        String apiArtifactId = apiResource.getUUID();
                        PublisherAPI pubAPI;
                        if (apiArtifactId != null) {
                            GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                            String accociatedType;
                            if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.AuditLogConstants.API_PRODUCT)) {
                                // associatedAPIProduct = APIUtil.getAPIProduct(apiArtifact, registry);
                                accociatedType = APIConstants.API_PRODUCT;
                            } else {
                                // associatedAPI = APIUtil.getAPI(apiArtifact, registry);
                                accociatedType = APIConstants.API;
                            }
                            pubAPI = RegistryPersistenceUtil.getAPIForSearch(apiArtifact);
                            docSearch.setApiName(pubAPI.getApiName());
                            docSearch.setApiProvider(pubAPI.getProviderName());
                            docSearch.setApiVersion(pubAPI.getVersion());
                            docSearch.setApiUUID(pubAPI.getId());
                            docSearch.setAssociatedType(accociatedType);
                            docSearch.setDocType(doc.getType());
                            docSearch.setId(doc.getId());
                            docSearch.setSourceType(doc.getSourceType());
                            docSearch.setVisibility(doc.getVisibility());
                            docSearch.setName(doc.getName());
                            contentData.add(docSearch);
                        } else {
                            throw new GovernanceException("artifact id is null of " + apiPath);
                        }
                    } else {
                        String apiArtifactId = resource.getUUID();
                        // API api;
                        // APIProduct apiProduct;
                        String type;
                        if (apiArtifactId != null) {
                            GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                            if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.API_PRODUCT)) {
                                // apiProduct = APIUtil.getAPIProduct(apiArtifact, registry);
                                // apiProductSet.add(apiProduct);
                                type = APIConstants.API_PRODUCT;
                            } else {
                                // api = APIUtil.getAPI(apiArtifact, registry);
                                // apiSet.add(api);
                                type = APIConstants.API;
                            }
                            PublisherAPI pubAPI = RegistryPersistenceUtil.getAPIForSearch(apiArtifact);
                            PublisherSearchContent content = new PublisherSearchContent();
                            content.setContext(pubAPI.getContext());
                            content.setDescription(pubAPI.getDescription());
                            content.setId(pubAPI.getId());
                            content.setName(pubAPI.getApiName());
                            content.setProvider(RegistryPersistenceUtil.replaceEmailDomainBack(pubAPI.getProviderName()));
                            content.setType(type);
                            content.setVersion(pubAPI.getVersion());
                            content.setStatus(pubAPI.getStatus());
                            content.setAdvertiseOnly(pubAPI.isAdvertiseOnly());
                            contentData.add(content);
                        } else {
                            throw new GovernanceException("artifact id is null for " + resourcePath);
                        }
                    }
                }
            }
            result.setTotalCount(totalLength);
            result.setReturnedCount(contentData.size());
            result.setResults(contentData);
        }
    } catch (RegistryException | IndexerException | DocumentationPersistenceException | APIManagementException e) {
        throw new APIPersistenceException("Error while searching for content ", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return result;
}
Also used : DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) ArrayList(java.util.ArrayList) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) SearchResultsBean(org.wso2.carbon.registry.indexing.service.SearchResultsBean) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) PublisherSearchContent(org.wso2.carbon.apimgt.persistence.dto.PublisherSearchContent) SearchContent(org.wso2.carbon.apimgt.persistence.dto.SearchContent) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) ResourceData(org.wso2.carbon.registry.common.ResourceData) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) PublisherSearchContent(org.wso2.carbon.apimgt.persistence.dto.PublisherSearchContent) Documentation(org.wso2.carbon.apimgt.persistence.dto.Documentation) Resource(org.wso2.carbon.registry.core.Resource) 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) ContentBasedSearchService(org.wso2.carbon.registry.indexing.service.ContentBasedSearchService) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PublisherContentSearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherContentSearchResult)

Example 25 with APIResource

use of org.wso2.carbon.apimgt.api.doc.model.APIResource in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method updateRegistryResources.

/**
 * To add API/Product roles restrictions and add additional properties.
 *
 * @param artifactPath                Path of the API/Product artifact.
 * @param publisherAccessControlRoles Role specified for the publisher access control.
 * @param publisherAccessControl      Publisher Access Control restriction.
 * @param additionalProperties        Additional properties that is related with an API/Product.
 * @throws RegistryException Registry Exception.
 */
private void updateRegistryResources(Registry registry, String artifactPath, String publisherAccessControlRoles, String publisherAccessControl, Map<String, String> additionalProperties) throws RegistryException {
    publisherAccessControlRoles = (publisherAccessControlRoles == null || publisherAccessControlRoles.trim().isEmpty()) ? APIConstants.NULL_USER_ROLE_LIST : publisherAccessControlRoles;
    if (publisherAccessControlRoles.equalsIgnoreCase(APIConstants.NULL_USER_ROLE_LIST)) {
        publisherAccessControl = APIConstants.NO_ACCESS_CONTROL;
    }
    if (!registry.resourceExists(artifactPath)) {
        return;
    }
    Resource apiResource = registry.get(artifactPath);
    if (apiResource != null) {
        if (additionalProperties != null) {
            // Removing all the properties, before updating new properties.
            Properties properties = apiResource.getProperties();
            if (properties != null) {
                Enumeration propertyNames = properties.propertyNames();
                while (propertyNames.hasMoreElements()) {
                    String propertyName = (String) propertyNames.nextElement();
                    if (propertyName.startsWith(APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX)) {
                        apiResource.removeProperty(propertyName);
                    }
                }
            }
        }
        // We are changing to lowercase, as registry search only supports lower-case characters.
        apiResource.setProperty(APIConstants.PUBLISHER_ROLES, publisherAccessControlRoles.toLowerCase());
        // This property will be only used for display proposes in the Publisher UI so that the original case of
        // the roles that were specified can be maintained.
        apiResource.setProperty(APIConstants.DISPLAY_PUBLISHER_ROLES, publisherAccessControlRoles);
        apiResource.setProperty(APIConstants.ACCESS_CONTROL, publisherAccessControl);
        apiResource.removeProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY);
        if (additionalProperties != null && additionalProperties.size() != 0) {
            for (Map.Entry<String, String> entry : additionalProperties.entrySet()) {
                apiResource.setProperty((APIConstants.API_RELATED_CUSTOM_PROPERTIES_PREFIX + entry.getKey()), entry.getValue());
            }
        }
        registry.put(artifactPath, apiResource);
    }
}
Also used : Enumeration(java.util.Enumeration) Resource(org.wso2.carbon.registry.core.Resource) Properties(java.util.Properties) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

Resource (org.wso2.carbon.registry.core.Resource)14 APIResource (org.wso2.carbon.apimgt.api.doc.model.APIResource)13 ArrayList (java.util.ArrayList)12 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)11 HashMap (java.util.HashMap)10 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)8 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)8 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)7 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)7 Map (java.util.Map)6 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 API (org.wso2.carbon.apimgt.api.model.API)5 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)5 List (java.util.List)4 JSONObject (org.json.simple.JSONObject)4 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)4 APIResource (org.wso2.carbon.apimgt.core.models.APIResource)4 UriTemplate (org.wso2.carbon.apimgt.core.models.UriTemplate)4 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)4