Search in sources :

Example 16 with APIEvent

use of org.wso2.carbon.apimgt.impl.notifier.events.APIEvent in project carbon-apimgt by wso2.

the class ExternallyDeployedApiNotifier method undeployWhenDeleting.

/**
 * Undeploy APIs from external gateway when API is deleted
 *
 * @param apiEvent APIEvent to undeploy APIs from external gateway
 * @throws NotifierException if error occurs when undeploying APIs from external gateway
 */
private void undeployWhenDeleting(APIEvent apiEvent) throws NotifierException {
    Map<String, Environment> gatewayEnvironments = APIUtil.getReadOnlyGatewayEnvironments();
    boolean deleted;
    String apiId = apiEvent.getUuid();
    try {
        List<APIRevisionDeployment> test = apiMgtDAO.getAPIRevisionDeploymentsByApiUUID(apiId);
        for (APIRevisionDeployment deployment : test) {
            String deploymentEnv = deployment.getDeployment();
            if (gatewayEnvironments.containsKey(deploymentEnv)) {
                ExternalGatewayDeployer deployer = ServiceReferenceHolder.getInstance().getExternalGatewayDeployer(gatewayEnvironments.get(deploymentEnv).getProvider());
                if (deployer != null) {
                    try {
                        deleted = deployer.undeploy(apiEvent.getApiName(), apiEvent.getApiVersion(), apiEvent.getApiContext(), gatewayEnvironments.get(deploymentEnv));
                        if (!deleted) {
                            throw new NotifierException("Error while deleting API product from Solace broker");
                        }
                    } catch (DeployerException e) {
                        throw new NotifierException(e.getMessage());
                    }
                }
            }
        }
    } catch (APIManagementException e) {
        throw new NotifierException(e.getMessage());
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ExternalGatewayDeployer(org.wso2.carbon.apimgt.impl.deployer.ExternalGatewayDeployer) Environment(org.wso2.carbon.apimgt.api.model.Environment) DeployerException(org.wso2.carbon.apimgt.impl.deployer.exceptions.DeployerException) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException)

Example 17 with APIEvent

use of org.wso2.carbon.apimgt.impl.notifier.events.APIEvent in project carbon-apimgt by wso2.

the class InMemoryAPIDeployer method unDeployAPI.

private void unDeployAPI(APIGatewayAdmin apiGatewayAdmin, DeployAPIInGatewayEvent gatewayEvent) throws AxisFault {
    if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled()) {
        GatewayAPIDTO gatewayAPIDTO = new GatewayAPIDTO();
        gatewayAPIDTO.setName(gatewayEvent.getName());
        gatewayAPIDTO.setVersion(gatewayEvent.getVersion());
        gatewayAPIDTO.setProvider(gatewayEvent.getProvider());
        gatewayAPIDTO.setTenantDomain(gatewayEvent.getTenantDomain());
        gatewayAPIDTO.setApiId(gatewayEvent.getUuid());
        setClientCertificatesToRemoveIntoGatewayDTO(gatewayAPIDTO);
        if (APIConstants.API_PRODUCT.equals(gatewayEvent.getApiType())) {
            APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(gatewayEvent.getProvider(), gatewayEvent.getName(), gatewayEvent.getVersion());
            Set<APIEvent> associatedApis = gatewayEvent.getAssociatedApis();
            for (APIEvent associatedApi : associatedApis) {
                GatewayUtils.setCustomSequencesToBeRemoved(apiProductIdentifier, associatedApi.getUuid(), gatewayAPIDTO);
                GatewayUtils.setEndpointsToBeRemoved(apiProductIdentifier, associatedApi.getUuid(), gatewayAPIDTO);
            }
        } else {
            API api = new API(new APIIdentifier(gatewayEvent.getProvider(), gatewayEvent.getName(), gatewayEvent.getVersion()));
            if (APIConstants.APITransportType.GRAPHQL.toString().equalsIgnoreCase(gatewayEvent.getApiType())) {
                gatewayAPIDTO.setLocalEntriesToBeRemove(org.wso2.carbon.apimgt.impl.utils.GatewayUtils.addStringToList(gatewayEvent.getUuid().concat("_graphQL"), gatewayAPIDTO.getLocalEntriesToBeRemove()));
                DataHolder.getInstance().getApiToGraphQLSchemaDTOMap().remove(gatewayEvent.getUuid());
            }
            if (APIConstants.APITransportType.WS.toString().equalsIgnoreCase(gatewayEvent.getApiType())) {
                org.wso2.carbon.apimgt.gateway.utils.GatewayUtils.setWebsocketEndpointsToBeRemoved(gatewayAPIDTO, gatewayEvent.getTenantDomain());
            } else {
                GatewayUtils.setEndpointsToBeRemoved(gatewayAPIDTO.getName(), gatewayAPIDTO.getVersion(), gatewayAPIDTO);
            }
            GatewayUtils.setCustomSequencesToBeRemoved(api, gatewayAPIDTO);
        }
        gatewayAPIDTO.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(gatewayEvent.getUuid(), gatewayAPIDTO.getLocalEntriesToBeRemove()));
        apiGatewayAdmin.unDeployAPI(gatewayAPIDTO);
        DataHolder.getInstance().getApiToCertificatesMap().remove(gatewayEvent.getUuid());
        DataHolder.getInstance().removeKeyManagerToAPIMapping(gatewayAPIDTO.getApiId());
    }
}
Also used : GatewayAPIDTO(org.wso2.carbon.apimgt.api.gateway.GatewayAPIDTO) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 18 with APIEvent

