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());
}
}
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());
}
}
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());
}
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);
}
}
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;
}
Aggregations