Search in sources :

Example 86 with APIPersistenceException

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

the class APIProviderImpl method deleteAPI.

public void deleteAPI(String apiUuid, String organization) throws APIManagementException {
    boolean isError = false;
    int apiId = -1;
    API api = null;
    // get api object by uuid
    try {
        api = getAPIbyUUID(apiUuid, organization);
    } catch (APIManagementException e) {
        log.error("Error while getting API by uuid for deleting API " + apiUuid + " on organization " + organization);
        log.debug("Following steps will be skipped while deleting API " + apiUuid + "on organization " + organization + " due to api being null. " + "deleting Resource Registration from key managers, deleting on external API stores, " + "event publishing to gateways, logging audit message, extracting API details for " + "the recommendation system. ");
        isError = true;
    }
    // get api id from db
    try {
        apiId = apiMgtDAO.getAPIID(apiUuid);
    } catch (APIManagementException e) {
        log.error("Error while getting API ID from DB for deleting API " + apiUuid + " on organization " + organization, e);
        log.debug("Following steps will be skipped while deleting the API " + apiUuid + " on organization " + organization + "due to api id being null. cleanup workflow tasks of the API, " + "delete event publishing to gateways");
        isError = true;
    }
    // DB delete operations
    if (!isError && api != null) {
        try {
            deleteAPIRevisions(apiUuid, organization);
            deleteAPIFromDB(api);
            if (log.isDebugEnabled()) {
                String logMessage = "API Name: " + api.getId().getApiName() + ", API Version " + api.getId().getVersion() + " successfully removed from the database.";
                log.debug(logMessage);
            }
        } catch (APIManagementException e) {
            log.error("Error while executing API delete operations on DB for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    // Deleting Resource Registration from key managers
    if (api != null && api.getId() != null && api.getId().toString() != null) {
        Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getTenantKeyManagers(tenantDomain);
        for (Map.Entry<String, KeyManagerDto> keyManagerDtoEntry : tenantKeyManagers.entrySet()) {
            KeyManager keyManager = keyManagerDtoEntry.getValue().getKeyManager();
            if (keyManager != null) {
                try {
                    keyManager.deleteRegisteredResourceByAPIId(api.getId().toString());
                    log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the Key Manager " + keyManagerDtoEntry.getKey());
                } catch (APIManagementException e) {
                    log.error("Error while deleting Resource Registration for API " + apiUuid + " on organization " + organization + " in Key Manager " + keyManagerDtoEntry.getKey(), e);
                }
            }
        }
    }
    try {
        GatewayArtifactsMgtDAO.getInstance().deleteGatewayArtifacts(apiUuid);
        log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the gateway artifacts.");
    } catch (APIManagementException e) {
        log.error("Error while executing API delete operation on gateway artifacts for API " + apiUuid, e);
        isError = true;
    }
    try {
        apiPersistenceInstance.deleteAPI(new Organization(organization), apiUuid);
        log.debug("API " + apiUuid + " on organization " + organization + " has successfully removed from the persistence instance.");
    } catch (APIPersistenceException e) {
        log.error("Error while executing API delete operation on persistence instance for API " + apiUuid + " on organization " + organization, e);
        isError = true;
    }
    // Deleting on external API stores
    if (api != null) {
        // gatewayType check is required when API Management is deployed on
        // other servers to avoid synapse
        // Check if there are already published external APIStores.If yes,removing APIs from them.
        Set<APIStore> apiStoreSet;
        try {
            apiStoreSet = getPublishedExternalAPIStores(apiUuid);
            WSO2APIPublisher wso2APIPublisher = new WSO2APIPublisher();
            if (apiStoreSet != null && !apiStoreSet.isEmpty()) {
                for (APIStore store : apiStoreSet) {
                    wso2APIPublisher.deleteFromStore(api.getId(), APIUtil.getExternalAPIStore(store.getName(), tenantId));
                }
            }
        } catch (APIManagementException e) {
            log.error("Error while executing API delete operation on external API stores for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    if (apiId != -1) {
        try {
            cleanUpPendingAPIStateChangeTask(apiId, false);
        } catch (WorkflowException | APIManagementException e) {
            log.error("Error while executing API delete operation on cleanup workflow tasks for API " + apiUuid + " on organization " + organization, e);
            isError = true;
        }
    }
    // Delete event publishing to gateways
    if (api != null && apiId != -1) {
        APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_DELETE.name(), tenantId, tenantDomain, api.getId().getApiName(), apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(), APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
        APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
    } else {
        log.debug("Event has not published to gateways due to API id has failed to retrieve from DB for API " + apiUuid + " on organization " + organization);
    }
    // Logging audit message for API delete
    if (api != null) {
        JSONObject apiLogObject = new JSONObject();
        apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
        apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
        apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
    }
    // Extracting API details for the recommendation system
    if (api != null && recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(api, tenantDomain, APIConstants.DELETE_API);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
    // if one of the above has failed throw an error
    if (isError) {
        throw new APIManagementException("Error while deleting the API " + apiUuid + " on organization " + organization);
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) KeyManagerDto(org.wso2.carbon.apimgt.impl.dto.KeyManagerDto) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) JSONObject(org.json.simple.JSONObject) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) 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) WSO2APIPublisher(org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) KeyManager(org.wso2.carbon.apimgt.api.model.KeyManager) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Example 87 with APIPersistenceException

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

the class APIProviderImpl method addAPIProductRevision.

@Override
public String addAPIProductRevision(APIRevision apiRevision, String organization) throws APIManagementException {
    int revisionCountPerAPI = apiMgtDAO.getRevisionCountByAPI(apiRevision.getApiUUID());
    if (revisionCountPerAPI > 4) {
        String errorMessage = "Maximum number of revisions per API Product has reached. " + "Need to remove stale revision to create a new Revision for API Product with id:" + apiRevision.getApiUUID();
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.MAXIMUM_REVISIONS_REACHED, apiRevision.getApiUUID()));
    }
    int revisionId = apiMgtDAO.getMostRecentRevisionId(apiRevision.getApiUUID()) + 1;
    apiRevision.setId(revisionId);
    APIProductIdentifier apiProductIdentifier = APIUtil.getAPIProductIdentifierFromUUID(apiRevision.getApiUUID());
    if (apiProductIdentifier == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Product with ID: " + apiRevision.getApiUUID(), ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiRevision.getApiUUID()));
    }
    apiProductIdentifier.setUUID(apiRevision.getApiUUID());
    String revisionUUID;
    try {
        revisionUUID = apiPersistenceInstance.addAPIRevision(new Organization(tenantDomain), apiProductIdentifier.getUUID(), revisionId);
    } catch (APIPersistenceException e) {
        String errorMessage = "Failed to add revision registry artifacts";
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.ERROR_CREATING_API_REVISION, apiRevision.getApiUUID()));
    }
    if (StringUtils.isEmpty(revisionUUID)) {
        String errorMessage = "Failed to retrieve revision uuid";
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.API_REVISION_UUID_NOT_FOUND));
    }
    apiRevision.setRevisionUUID(revisionUUID);
    apiMgtDAO.addAPIProductRevision(apiRevision);
    try {
        File artifact = importExportAPI.exportAPIProduct(apiRevision.getApiUUID(), revisionUUID, true, ExportFormat.JSON, false, true, organization);
        gatewayArtifactsMgtDAO.addGatewayAPIArtifactAndMetaData(apiRevision.getApiUUID(), apiProductIdentifier.getName(), apiProductIdentifier.getVersion(), apiRevision.getRevisionUUID(), tenantDomain, APIConstants.API_PRODUCT, artifact);
        if (artifactSaver != null) {
            artifactSaver.saveArtifact(apiRevision.getApiUUID(), apiProductIdentifier.getName(), apiProductIdentifier.getVersion(), apiRevision.getRevisionUUID(), tenantDomain, artifact);
        }
    } catch (APIImportExportException | ArtifactSynchronizerException e) {
        throw new APIManagementException("Error while Store the Revision Artifact", ExceptionCodes.from(ExceptionCodes.API_REVISION_UUID_NOT_FOUND));
    }
    return revisionUUID;
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 88 with APIPersistenceException

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

