Search in sources :

Example 1 with AsyncSpecPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method getAsyncDefinition.

@Override
public String getAsyncDefinition(Organization org, String apiId) throws AsyncSpecPersistenceException {
    String apiTenantDomain = org.getName();
    String definition = null;
    boolean tenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(apiTenantDomain);
        Registry registryType = holder.getRegistry();
        tenantFlowStarted = holder.isTenantFlowStarted;
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registryType, APIConstants.API_KEY);
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
        if (apiArtifact != null) {
            String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
            String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
            String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
            String apiPath = GovernanceUtils.getArtifactPath(registryType, apiId);
            int prependIndex = apiPath.lastIndexOf("/api");
            String apiSourcePath = apiPath.substring(0, prependIndex);
            String definitionPath = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
            if (registryType.resourceExists(definitionPath)) {
                Resource apiDocResource = registryType.get(definitionPath);
                definition = new String((byte[]) apiDocResource.getContent(), Charset.defaultCharset());
                return definition;
            }
        }
    } catch (RegistryException | APIPersistenceException e) {
        String msg = "Failed to get specification of API : " + apiId;
        throw new AsyncSpecPersistenceException(msg, e);
    } finally {
        if (tenantFlowStarted) {
            RegistryPersistenceUtil.endTenantFlow();
        }
    }
    return definition;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 2 with AsyncSpecPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method saveAsyncDefinition.

