Search in sources :

Example 31 with GovernanceException

use of org.wso2.carbon.governance.api.exception.GovernanceException in project carbon-apimgt by wso2.

the class APIUtil method getProvider.

/**
 * This method used to get Provider from provider artifact
 *
 * @param artifact provider artifact
 * @return Provider
 * @throws APIManagementException if failed to get Provider from provider artifact.
 */
public static Provider getProvider(GenericArtifact artifact) throws APIManagementException {
    Provider provider;
    try {
        provider = new Provider(artifact.getAttribute(APIConstants.PROVIDER_OVERVIEW_NAME));
        provider.setDescription(artifact.getAttribute(APIConstants.PROVIDER_OVERVIEW_DESCRIPTION));
        provider.setEmail(artifact.getAttribute(APIConstants.PROVIDER_OVERVIEW_EMAIL));
    } catch (GovernanceException e) {
        String msg = "Failed to get provider ";
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    }
    return provider;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CacheProvider(org.wso2.carbon.apimgt.impl.caching.CacheProvider) Provider(org.wso2.carbon.apimgt.api.model.Provider)

Example 32 with GovernanceException

use of org.wso2.carbon.governance.api.exception.GovernanceException 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 33 with GovernanceException

use of org.wso2.carbon.governance.api.exception.GovernanceException in project carbon-apimgt by wso2.

the class APIUtil method getDocumentation.

/**
 * Create the Documentation from artifact
 *
 * @param artifact Documentation artifact
 * @return Documentation
 * @throws APIManagementException if failed to create Documentation from artifact
 */
public static Documentation getDocumentation(GenericArtifact artifact) throws APIManagementException {
    Documentation documentation;
    try {
        DocumentationType type;
        String docType = artifact.getAttribute(APIConstants.DOC_TYPE);
        if (docType.equalsIgnoreCase(DocumentationType.HOWTO.getType())) {
            type = DocumentationType.HOWTO;
        } else if (docType.equalsIgnoreCase(DocumentationType.PUBLIC_FORUM.getType())) {
            type = DocumentationType.PUBLIC_FORUM;
        } else if (docType.equalsIgnoreCase(DocumentationType.SUPPORT_FORUM.getType())) {
            type = DocumentationType.SUPPORT_FORUM;
        } else if (docType.equalsIgnoreCase(DocumentationType.API_MESSAGE_FORMAT.getType())) {
            type = DocumentationType.API_MESSAGE_FORMAT;
        } else if (docType.equalsIgnoreCase(DocumentationType.SAMPLES.getType())) {
            type = DocumentationType.SAMPLES;
        } else {
            type = DocumentationType.OTHER;
        }
        documentation = new Documentation(type, artifact.getAttribute(APIConstants.DOC_NAME));
        documentation.setId(artifact.getId());
        documentation.setSummary(artifact.getAttribute(APIConstants.DOC_SUMMARY));
        String visibilityAttr = artifact.getAttribute(APIConstants.DOC_VISIBILITY);
        Documentation.DocumentVisibility documentVisibility = Documentation.DocumentVisibility.API_LEVEL;
        if (visibilityAttr != null) {
            if (visibilityAttr.equals(Documentation.DocumentVisibility.API_LEVEL.name())) {
                documentVisibility = Documentation.DocumentVisibility.API_LEVEL;
            } else if (visibilityAttr.equals(Documentation.DocumentVisibility.PRIVATE.name())) {
                documentVisibility = Documentation.DocumentVisibility.PRIVATE;
            } else if (visibilityAttr.equals(Documentation.DocumentVisibility.OWNER_ONLY.name())) {
                documentVisibility = Documentation.DocumentVisibility.OWNER_ONLY;
            }
        }
        documentation.setVisibility(documentVisibility);
        Documentation.DocumentSourceType docSourceType = Documentation.DocumentSourceType.INLINE;
        String artifactAttribute = artifact.getAttribute(APIConstants.DOC_SOURCE_TYPE);
        if (Documentation.DocumentSourceType.URL.name().equals(artifactAttribute)) {
            docSourceType = Documentation.DocumentSourceType.URL;
            documentation.setSourceUrl(artifact.getAttribute(APIConstants.DOC_SOURCE_URL));
        } else if (Documentation.DocumentSourceType.FILE.name().equals(artifactAttribute)) {
            docSourceType = Documentation.DocumentSourceType.FILE;
            documentation.setFilePath(prependWebContextRoot(artifact.getAttribute(APIConstants.DOC_FILE_PATH)));
        } else if (Documentation.DocumentSourceType.MARKDOWN.name().equals(artifactAttribute)) {
            docSourceType = Documentation.DocumentSourceType.MARKDOWN;
        }
        documentation.setSourceType(docSourceType);
        if (documentation.getType() == DocumentationType.OTHER) {
            documentation.setOtherTypeName(artifact.getAttribute(APIConstants.DOC_OTHER_TYPE_NAME));
        }
    } catch (GovernanceException e) {
        throw new APIManagementException("Failed to get documentation from artifact", e);
    }
    return documentation;
}
Also used : DocumentationType(org.wso2.carbon.apimgt.api.model.DocumentationType) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException)