the class RegistryPersistenceImplTestCase method testAddAPIProduct.

@Test
public void testAddAPIProduct() throws RegistryException, APIPersistenceException, APIManagementException {
    GenericArtifact artifact = PersistenceHelper.getSampleAPIProductArtifact();
    PublisherAPIProduct publisherAPI = new PublisherAPIProduct();
    publisherAPI.setApiProductName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
    publisherAPI.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
    publisherAPI.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
    APIProduct api = APIProductMapper.INSTANCE.toApiProduct(publisherAPI);
    Registry registry = Mockito.mock(UserRegistry.class);
    Resource resource = new ResourceImpl();
    Mockito.when(registry.get(anyString())).thenReturn(resource);
    Tag[] tags = new Tag[0];
    Mockito.when(registry.getTags(anyString())).thenReturn(tags);
    PowerMockito.mockStatic(RegistryPersistenceUtil.class);
    GenericArtifactManager manager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY)).thenReturn(manager);
    PowerMockito.when(RegistryPersistenceUtil.createAPIProductArtifactContent(any(GenericArtifact.class), any(APIProduct.class))).thenReturn(artifact);
    GenericArtifact newArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(manager.newGovernanceArtifact(new QName(publisherAPI.getApiProductName()))).thenReturn(newArtifact);
    Mockito.when(manager.getGenericArtifact(any(String.class))).thenReturn(newArtifact);
    Mockito.doNothing().when(newArtifact).invokeAction("Publish", APIConstants.API_LIFE_CYCLE);
    Organization org = new Organization(SUPER_TENANT_DOMAIN);
    APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(registry, artifact);
    apiPersistenceInstance.addAPIProduct(org, publisherAPI);
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) Matchers.anyString(org.mockito.Matchers.anyString) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) Tag(org.wso2.carbon.registry.core.Tag) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 89 with APIPersistenceException

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