@Override
public void saveAsyncDefinition(Organization org, String apiId, String apiDefinition) throws AsyncSpecPersistenceException {
    boolean isTenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when deleting API " + apiId;
            log.error(errorMessage);
            throw new AsyncSpecPersistenceException(errorMessage);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
        String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        String visibility = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY);
        String visibleRoles = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES);
        String apiPath = GovernanceUtils.getArtifactPath(registry, apiId);
        int prependIndex = apiPath.lastIndexOf("/api");
        String apiSourcePath = apiPath.substring(0, prependIndex);
        String resourcePath = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
        Resource resource;
        if (!registry.resourceExists(resourcePath)) {
            resource = registry.newResource();
        } else {
            resource = registry.get(resourcePath);
        }
        resource.setContent(apiDefinition);
        // add a constant for app.json
        resource.setMediaType(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
        registry.put(resourcePath, resource);
        String[] visibleRolesArr = null;
        if (visibleRoles != null) {
            visibleRolesArr = visibleRoles.split(",");
        }
        RegistryPersistenceUtil.clearResourcePermissions(resourcePath, new APIIdentifier(apiProviderName, apiName, apiVersion), ((UserRegistry) registry).getTenantId());
        RegistryPersistenceUtil.setResourcePermissions(apiProviderName, visibility, visibleRolesArr, resourcePath);
    } catch (RegistryException | APIPersistenceException | APIManagementException e) {
        throw new AsyncSpecPersistenceException("Error while adding AsyncApi Definition for " + apiId, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 3 with AsyncSpecPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException in project carbon-apimgt by wso2.

the class APIProviderImpl method getAPIbyUUID.

@Override
public API getAPIbyUUID(String uuid, String organization) throws APIManagementException {
    Organization org = new Organization(organization);
    try {
        PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, uuid);
        if (publisherAPI != null) {
            API api = APIMapper.INSTANCE.toApi(publisherAPI);
            APIIdentifier apiIdentifier = api.getId();
            apiIdentifier.setUuid(uuid);
            api.setId(apiIdentifier);
            checkAccessControlPermission(userNameWithoutChange, api.getAccessControl(), api.getAccessControlRoles());
            // ///////////////// Do processing on the data object//////////
            populateRevisionInformation(api, uuid);
            populateAPIInformation(uuid, organization, api);
            loadMediationPoliciesToAPI(api, organization);
            populateAPIStatus(api);
            populateDefaultVersion(api);
            return api;
        } else {
            String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Failed to get API", e);
    } catch (OASPersistenceException e) {
        throw new APIManagementException("Error while retrieving the OAS definition", e);
    } catch (ParseException e) {
        throw new APIManagementException("Error while parsing the OAS definition", e);
    } catch (AsyncSpecPersistenceException e) {
        throw new APIManagementException("Error while retrieving the Async API definition", e);
    }
}
Also used : AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) OASPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.OASPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ParseException(org.json.simple.parser.ParseException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Example 4 with AsyncSpecPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateAPIInformation.

protected void populateAPIInformation(String uuid, String organization, API api) throws APIManagementException, OASPersistenceException, ParseException, AsyncSpecPersistenceException {
    Organization org = new Organization(organization);
    // UUID
    if (api.getUuid() == null) {
        api.setUuid(uuid);
    }
    api.setOrganization(organization);
    // environment
    String environmentString = null;
    if (api.getEnvironments() != null) {
        environmentString = String.join(",", api.getEnvironments());
    }
    api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIIdentifier apiId = api.getId();
    WorkflowDTO workflow;
    String currentApiUuid = uuid;
    if (api.isRevision() && api.getRevisionedApiId() != null) {
        currentApiUuid = api.getRevisionedApiId();
    }
    workflow = APIUtil.getAPIWorkflowStatus(currentApiUuid, WF_TYPE_AM_API_STATE);
    if (workflow != null) {
        WorkflowStatus status = workflow.getStatus();
        api.setWorkflowStatus(status.toString());
    }
    // TODO try to use a single query to get info from db
    int internalId = apiMgtDAO.getAPIID(currentApiUuid);
    apiId.setId(internalId);
    apiMgtDAO.setServiceStatusInfoToAPI(api, internalId);
    // api level tier
    String apiLevelTier;
    if (api.isRevision()) {
        apiLevelTier = apiMgtDAO.getAPILevelTier(api.getRevisionedApiId(), api.getUuid());
    } else {
        apiLevelTier = apiMgtDAO.getAPILevelTier(internalId);
    }
    api.setApiLevelPolicy(apiLevelTier);
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = api.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (api.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(APIUtil.getInternalOrganizationId(organization));
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, api.getId().getApiName());
    api.setAvailableTiers(availableTier);
    // Scopes
    Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(currentApiUuid, organization);
    api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
    // templates
    String resourceConfigsString;
    if (api.getSwaggerDefinition() != null) {
        resourceConfigsString = api.getSwaggerDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
    }
    api.setSwaggerDefinition(resourceConfigsString);
    if (resourceConfigsString == null) {
        if (api.getAsyncApiDefinition() != null) {
            resourceConfigsString = api.getAsyncApiDefinition();
        } else {
            resourceConfigsString = apiPersistenceInstance.getAsyncDefinition(org, uuid);
        }
        api.setAsyncApiDefinition(resourceConfigsString);
    }
    if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
        api.setGraphQLSchema(getGraphqlSchemaDefinition(uuid, organization));
    }
    JSONParser jsonParser = new JSONParser();
    JSONObject paths = null;
    if (resourceConfigsString != null) {
        JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
        paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
    }
    Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
    for (URITemplate uriTemplate : uriTemplates) {
        String uTemplate = uriTemplate.getUriTemplate();
        String method = uriTemplate.getHTTPVerb();
        List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
        List<Scope> newTemplateScopes = new ArrayList<>();
        if (!oldTemplateScopes.isEmpty()) {
            for (Scope templateScope : oldTemplateScopes) {
                Scope scope = scopeToKeyMapping.get(templateScope.getKey());
                newTemplateScopes.add(scope);
            }
        }
        uriTemplate.addAllScopes(newTemplateScopes);
        uriTemplate.setResourceURI(api.getUrl());
        uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
        // AWS Lambda: set arn & timeout to URI template
        if (paths != null) {
            JSONObject path = (JSONObject) paths.get(uTemplate);
            if (path != null) {
                JSONObject operation = (JSONObject) path.get(method.toLowerCase());
                if (operation != null) {
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                        uriTemplate.setAmznResourceName((String) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                    }
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                        uriTemplate.setAmznResourceTimeout(((Long) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                    }
                }
            }
        }
    }
    if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
        for (URITemplate template : uriTemplates) {
            template.setMediationScript(template.getAggregatedMediationScript());
        }
    }
    api.setUriTemplates(uriTemplates);
    // CORS . if null is returned, set default config from the configuration
    if (api.getCorsConfiguration() == null) {
        api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = api.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // 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
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            // todo-category: optimize this loop with breaks
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        api.setApiCategories(categoryList);
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 5 with AsyncSpecPersistenceException

use of org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException in project carbon-apimgt by wso2.

the class APIProviderImpl method saveAsyncApiDefinition.

@Override
public void saveAsyncApiDefinition(API api, String jsonText) throws APIManagementException {
    String apiId;
    String organization = api.getOrganization();
    if (api.getUuid() != null) {
        apiId = api.getUuid();
    } else if (api.getId().getUUID() != null) {
        apiId = api.getId().getUUID();
    } else {
        apiId = apiMgtDAO.getUUIDFromIdentifier(api.getId().getProviderName(), api.getId().getApiName(), api.getId().getVersion(), organization);
    }
    try {
        apiPersistenceInstance.saveAsyncDefinition(new Organization(organization), apiId, jsonText);
    } catch (AsyncSpecPersistenceException e) {
        throw new APIManagementException("Error while persisting Async API definition ", e);
    }
}
Also used : AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Aggregations

Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)4 AsyncSpecPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException)4 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)3 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)3 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)3 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)3 Registry (org.wso2.carbon.registry.core.Registry)3 Resource (org.wso2.carbon.registry.core.Resource)3 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)3 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)2 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 LinkedHashSet (java.util.LinkedHashSet)1 JSONObject (org.json.simple.JSONObject)1 JSONParser (org.json.simple.parser.JSONParser)1 ParseException (org.json.simple.parser.ParseException)1 Test (org.junit.Test)1 Matchers.anyString (org.mockito.Matchers.anyString)1 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)1