Example 34 with GovernanceException

use of org.wso2.carbon.governance.api.exception.GovernanceException 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 35 with GovernanceException

use of org.wso2.carbon.governance.api.exception.GovernanceException in project carbon-apimgt by wso2.

the class APIUtilTest method testGetDocumentation.

@Test
public void testGetDocumentation() throws GovernanceException, APIManagementException {
    PowerMockito.mockStatic(CarbonUtils.class);
    ServerConfiguration serverConfiguration = Mockito.mock(ServerConfiguration.class);
    Mockito.when(serverConfiguration.getFirstProperty("WebContextRoot")).thenReturn("/abc").thenReturn("/");
    PowerMockito.when(CarbonUtils.getServerConfiguration()).thenReturn(serverConfiguration);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_TYPE)).thenReturn(DocumentationType.HOWTO.getType()).thenReturn(DocumentationType.PUBLIC_FORUM.getType()).thenReturn(DocumentationType.SUPPORT_FORUM.getType()).thenReturn(DocumentationType.API_MESSAGE_FORMAT.getType()).thenReturn(DocumentationType.SAMPLES.getType()).thenReturn(DocumentationType.OTHER.getType());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_NAME)).thenReturn("Docname");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_VISIBILITY)).thenReturn(null).thenReturn(Documentation.DocumentVisibility.API_LEVEL.name()).thenReturn(Documentation.DocumentVisibility.PRIVATE.name()).thenReturn(Documentation.DocumentVisibility.OWNER_ONLY.name());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_SOURCE_TYPE)).thenReturn(Documentation.DocumentSourceType.URL.name()).thenReturn(Documentation.DocumentSourceType.FILE.name());
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_SOURCE_URL)).thenReturn("https://localhost");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_FILE_PATH)).thenReturn("file://abc");
    Mockito.when(genericArtifact.getAttribute(APIConstants.DOC_OTHER_TYPE_NAME)).thenReturn("abc");
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);
    APIUtil.getDocumentation(genericArtifact);
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) ServerConfiguration(org.wso2.carbon.base.ServerConfiguration) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)42 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)32 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)29 API (org.wso2.carbon.apimgt.api.model.API)26 Test (org.junit.Test)19 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)19 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)18 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)17 ArrayList (java.util.ArrayList)15 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)15 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)14 Tier (org.wso2.carbon.apimgt.api.model.Tier)13 HashSet (java.util.HashSet)11 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)10 UserStoreException (org.wso2.carbon.user.api.UserStoreException)10 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)9 Endpoint (org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)9 Resource (org.wso2.carbon.registry.core.Resource)9 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)9 LinkedHashSet (java.util.LinkedHashSet)8