Search in sources :

Example 26 with GovernanceException

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

Example 27 with GovernanceException

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

the class APIProviderImpl method getAPILifeCycleStatus.

@Override
public String getAPILifeCycleStatus(APIIdentifier apiIdentifier) throws APIManagementException {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(this.tenantDomain, true);
        GenericArtifact apiArtifact = APIUtil.getAPIArtifact(apiIdentifier, registry);
        if (apiArtifact == null) {
            String errorMessage = "API artifact is null when retrieving lifecycle status of API " + apiIdentifier.getApiName();
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        return apiArtifact.getLifecycleState();
    } catch (GovernanceException e) {
        handleException("Failed to get the life cycle status : " + e.getMessage(), e);
        return null;
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException)

Example 28 with GovernanceException

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

the class APIUtil method searchAPIsByDoc.

/**
 * Search Apis by Doc Content
 *
 * @param registry     - Registry which is searched
 * @param tenantID     - Tenant id of logged in domain
 * @param username     - Logged in username
 * @param searchTerm   - Search value for doc
 * @param searchClient - Search client
 * @return - Documentation to APIs map
 * @throws APIManagementException - If failed to get ArtifactManager for given tenant
 */
public static Map<Documentation, API> searchAPIsByDoc(Registry registry, int tenantID, String username, String searchTerm, String searchClient) throws APIManagementException {
    Map<Documentation, API> apiDocMap = new HashMap<Documentation, API>();
    try {
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
        GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        GenericArtifactManager docArtifactManager = APIUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        if (docArtifactManager == null) {
            String errorMessage = "Doc artifact manager is null when searching APIs by docs in tenant ID " + tenantID;
            log.error(errorMessage);
            throw new APIManagementException(errorMessage);
        }
        SolrClient client = SolrClient.getInstance();
        Map<String, String> fields = new HashMap<String, String>();
        fields.put(APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, "*" + APIConstants.API_ROOT_LOCATION + "*");
        fields.put(APIConstants.DOCUMENTATION_SEARCH_MEDIA_TYPE_FIELD, "*");
        if (tenantID == -1) {
            tenantID = MultitenantConstants.SUPER_TENANT_ID;
        }
        // PaginationContext.init(0, 10000, "ASC", APIConstants.DOCUMENTATION_SEARCH_PATH_FIELD, Integer.MAX_VALUE);
        SolrDocumentList documentList = client.query(searchTerm, tenantID, fields);
        org.wso2.carbon.user.api.AuthorizationManager manager = ServiceReferenceHolder.getInstance().getRealmService().getTenantUserRealm(tenantID).getAuthorizationManager();
        username = MultitenantUtils.getTenantAwareUsername(username);
        for (SolrDocument document : documentList) {
            String filePath = (String) document.getFieldValue("path_s");
            String fileName = (String) document.getFieldValue("resourceName_s");
            int index = filePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
            filePath = filePath.substring(index);
            API api = null;
            Documentation doc = null;
            boolean isAuthorized;
            int indexOfContents = filePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
            String documentationPath = filePath.substring(0, indexOfContents) + fileName;
            String path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + documentationPath);
            if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
                isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
            } else {
                isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
            }
            if (isAuthorized) {
                Resource docResource = registry.get(documentationPath);
                String docArtifactId = docResource.getUUID();
                if (docArtifactId != null) {
                    GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
                    doc = APIUtil.getDocumentation(docArtifact);
                }
                int indexOfDocumentation = filePath.indexOf(APIConstants.DOCUMENTATION_KEY);
                String apiPath = documentationPath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
                path = RegistryUtils.getAbsolutePath(RegistryContext.getBaseInstance(), APIUtil.getMountedPath(RegistryContext.getBaseInstance(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH) + apiPath);
                if (CarbonConstants.REGISTRY_ANONNYMOUS_USERNAME.equalsIgnoreCase(username)) {
                    isAuthorized = manager.isRoleAuthorized(APIConstants.ANONYMOUS_ROLE, path, ActionConstants.GET);
                } else {
                    isAuthorized = manager.isUserAuthorized(username, path, ActionConstants.GET);
                }
                if (isAuthorized) {
                    Resource resource = registry.get(apiPath);
                    String apiArtifactId = resource.getUUID();
                    if (apiArtifactId != null) {
                        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiArtifactId);
                        api = APIUtil.getAPI(apiArtifact, registry);
                    } else {
                        throw new GovernanceException("artifact id is null of " + apiPath);
                    }
                }
            }
            if (doc != null && api != null) {
                if (APIConstants.STORE_CLIENT.equals(searchClient)) {
                    if (APIConstants.PUBLISHED.equals(api.getStatus()) || APIConstants.PROTOTYPED.equals(api.getStatus())) {
                        apiDocMap.put(doc, api);
                    }
                } else {
                    apiDocMap.put(doc, api);
                }
            }
        }
    } catch (IndexerException e) {
        handleException("Failed to search APIs with type Doc", e);
    } catch (RegistryException e) {
        handleException("Failed to search APIs with type Doc", e);
    } catch (UserStoreException e) {
        handleException("Failed to search APIs with type Doc", e);
    }
    return apiDocMap;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) 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) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) SolrDocumentList(org.apache.solr.common.SolrDocumentList) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) SolrDocument(org.apache.solr.common.SolrDocument) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SolrClient(org.wso2.carbon.registry.indexing.solr.SolrClient) UserStoreException(org.wso2.carbon.user.api.UserStoreException) API(org.wso2.carbon.apimgt.api.model.API) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException)

