Search in sources :

Example 11 with APICategory

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

the class ApiMgtDAO method getAPICategoryByID.

public APICategory getAPICategoryByID(String apiCategoryID) throws APIManagementException {
    APICategory apiCategory = null;
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQLConstants.GET_API_CATEGORY_BY_ID)) {
        statement.setString(1, apiCategoryID);
        ResultSet rs = statement.executeQuery();
        if (rs.next()) {
            apiCategory = new APICategory();
            apiCategory.setName(rs.getString("NAME"));
            apiCategory.setDescription(rs.getString("DESCRIPTION"));
            apiCategory.setId(apiCategoryID);
        }
    } catch (SQLException e) {
        handleException("Failed to fetch API category : " + apiCategoryID, e);
    }
    return apiCategory;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 12 with APICategory

use of org.wso2.carbon.apimgt.api.model.APICategory 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 13 with APICategory

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

the class APIUtil method getAPICategoriesFromAPIGovernanceArtifact.

/**
 * This method returns the categories attached to the API
 *
 * @param artifact API artifact
 * @param tenantID tenant ID of API Provider
 * @return List<APICategory> list of categories
 */
private static List<APICategory> getAPICategoriesFromAPIGovernanceArtifact(GovernanceArtifact artifact, int tenantID) throws GovernanceException, APIManagementException {
    String[] categoriesOfAPI = artifact.getAttributes(APIConstants.API_CATEGORIES_CATEGORY_NAME);
    List<APICategory> categoryList = new ArrayList<>();
    if (ArrayUtils.isNotEmpty(categoriesOfAPI)) {
        // category array retrieved from artifact has only the category name, therefore we need to fetch categories
        // and fill out missing attributes before attaching the list to the api
        String tenantDomain = getTenantDomainFromTenantId(tenantID);
        List<APICategory> allCategories = getAllAPICategoriesOfOrganization(tenantDomain);
        // todo-category: optimize this loop with breaks
        for (String categoryName : categoriesOfAPI) {
            for (APICategory category : allCategories) {
                if (categoryName.equals(category.getName())) {
                    categoryList.add(category);
                    break;
                }
            }
        }
    }
    return categoryList;
}
Also used : ArrayList(java.util.ArrayList) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 14 with APICategory

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

the class APIUtil method createAPIArtifactContent.

/**
 * Create Governance artifact from given attributes
 *
 * @param artifact initial governance artifact
 * @param api      API object with the attributes value
 * @return GenericArtifact
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to create API
 */