use of org.wso2.carbon.apimgt.impl.notifier.events.APIEvent in project carbon-apimgt by wso2.

the class APILoggingImpl method publishLogAPIData.

private void publishLogAPIData(String tenantId, String apiId, String logLevel) throws APIManagementException {
    APIEvent apiEvent = new APIEvent(apiId, logLevel, APIConstants.EventType.UDATE_API_LOG_LEVEL.name(), apiMgtDAO.getAPIContext(apiId));
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
}
Also used : APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent)

Example 19 with APIEvent

use of org.wso2.carbon.apimgt.impl.notifier.events.APIEvent 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 20 with APIEvent

use of org.wso2.carbon.apimgt.impl.notifier.events.APIEvent in project carbon-apimgt by wso2.

the class APIProviderImpl method updateAPIProduct.

@Override
public Map<API, List<APIProductResource>> updateAPIProduct(APIProduct product) throws APIManagementException, FaultGatewaysException {
    Map<API, List<APIProductResource>> apiToProductResourceMapping = new HashMap<>();
    // validate resources and set api identifiers and resource ids to product
    List<APIProductResource> resources = product.getProductResources();
    for (APIProductResource apiProductResource : resources) {
        API api;
        APIProductIdentifier productIdentifier = apiProductResource.getProductIdentifier();
        String apiUUID;
        if (productIdentifier != null) {
            APIIdentifier productAPIIdentifier = apiProductResource.getApiIdentifier();
            String emailReplacedAPIProviderName = APIUtil.replaceEmailDomain(productAPIIdentifier.getProviderName());
            APIIdentifier emailReplacedAPIIdentifier = new APIIdentifier(emailReplacedAPIProviderName, productAPIIdentifier.getApiName(), productAPIIdentifier.getVersion());
            apiUUID = apiMgtDAO.getUUIDFromIdentifier(emailReplacedAPIIdentifier, product.getOrganization());
            api = getAPIbyUUID(apiUUID, tenantDomain);
        } else {
            apiUUID = apiProductResource.getApiId();
            api = getAPIbyUUID(apiUUID, tenantDomain);
        }
        if (api.getSwaggerDefinition() != null) {
            api.setSwaggerDefinition(getOpenAPIDefinition(apiUUID, tenantDomain));
        }
        if (!apiToProductResourceMapping.containsKey(api)) {
            apiToProductResourceMapping.put(api, new ArrayList<>());
        }
        List<APIProductResource> apiProductResources = apiToProductResourceMapping.get(api);
        apiProductResources.add(apiProductResource);
        // if API does not exist, getLightweightAPIByUUID() method throws exception. so no need to handle NULL
        apiProductResource.setApiIdentifier(api.getId());
        apiProductResource.setProductIdentifier(product.getId());
        if (api.isAdvertiseOnly()) {
            apiProductResource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
        } else {
            apiProductResource.setEndpointConfig(api.getEndpointConfig());
        }
        apiProductResource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        URITemplate uriTemplate = apiProductResource.getUriTemplate();
        Map<String, URITemplate> templateMap = apiMgtDAO.getURITemplatesForAPI(api);
        if (uriTemplate == null) {
        // TODO handle if no resource is defined. either throw an error or add all the resources of that API
        // to the product
        } else {
            String key = uriTemplate.getHTTPVerb() + ":" + uriTemplate.getUriTemplate();
            if (templateMap.containsKey(key)) {
                // Since the template ID is not set from the request, we manually set it.
                uriTemplate.setId(templateMap.get(key).getId());
            } else {
                throw new APIManagementException("API with id " + apiProductResource.getApiId() + " does not have a resource " + uriTemplate.getUriTemplate() + " with http method " + uriTemplate.getHTTPVerb());
            }
        }
    }
    APIProduct oldApi = getAPIProductbyUUID(product.getUuid(), CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
    Gson gson = new Gson();
    Map<String, String> oldMonetizationProperties = gson.fromJson(oldApi.getMonetizationProperties().toString(), HashMap.class);
    if (oldMonetizationProperties != null && !oldMonetizationProperties.isEmpty()) {
        Map<String, String> newMonetizationProperties = gson.fromJson(product.getMonetizationProperties().toString(), HashMap.class);
        if (newMonetizationProperties != null) {
            for (Map.Entry<String, String> entry : oldMonetizationProperties.entrySet()) {
                String newValue = newMonetizationProperties.get(entry.getKey());
                if (StringUtils.isAllBlank(newValue)) {
                    newMonetizationProperties.put(entry.getKey(), entry.getValue());
                }
            }
            JSONParser parser = new JSONParser();
            try {
                JSONObject jsonObj = (JSONObject) parser.parse(gson.toJson(newMonetizationProperties));
                product.setMonetizationProperties(jsonObj);
            } catch (ParseException e) {
                throw new APIManagementException("Error when parsing monetization properties ", e);
            }
        }
    }
    invalidateResourceCache(product.getContext(), product.getId().getVersion(), Collections.EMPTY_SET);
    // todo : check whether permissions need to be updated and pass it along
    updateApiProductArtifact(product, true, true);
    apiMgtDAO.updateAPIProduct(product, userNameWithoutChange);
    int productId = apiMgtDAO.getAPIProductId(product.getId());
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, product.getId().getName(), productId, product.getId().getUUID(), product.getId().getVersion(), product.getType(), product.getContext(), product.getId().getProviderName(), APIConstants.LC_PUBLISH_LC_STATE);
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
    return apiToProductResourceMapping;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Gson(com.google.gson.Gson) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) 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) ArrayList(java.util.ArrayList) List(java.util.List) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Aggregations

APIEvent (org.wso2.carbon.apimgt.impl.notifier.events.APIEvent)15 API (org.wso2.carbon.apimgt.api.model.API)8 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)7 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)6 APIEvent (org.wso2.carbon.apimgt.core.models.events.APIEvent)6 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)5 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)5 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 TreeMap (java.util.TreeMap)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 JSONObject (org.json.simple.JSONObject)4 Gson (com.google.gson.Gson)3 JSONParser (org.json.simple.parser.JSONParser)3 ParseException (org.json.simple.parser.ParseException)3 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)3 HashSet (java.util.HashSet)2 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)2 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)2