Example 29 with GovernanceException

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

the class APIUtil method getAPIInformation.

/**
 * This method used to get API minimum information from governance artifact
 *
 * @param artifact API artifact
 * @param registry Registry
 * @return API
 * @throws APIManagementException if failed to get API from artifact
 */
public static API getAPIInformation(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        api = new API(new APIIdentifier(providerName, apiName, apiVersion, artifact.getId()));
        // set uuid
        api.setUUID(artifact.getId());
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
        api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
        api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        api.setEnvironments(extractEnvironmentsForAPI(environments));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        api.setLastUpdated(registry.get(artifactPath).getLastModified());
        api.setCreatedTime(String.valueOf(registry.get(artifactPath).getCreatedTime().getTime()));
    } catch (GovernanceException e) {
        String msg = "Failed to get API from artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 30 with GovernanceException

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

the class APIUtil method getAPI.

public static API getAPI(GovernanceArtifact artifact) throws APIManagementException {
    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion);
        api = new API(apiIdentifier);
        int apiId = ApiMgtDAO.getInstance().getAPIID(artifact.getId());
        if (apiId == -1) {
            return null;
        }
        // set uuid
        api.setUUID(artifact.getId());
        api.setRating(getAverageRating(apiId));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
        api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
        api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
        api.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
        } catch (NumberFormatException e) {
        // ignore
        }
        api.setCacheTimeout(cacheTimeout);
        String apiLevelTier = ApiMgtDAO.getInstance().getAPILevelTier(apiId);
        api.setApiLevelPolicy(apiLevelTier);
        Set<Tier> availablePolicy = new HashSet<Tier>();
        String[] subscriptionPolicy = ApiMgtDAO.getInstance().getPolicyNames(PolicyConstants.POLICY_LEVEL_SUB, replaceEmailDomainBack(providerName));
        List<String> definedPolicyNames = Arrays.asList(subscriptionPolicy);
        String policies = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        if (policies != null && !"".equals(policies)) {
            String[] policyNames = policies.split("\\|\\|");
            for (String policyName : policyNames) {
                if (definedPolicyNames.contains(policyName) || APIConstants.UNLIMITED_TIER.equals(policyName)) {
                    Tier p = new Tier(policyName);
                    availablePolicy.add(p);
                } else {
                    log.warn("Unknown policy: " + policyName + " found on API: " + apiName);
                }
            }
        }
        api.addAvailableTiers(availablePolicy);
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        api.setMonetizationCategory(getAPIMonetizationCategory(availablePolicy, tenantDomainName));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        api.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        ArrayList<URITemplate> urlPatternsList;
        urlPatternsList = ApiMgtDAO.getInstance().getAllURITemplates(api.getContext(), api.getId().getVersion());
        Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);
        for (URITemplate uriTemplate : uriTemplates) {
            uriTemplate.setResourceURI(api.getUrl());
            uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
        }
        api.setUriTemplates(uriTemplates);
        String environments = artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS);
        api.setEnvironments(extractEnvironmentsForAPI(environments));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        // non empty URLs to API object
        try {
            api.setEnvironmentList(extractEnvironmentListForAPI(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
        } catch (ParseException e) {
            String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        } catch (ClassCastException e) {
            String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        }
    } catch (GovernanceException e) {
        String msg = "Failed to get API from artifact ";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

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