public static GenericArtifact createAPIArtifactContent(GenericArtifact artifact, API api) throws APIManagementException {
    try {
        String apiStatus = api.getStatus();
        artifact.setAttribute(APIConstants.API_OVERVIEW_NAME, api.getId().getApiName());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, api.getId().getVersion());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP, api.getVersionTimestamp());
        artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT, api.getContext());
        artifact.setAttribute(APIConstants.API_OVERVIEW_PROVIDER, api.getId().getProviderName());
        artifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, api.getDescription());
        artifact.setAttribute(APIConstants.API_OVERVIEW_WSDL, api.getWsdlUrl());
        artifact.setAttribute(APIConstants.API_OVERVIEW_WADL, api.getWadlUrl());
        artifact.setAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL, api.getThumbnailUrl());
        artifact.setAttribute(APIConstants.API_OVERVIEW_STATUS, apiStatus);
        artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER, api.getTechnicalOwner());
        artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL, api.getTechnicalOwnerEmail());
        artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER, api.getBusinessOwner());
        artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL, api.getBusinessOwnerEmail());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBILITY, api.getVisibility());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES, api.getVisibleRoles());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS, api.getVisibleTenants());
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED, Boolean.toString(api.isEndpointSecured()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST, Boolean.toString(api.isEndpointAuthDigest()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME, api.getEndpointUTUsername());
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD, api.getEndpointUTPassword());
        artifact.setAttribute(APIConstants.API_OVERVIEW_TRANSPORTS, api.getTransports());
        artifact.setAttribute(APIConstants.API_OVERVIEW_INSEQUENCE, api.getInSequence());
        artifact.setAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE, api.getOutSequence());
        artifact.setAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE, api.getFaultSequence());
        artifact.setAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING, api.getResponseCache());
        artifact.setAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT, Integer.toString(api.getCacheTimeout()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL, api.getRedirectURL());
        artifact.setAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT, api.getApiExternalProductionEndpoint());
        artifact.setAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT, api.getApiExternalSandboxEndpoint());
        artifact.setAttribute(APIConstants.API_OVERVIEW_OWNER, api.getApiOwner());
        artifact.setAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY, Boolean.toString(api.isAdvertiseOnly()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG, api.getEndpointConfig());
        artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY, api.getSubscriptionAvailability());
        artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS, api.getSubscriptionAvailableTenants());
        artifact.setAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION, api.getImplementation());
        artifact.setAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS, api.getProductionMaxTps());
        artifact.setAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS, api.getSandboxMaxTps());
        artifact.setAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER, api.getAuthorizationHeader());
        artifact.setAttribute(APIConstants.API_OVERVIEW_API_SECURITY, api.getApiSecurity());
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA, Boolean.toString(api.isEnabledSchemaValidation()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE, Boolean.toString(api.isEnableStore()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_TESTKEY, api.getTestKey());
        // Validate if the API has an unsupported context before setting it in the artifact
        String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) {
            String invalidContext = File.separator + APIConstants.VERSION_PLACEHOLDER;
            if (invalidContext.equals(api.getContextTemplate())) {
                throw new APIManagementException("API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
            }
        } else {
            String invalidContext = APIConstants.TENANT_PREFIX + tenantDomain + File.separator + APIConstants.VERSION_PLACEHOLDER;
            if (invalidContext.equals(api.getContextTemplate())) {
                throw new APIManagementException("API : " + api.getId() + " has an unsupported context : " + api.getContextTemplate());
            }
        }
        // This is to support the pluggable version strategy.
        artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE, api.getContextTemplate());
        artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TYPE, "context");
        artifact.setAttribute(APIConstants.API_OVERVIEW_TYPE, api.getType());
        StringBuilder policyBuilder = new StringBuilder();
        for (Tier tier : api.getAvailableTiers()) {
            policyBuilder.append(tier.getName());
            policyBuilder.append("||");
        }
        String policies = policyBuilder.toString();
        if (!"".equals(policies)) {
            policies = policies.substring(0, policies.length() - 2);
            artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
        }
        StringBuilder tiersBuilder = new StringBuilder();
        for (Tier tier : api.getAvailableTiers()) {
            tiersBuilder.append(tier.getName());
            tiersBuilder.append("||");
        }
        String tiers = tiersBuilder.toString();
        if (!"".equals(tiers)) {
            tiers = tiers.substring(0, tiers.length() - 2);
            artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, tiers);
        } else {
            artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, tiers);
        }
        if (APIConstants.PUBLISHED.equals(apiStatus)) {
            artifact.setAttribute(APIConstants.API_OVERVIEW_IS_LATEST, "true");
        }
        String[] keys = artifact.getAttributeKeys();
        for (String key : keys) {
            if (key.contains("URITemplate")) {
                artifact.removeAttribute(key);
            }
        }
        Set<URITemplate> uriTemplateSet = api.getUriTemplates();
        int i = 0;
        for (URITemplate uriTemplate : uriTemplateSet) {
            artifact.addAttribute(APIConstants.API_URI_PATTERN + i, uriTemplate.getUriTemplate());
            artifact.addAttribute(APIConstants.API_URI_HTTP_METHOD + i, uriTemplate.getHTTPVerb());
            artifact.addAttribute(APIConstants.API_URI_AUTH_TYPE + i, uriTemplate.getAuthType());
            i++;
        }
        artifact.setAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS, writeEnvironmentsToArtifact(api));
        artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION, APIUtil.getCorsConfigurationJsonFromDto(api.getCorsConfiguration()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_WEBSUB_SUBSCRIPTION_CONFIGURATION, APIUtil.getWebsubSubscriptionConfigurationJsonFromDto(api.getWebsubSubscriptionConfiguration()));
        artifact.setAttribute(APIConstants.API_OVERVIEW_WS_URI_MAPPING, APIUtil.getWsUriMappingJsonFromDto(api.getWsUriMapping()));
        // 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());
            }
        }
        // set monetization status (i.e - enabled or disabled)
        artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS, Boolean.toString(api.getMonetizationStatus()));
        // set additional monetization data
        if (api.getMonetizationProperties() != null) {
            artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES, api.getMonetizationProperties().toJSONString());
        }
        if (api.getKeyManagers() != null) {
            artifact.setAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS, new Gson().toJson(api.getKeyManagers()));
        }
        // check in github code to see this method was removed
        String apiSecurity = artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY);
        if (apiSecurity != null && !apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2) && !apiSecurity.contains(APIConstants.API_SECURITY_API_KEY)) {
            artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, "");
        }
    } catch (GovernanceException e) {
        String msg = "Failed to create API for : " + api.getId().getApiName();
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    }
    return artifact;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 15 with APICategory

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

the class APIUtilTest method testValidateAPICategoriesWithValidCategories.

@Test
public void testValidateAPICategoriesWithValidCategories() throws Exception {
    List<APICategory> inputApiCategories = new ArrayList<>();
    List<APICategory> availableApiCategories = new ArrayList<>();
    APICategory apiCategory1 = Mockito.mock(APICategory.class);
    APICategory apiCategory2 = Mockito.mock(APICategory.class);
    ;
    APICategory apiCategory3 = Mockito.mock(APICategory.class);
    inputApiCategories.add(apiCategory1);
    inputApiCategories.add(apiCategory2);
    availableApiCategories.add(apiCategory1);
    availableApiCategories.add(apiCategory2);
    availableApiCategories.add(apiCategory3);
    PowerMockito.spy(APIUtil.class);
    PowerMockito.doReturn(availableApiCategories).when(APIUtil.class, "getAllAPICategoriesOfOrganization", tenantDomain);
    Assert.assertTrue("Failed to Validate API categories", APIUtil.validateAPICategories(inputApiCategories, tenantDomain));
}
Also used : ArrayList(java.util.ArrayList) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

APICategory (org.wso2.carbon.apimgt.api.model.APICategory)38 ArrayList (java.util.ArrayList)23 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)14 Tier (org.wso2.carbon.apimgt.api.model.Tier)13 URITemplate (org.wso2.carbon.apimgt.api.model.URITemplate)8 JSONObject (org.json.simple.JSONObject)7 Test (org.junit.Test)6 API (org.wso2.carbon.apimgt.api.model.API)6 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)6 HashMap (java.util.HashMap)5 HashSet (java.util.HashSet)5 JSONParser (org.json.simple.parser.JSONParser)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)4 Scope (org.wso2.carbon.apimgt.api.model.Scope)4 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)4 LinkedHashMap (java.util.LinkedHashMap)3 LinkedHashSet (java.util.LinkedHashSet)3 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)3 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)3