the class RegistryPersistenceImplTestCase method testGetAsyncDefinition.

@Test
public void testGetAsyncDefinition() throws AsyncSpecPersistenceException, RegistryException, APIPersistenceException, APIManagementException {
    Registry registry = Mockito.mock(UserRegistry.class);
    GenericArtifact artifact = PersistenceHelper.getSampleAPIArtifact();
    String apiUUID = artifact.getId();
    PowerMockito.mockStatic(RegistryPersistenceUtil.class);
    GenericArtifactManager manager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY)).thenReturn(manager);
    Mockito.when(manager.getGenericArtifact(apiUUID)).thenReturn(artifact);
    Mockito.doNothing().when(manager).updateGenericArtifact(artifact);
    String apiProviderName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
    apiProviderName = RegistryPersistenceUtil.replaceEmailDomain(apiProviderName);
    String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
    String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
    String definitionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + RegistryPersistenceUtil.replaceEmailDomain(apiProviderName) + RegistryConstants.PATH_SEPARATOR + apiName + RegistryConstants.PATH_SEPARATOR + apiVersion + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
    String apiPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + apiProviderName + RegistryConstants.PATH_SEPARATOR + apiName + RegistryConstants.PATH_SEPARATOR + apiVersion + RegistryConstants.PATH_SEPARATOR + "api";
    PowerMockito.when(GovernanceUtils.getArtifactPath(registry, apiUUID)).thenReturn(apiPath);
    String definition = "{\"asyncapi\":\"2.0.0\",\"info\":{\"description\":\"This is a sample Async API\"}}";
    Organization org = new Organization(SUPER_TENANT_DOMAIN);
    APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(registry, artifact);
    Mockito.when(registry.resourceExists(definitionPath)).thenReturn(true);
    Resource asyncResource = new ResourceImpl();
    asyncResource.setContent(definition.getBytes());
    Mockito.when(registry.get(definitionPath)).thenReturn(asyncResource);
    String def = apiPersistenceInstance.getAsyncDefinition(org, apiUUID);
    Assert.assertEquals("API Async definition does not match", definition, def);
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) Matchers.anyString(org.mockito.Matchers.anyString) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 90 with APIPersistenceException

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

the class RegistryPersistenceImplTestCase method testAddAPI.

@Test
public void testAddAPI() throws RegistryException, APIPersistenceException, APIManagementException {
    GenericArtifact artifact = PersistenceHelper.getSampleAPIArtifact();
    PublisherAPI publisherAPI = new PublisherAPI();
    publisherAPI.setApiName(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME));
    publisherAPI.setProviderName(artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER));
    publisherAPI.setVersion(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION));
    API api = APIMapper.INSTANCE.toApi(publisherAPI);
    Registry registry = Mockito.mock(UserRegistry.class);
    Resource resource = new ResourceImpl();
    Mockito.when(registry.get(anyString())).thenReturn(resource);
    Tag[] tags = new Tag[0];
    Mockito.when(registry.getTags(anyString())).thenReturn(tags);
    PowerMockito.mockStatic(RegistryPersistenceUtil.class);
    GenericArtifactManager manager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY)).thenReturn(manager);
    // add 1 year old timestamp since it is not the latest
    LocalDateTime now = LocalDateTime.now().minusDays(365);
    Timestamp timestamp = Timestamp.valueOf(now);
    PowerMockito.when(RegistryPersistenceUtil.createAPIArtifactContent(any(GenericArtifact.class), any(API.class))).thenReturn(artifact);
    GenericArtifact newArtifact = Mockito.mock(GenericArtifact.class);
    publisherAPI.setVersionTimestamp(timestamp.getTime() + "");
    Mockito.when(manager.newGovernanceArtifact(new QName(api.getId().getApiName()))).thenReturn(newArtifact);
    Organization org = new Organization(SUPER_TENANT_DOMAIN);
    APIPersistence apiPersistenceInstance = new RegistryPersistenceImplWrapper(registry, artifact);
    PublisherAPI returnAPI = apiPersistenceInstance.addAPI(org, publisherAPI);
    Assert.assertEquals(returnAPI.getVersionTimestamp(), String.valueOf(timestamp.getTime()));
}
Also used : LocalDateTime(java.time.LocalDateTime) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) Timestamp(java.sql.Timestamp) ResourceImpl(org.wso2.carbon.registry.core.ResourceImpl) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) Tag(org.wso2.carbon.registry.core.Tag) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)83 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)55 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)49 Registry (org.wso2.carbon.registry.core.Registry)49 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)47 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)44 Resource (org.wso2.carbon.registry.core.Resource)40 API (org.wso2.carbon.apimgt.api.model.API)35 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)34 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)32 Test (org.junit.Test)29 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)27 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)24 ArrayList (java.util.ArrayList)21 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)19 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)18 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)18 GovernanceException (org.wso2.carbon.governance.api.exception.GovernanceException)16